UNPKG

1.35 MBJavaScriptView Raw
1(function webpackUniversalModuleDefinition(root, factory) {
2 if(typeof exports === 'object' && typeof module === 'object')
3 module.exports = factory();
4 else if(typeof define === 'function' && define.amd)
5 define([], factory);
6 else if(typeof exports === 'object')
7 exports["AV"] = factory();
8 else
9 root["AV"] = factory();
10})(typeof self !== 'undefined' ? self : this, function() {
11return /******/ (function(modules) { // webpackBootstrap
12/******/ // The module cache
13/******/ var installedModules = {};
14/******/
15/******/ // The require function
16/******/ function __webpack_require__(moduleId) {
17/******/
18/******/ // Check if module is in cache
19/******/ if(installedModules[moduleId]) {
20/******/ return installedModules[moduleId].exports;
21/******/ }
22/******/ // Create a new module (and put it into the cache)
23/******/ var module = installedModules[moduleId] = {
24/******/ i: moduleId,
25/******/ l: false,
26/******/ exports: {}
27/******/ };
28/******/
29/******/ // Execute the module function
30/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
31/******/
32/******/ // Flag the module as loaded
33/******/ module.l = true;
34/******/
35/******/ // Return the exports of the module
36/******/ return module.exports;
37/******/ }
38/******/
39/******/
40/******/ // expose the modules object (__webpack_modules__)
41/******/ __webpack_require__.m = modules;
42/******/
43/******/ // expose the module cache
44/******/ __webpack_require__.c = installedModules;
45/******/
46/******/ // define getter function for harmony exports
47/******/ __webpack_require__.d = function(exports, name, getter) {
48/******/ if(!__webpack_require__.o(exports, name)) {
49/******/ Object.defineProperty(exports, name, {
50/******/ configurable: false,
51/******/ enumerable: true,
52/******/ get: getter
53/******/ });
54/******/ }
55/******/ };
56/******/
57/******/ // getDefaultExport function for compatibility with non-harmony modules
58/******/ __webpack_require__.n = function(module) {
59/******/ var getter = module && module.__esModule ?
60/******/ function getDefault() { return module['default']; } :
61/******/ function getModuleExports() { return module; };
62/******/ __webpack_require__.d(getter, 'a', getter);
63/******/ return getter;
64/******/ };
65/******/
66/******/ // Object.prototype.hasOwnProperty.call
67/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
68/******/
69/******/ // __webpack_public_path__
70/******/ __webpack_require__.p = "";
71/******/
72/******/ // Load entry module and return exports
73/******/ return __webpack_require__(__webpack_require__.s = 212);
74/******/ })
75/************************************************************************/
76/******/ ([
77/* 0 */
78/***/ (function(module, __webpack_exports__, __webpack_require__) {
79
80"use strict";
81Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
82/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__index_default_js__ = __webpack_require__(229);
83/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return __WEBPACK_IMPORTED_MODULE_0__index_default_js__["a"]; });
84/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__index_js__ = __webpack_require__(92);
85/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "VERSION", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["VERSION"]; });
86/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "restArguments", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["restArguments"]; });
87/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isObject", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isObject"]; });
88/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isNull", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isNull"]; });
89/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isUndefined", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isUndefined"]; });
90/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isBoolean", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isBoolean"]; });
91/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isElement", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isElement"]; });
92/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isString", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isString"]; });
93/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isNumber", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isNumber"]; });
94/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isDate", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isDate"]; });
95/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isRegExp", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isRegExp"]; });
96/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isError", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isError"]; });
97/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isSymbol", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isSymbol"]; });
98/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isArrayBuffer", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isArrayBuffer"]; });
99/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isDataView", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isDataView"]; });
100/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isArray", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isArray"]; });
101/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isFunction", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isFunction"]; });
102/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isArguments", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isArguments"]; });
103/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isFinite", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isFinite"]; });
104/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isNaN", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isNaN"]; });
105/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isTypedArray", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isTypedArray"]; });
106/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isEmpty", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isEmpty"]; });
107/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isMatch", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isMatch"]; });
108/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isEqual", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isEqual"]; });
109/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isMap", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isMap"]; });
110/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isWeakMap", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isWeakMap"]; });
111/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isSet", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isSet"]; });
112/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isWeakSet", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isWeakSet"]; });
113/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "keys", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["keys"]; });
114/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "allKeys", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["allKeys"]; });
115/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "values", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["values"]; });
116/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "pairs", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["pairs"]; });
117/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "invert", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["invert"]; });
118/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "functions", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["functions"]; });
119/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "methods", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["methods"]; });
120/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "extend", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["extend"]; });
121/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "extendOwn", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["extendOwn"]; });
122/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "assign", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["assign"]; });
123/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "defaults", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["defaults"]; });
124/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "create", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["create"]; });
125/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "clone", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["clone"]; });
126/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "tap", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["tap"]; });
127/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "get", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["get"]; });
128/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "has", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["has"]; });
129/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "mapObject", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["mapObject"]; });
130/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "identity", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["identity"]; });
131/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "constant", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["constant"]; });
132/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "noop", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["noop"]; });
133/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "toPath", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["toPath"]; });
134/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "property", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["property"]; });
135/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "propertyOf", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["propertyOf"]; });
136/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "matcher", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["matcher"]; });
137/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "matches", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["matches"]; });
138/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "times", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["times"]; });
139/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "random", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["random"]; });
140/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "now", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["now"]; });
141/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "escape", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["escape"]; });
142/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "unescape", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["unescape"]; });
143/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "templateSettings", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["templateSettings"]; });
144/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "template", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["template"]; });
145/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "result", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["result"]; });
146/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "uniqueId", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["uniqueId"]; });
147/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "chain", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["chain"]; });
148/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "iteratee", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["iteratee"]; });
149/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "partial", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["partial"]; });
150/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "bind", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["bind"]; });
151/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "bindAll", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["bindAll"]; });
152/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "memoize", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["memoize"]; });
153/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "delay", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["delay"]; });
154/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "defer", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["defer"]; });
155/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "throttle", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["throttle"]; });
156/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "debounce", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["debounce"]; });
157/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "wrap", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["wrap"]; });
158/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "negate", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["negate"]; });
159/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "compose", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["compose"]; });
160/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "after", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["after"]; });
161/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "before", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["before"]; });
162/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "once", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["once"]; });
163/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "findKey", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["findKey"]; });
164/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "findIndex", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["findIndex"]; });
165/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "findLastIndex", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["findLastIndex"]; });
166/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "sortedIndex", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["sortedIndex"]; });
167/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "indexOf", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["indexOf"]; });
168/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "lastIndexOf", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["lastIndexOf"]; });
169/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "find", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["find"]; });
170/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "detect", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["detect"]; });
171/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "findWhere", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["findWhere"]; });
172/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "each", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["each"]; });
173/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "forEach", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["forEach"]; });
174/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "map", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["map"]; });
175/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "collect", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["collect"]; });
176/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "reduce", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["reduce"]; });
177/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "foldl", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["foldl"]; });
178/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "inject", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["inject"]; });
179/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "reduceRight", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["reduceRight"]; });
180/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "foldr", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["foldr"]; });
181/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "filter", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["filter"]; });
182/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "select", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["select"]; });
183/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "reject", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["reject"]; });
184/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "every", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["every"]; });
185/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "all", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["all"]; });
186/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "some", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["some"]; });
187/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "any", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["any"]; });
188/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "contains", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["contains"]; });
189/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "includes", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["includes"]; });
190/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "include", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["include"]; });
191/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "invoke", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["invoke"]; });
192/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "pluck", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["pluck"]; });
193/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "where", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["where"]; });
194/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "max", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["max"]; });
195/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "min", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["min"]; });
196/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "shuffle", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["shuffle"]; });
197/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "sample", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["sample"]; });
198/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "sortBy", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["sortBy"]; });
199/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "groupBy", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["groupBy"]; });
200/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "indexBy", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["indexBy"]; });
201/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "countBy", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["countBy"]; });
202/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["partition"]; });
203/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "toArray", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["toArray"]; });
204/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "size", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["size"]; });
205/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "pick", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["pick"]; });
206/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "omit", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["omit"]; });
207/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "first", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["first"]; });
208/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "head", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["head"]; });
209/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "take", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["take"]; });
210/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "initial", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["initial"]; });
211/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "last", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["last"]; });
212/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "rest", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["rest"]; });
213/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "tail", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["tail"]; });
214/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "drop", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["drop"]; });
215/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "compact", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["compact"]; });
216/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "flatten", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["flatten"]; });
217/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "without", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["without"]; });
218/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "uniq", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["uniq"]; });
219/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "unique", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["unique"]; });
220/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "union", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["union"]; });
221/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "intersection", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["intersection"]; });
222/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "difference", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["difference"]; });
223/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "unzip", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["unzip"]; });
224/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "transpose", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["transpose"]; });
225/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["zip"]; });
226/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "object", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["object"]; });
227/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "range", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["range"]; });
228/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "chunk", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["chunk"]; });
229/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "mixin", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["mixin"]; });
230// ESM Exports
231// ===========
232// This module is the package entry point for ES module users. In other words,
233// it is the module they are interfacing with when they import from the whole
234// package instead of from a submodule, like this:
235//
236// ```js
237// import { map } from 'underscore';
238// ```
239//
240// The difference with `./index-default`, which is the package entry point for
241// CommonJS, AMD and UMD users, is purely technical. In ES modules, named and
242// default exports are considered to be siblings, so when you have a default
243// export, its properties are not automatically available as named exports. For
244// this reason, we re-export the named exports in addition to providing the same
245// default export as in `./index-default`.
246
247
248
249
250/***/ }),
251/* 1 */
252/***/ (function(module, exports) {
253
254var core = module.exports = { version: '2.6.9' };
255if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
256
257
258/***/ }),
259/* 2 */
260/***/ (function(module, __webpack_exports__, __webpack_require__) {
261
262"use strict";
263/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return VERSION; });
264/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return root; });
265/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ArrayProto; });
266/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return ObjProto; });
267/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return SymbolProto; });
268/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return push; });
269/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return slice; });
270/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "t", function() { return toString; });
271/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return hasOwnProperty; });
272/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return supportsArrayBuffer; });
273/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "s", function() { return supportsDataView; });
274/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return nativeIsArray; });
275/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return nativeKeys; });
276/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return nativeCreate; });
277/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return nativeIsView; });
278/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return _isNaN; });
279/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return _isFinite; });
280/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return hasEnumBug; });
281/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return nonEnumerableProps; });
282/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return MAX_ARRAY_INDEX; });
283// Current version.
284var VERSION = '1.12.1';
285
286// Establish the root object, `window` (`self`) in the browser, `global`
287// on the server, or `this` in some virtual machines. We use `self`
288// instead of `window` for `WebWorker` support.
289var root = typeof self == 'object' && self.self === self && self ||
290 typeof global == 'object' && global.global === global && global ||
291 Function('return this')() ||
292 {};
293
294// Save bytes in the minified (but not gzipped) version:
295var ArrayProto = Array.prototype, ObjProto = Object.prototype;
296var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;
297
298// Create quick reference variables for speed access to core prototypes.
299var push = ArrayProto.push,
300 slice = ArrayProto.slice,
301 toString = ObjProto.toString,
302 hasOwnProperty = ObjProto.hasOwnProperty;
303
304// Modern feature detection.
305var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined',
306 supportsDataView = typeof DataView !== 'undefined';
307
308// All **ECMAScript 5+** native function implementations that we hope to use
309// are declared here.
310var nativeIsArray = Array.isArray,
311 nativeKeys = Object.keys,
312 nativeCreate = Object.create,
313 nativeIsView = supportsArrayBuffer && ArrayBuffer.isView;
314
315// Create references to these builtin functions because we override them.
316var _isNaN = isNaN,
317 _isFinite = isFinite;
318
319// Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
320var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
321var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
322 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
323
324// The largest integer that can be represented exactly.
325var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
326
327/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(66)))
328
329/***/ }),
330/* 3 */
331/***/ (function(module, exports, __webpack_require__) {
332
333module.exports = { "default": __webpack_require__(216), __esModule: true };
334
335/***/ }),
336/* 4 */
337/***/ (function(module, exports, __webpack_require__) {
338
339var global = __webpack_require__(5);
340var core = __webpack_require__(1);
341var ctx = __webpack_require__(22);
342var hide = __webpack_require__(24);
343var has = __webpack_require__(25);
344var PROTOTYPE = 'prototype';
345
346var $export = function (type, name, source) {
347 var IS_FORCED = type & $export.F;
348 var IS_GLOBAL = type & $export.G;
349 var IS_STATIC = type & $export.S;
350 var IS_PROTO = type & $export.P;
351 var IS_BIND = type & $export.B;
352 var IS_WRAP = type & $export.W;
353 var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
354 var expProto = exports[PROTOTYPE];
355 var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
356 var key, own, out;
357 if (IS_GLOBAL) source = name;
358 for (key in source) {
359 // contains in native
360 own = !IS_FORCED && target && target[key] !== undefined;
361 if (own && has(exports, key)) continue;
362 // export native or passed
363 out = own ? target[key] : source[key];
364 // prevent global pollution for namespaces
365 exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
366 // bind timers to global for call from export context
367 : IS_BIND && own ? ctx(out, global)
368 // wrap global constructors for prevent change them in library
369 : IS_WRAP && target[key] == out ? (function (C) {
370 var F = function (a, b, c) {
371 if (this instanceof C) {
372 switch (arguments.length) {
373 case 0: return new C();
374 case 1: return new C(a);
375 case 2: return new C(a, b);
376 } return new C(a, b, c);
377 } return C.apply(this, arguments);
378 };
379 F[PROTOTYPE] = C[PROTOTYPE];
380 return F;
381 // make static versions for prototype methods
382 })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
383 // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
384 if (IS_PROTO) {
385 (exports.virtual || (exports.virtual = {}))[key] = out;
386 // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
387 if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
388 }
389 }
390};
391// type bitmap
392$export.F = 1; // forced
393$export.G = 2; // global
394$export.S = 4; // static
395$export.P = 8; // proto
396$export.B = 16; // bind
397$export.W = 32; // wrap
398$export.U = 64; // safe
399$export.R = 128; // real proto method for `library`
400module.exports = $export;
401
402
403/***/ }),
404/* 5 */
405/***/ (function(module, exports) {
406
407// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
408var global = module.exports = typeof window != 'undefined' && window.Math == Math
409 ? window : typeof self != 'undefined' && self.Math == Math ? self
410 // eslint-disable-next-line no-new-func
411 : Function('return this')();
412if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
413
414
415/***/ }),
416/* 6 */
417/***/ (function(module, __webpack_exports__, __webpack_require__) {
418
419"use strict";
420/* harmony export (immutable) */ __webpack_exports__["a"] = keys;
421/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isObject_js__ = __webpack_require__(30);
422/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__setup_js__ = __webpack_require__(2);
423/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__has_js__ = __webpack_require__(27);
424/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__collectNonEnumProps_js__ = __webpack_require__(139);
425
426
427
428
429
430// Retrieve the names of an object's own properties.
431// Delegates to **ECMAScript 5**'s native `Object.keys`.
432function keys(obj) {
433 if (!Object(__WEBPACK_IMPORTED_MODULE_0__isObject_js__["a" /* default */])(obj)) return [];
434 if (__WEBPACK_IMPORTED_MODULE_1__setup_js__["m" /* nativeKeys */]) return Object(__WEBPACK_IMPORTED_MODULE_1__setup_js__["m" /* nativeKeys */])(obj);
435 var keys = [];
436 for (var key in obj) if (Object(__WEBPACK_IMPORTED_MODULE_2__has_js__["a" /* default */])(obj, key)) keys.push(key);
437 // Ahem, IE < 9.
438 if (__WEBPACK_IMPORTED_MODULE_1__setup_js__["h" /* hasEnumBug */]) Object(__WEBPACK_IMPORTED_MODULE_3__collectNonEnumProps_js__["a" /* default */])(obj, keys);
439 return keys;
440}
441
442
443/***/ }),
444/* 7 */
445/***/ (function(module, __webpack_exports__, __webpack_require__) {
446
447"use strict";
448/* harmony export (immutable) */ __webpack_exports__["a"] = tagTester;
449/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
450
451
452// Internal function for creating a `toString`-based type tester.
453function tagTester(name) {
454 var tag = '[object ' + name + ']';
455 return function(obj) {
456 return __WEBPACK_IMPORTED_MODULE_0__setup_js__["t" /* toString */].call(obj) === tag;
457 };
458}
459
460
461/***/ }),
462/* 8 */
463/***/ (function(module, exports, __webpack_require__) {
464
465var store = __webpack_require__(88)('wks');
466var uid = __webpack_require__(62);
467var Symbol = __webpack_require__(5).Symbol;
468var USE_SYMBOL = typeof Symbol == 'function';
469
470var $exports = module.exports = function (name) {
471 return store[name] || (store[name] =
472 USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
473};
474
475$exports.store = store;
476
477
478/***/ }),
479/* 9 */
480/***/ (function(module, exports) {
481
482module.exports = function (it) {
483 return typeof it === 'object' ? it !== null : typeof it === 'function';
484};
485
486
487/***/ }),
488/* 10 */
489/***/ (function(module, __webpack_exports__, __webpack_require__) {
490
491"use strict";
492/* harmony export (immutable) */ __webpack_exports__["a"] = cb;
493/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(12);
494/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__baseIteratee_js__ = __webpack_require__(149);
495/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__iteratee_js__ = __webpack_require__(150);
496
497
498
499
500// The function we call internally to generate a callback. It invokes
501// `_.iteratee` if overridden, otherwise `baseIteratee`.
502function cb(value, context, argCount) {
503 if (__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].iteratee !== __WEBPACK_IMPORTED_MODULE_2__iteratee_js__["a" /* default */]) return __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].iteratee(value, context);
504 return Object(__WEBPACK_IMPORTED_MODULE_1__baseIteratee_js__["a" /* default */])(value, context, argCount);
505}
506
507
508/***/ }),
509/* 11 */
510/***/ (function(module, __webpack_exports__, __webpack_require__) {
511
512"use strict";
513/* harmony export (immutable) */ __webpack_exports__["a"] = restArguments;
514// Some functions take a variable number of arguments, or a few expected
515// arguments at the beginning and then a variable number of values to operate
516// on. This helper accumulates all remaining arguments past the function’s
517// argument length (or an explicit `startIndex`), into an array that becomes
518// the last argument. Similar to ES6’s "rest parameter".
519function restArguments(func, startIndex) {
520 startIndex = startIndex == null ? func.length - 1 : +startIndex;
521 return function() {
522 var length = Math.max(arguments.length - startIndex, 0),
523 rest = Array(length),
524 index = 0;
525 for (; index < length; index++) {
526 rest[index] = arguments[index + startIndex];
527 }
528 switch (startIndex) {
529 case 0: return func.call(this, rest);
530 case 1: return func.call(this, arguments[0], rest);
531 case 2: return func.call(this, arguments[0], arguments[1], rest);
532 }
533 var args = Array(startIndex + 1);
534 for (index = 0; index < startIndex; index++) {
535 args[index] = arguments[index];
536 }
537 args[startIndex] = rest;
538 return func.apply(this, args);
539 };
540}
541
542
543/***/ }),
544/* 12 */
545/***/ (function(module, __webpack_exports__, __webpack_require__) {
546
547"use strict";
548/* harmony export (immutable) */ __webpack_exports__["a"] = _;
549/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
550
551
552// If Underscore is called as a function, it returns a wrapped object that can
553// be used OO-style. This wrapper holds altered versions of all functions added
554// through `_.mixin`. Wrapped objects may be chained.
555function _(obj) {
556 if (obj instanceof _) return obj;
557 if (!(this instanceof _)) return new _(obj);
558 this._wrapped = obj;
559}
560
561_.VERSION = __WEBPACK_IMPORTED_MODULE_0__setup_js__["e" /* VERSION */];
562
563// Extracts the result from a wrapped and chained object.
564_.prototype.value = function() {
565 return this._wrapped;
566};
567
568// Provide unwrapping proxies for some methods used in engine operations
569// such as arithmetic and JSON stringification.
570_.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
571
572_.prototype.toString = function() {
573 return String(this._wrapped);
574};
575
576
577/***/ }),
578/* 13 */
579/***/ (function(module, __webpack_exports__, __webpack_require__) {
580
581"use strict";
582/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createSizePropertyCheck_js__ = __webpack_require__(137);
583/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__getLength_js__ = __webpack_require__(18);
584
585
586
587// Internal helper for collection methods to determine whether a collection
588// should be iterated as an array or as an object.
589// Related: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
590// Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
591/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createSizePropertyCheck_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__getLength_js__["a" /* default */]));
592
593
594/***/ }),
595/* 14 */
596/***/ (function(module, exports, __webpack_require__) {
597
598"use strict";
599
600
601var _promise = __webpack_require__(3);
602
603var _promise2 = _interopRequireDefault(_promise);
604
605function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
606
607var _ = __webpack_require__(0);
608var md5 = __webpack_require__(342);
609
610var _require = __webpack_require__(0),
611 extend = _require.extend;
612
613var AV = __webpack_require__(42);
614
615var _require2 = __webpack_require__(19),
616 getSessionToken = _require2.getSessionToken;
617
618var ajax = __webpack_require__(72);
619
620// 计算 X-LC-Sign 的签名方法
621var sign = function sign(key, isMasterKey) {
622 var now = new Date().getTime();
623 var signature = md5(now + key);
624 if (isMasterKey) {
625 return signature + ',' + now + ',master';
626 }
627 return signature + ',' + now;
628};
629
630var setAppKey = function setAppKey(headers, signKey) {
631 if (signKey) {
632 headers['X-LC-Sign'] = sign(AV.applicationKey);
633 } else {
634 headers['X-LC-Key'] = AV.applicationKey;
635 }
636};
637
638var setHeaders = function setHeaders() {
639 var authOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
640 var signKey = arguments[1];
641
642 var headers = {
643 'X-LC-Id': AV.applicationId,
644 'Content-Type': 'application/json;charset=UTF-8'
645 };
646 var useMasterKey = false;
647 if (typeof authOptions.useMasterKey === 'boolean') {
648 useMasterKey = authOptions.useMasterKey;
649 } else if (typeof AV._config.useMasterKey === 'boolean') {
650 useMasterKey = AV._config.useMasterKey;
651 }
652 if (useMasterKey) {
653 if (AV.masterKey) {
654 if (signKey) {
655 headers['X-LC-Sign'] = sign(AV.masterKey, true);
656 } else {
657 headers['X-LC-Key'] = AV.masterKey + ',master';
658 }
659 } else {
660 console.warn('masterKey is not set, fall back to use appKey');
661 setAppKey(headers, signKey);
662 }
663 } else {
664 setAppKey(headers, signKey);
665 }
666 if (AV.hookKey) {
667 headers['X-LC-Hook-Key'] = AV.hookKey;
668 }
669 if (AV._config.production !== null) {
670 headers['X-LC-Prod'] = String(AV._config.production);
671 }
672 headers[ false ? 'User-Agent' : 'X-LC-UA'] = AV._sharedConfig.userAgent;
673
674 return _promise2.default.resolve().then(function () {
675 // Pass the session token
676 var sessionToken = getSessionToken(authOptions);
677 if (sessionToken) {
678 headers['X-LC-Session'] = sessionToken;
679 } else if (!AV._config.disableCurrentUser) {
680 return AV.User.currentAsync().then(function (currentUser) {
681 if (currentUser && currentUser._sessionToken) {
682 headers['X-LC-Session'] = currentUser._sessionToken;
683 }
684 return headers;
685 });
686 }
687 return headers;
688 });
689};
690
691var createApiUrl = function createApiUrl(_ref) {
692 var _ref$service = _ref.service,
693 service = _ref$service === undefined ? 'api' : _ref$service,
694 _ref$version = _ref.version,
695 version = _ref$version === undefined ? '1.1' : _ref$version,
696 path = _ref.path;
697
698 var apiURL = AV._config.serverURLs[service];
699
700 if (!apiURL) throw new Error('undefined server URL for ' + service);
701
702 if (apiURL.charAt(apiURL.length - 1) !== '/') {
703 apiURL += '/';
704 }
705 apiURL += version;
706 if (path) {
707 apiURL += path;
708 }
709
710 return apiURL;
711};
712
713/**
714 * Low level REST API client. Call REST endpoints with authorization headers.
715 * @function AV.request
716 * @since 3.0.0
717 * @param {Object} options
718 * @param {String} options.method HTTP method
719 * @param {String} options.path endpoint path, e.g. `/classes/Test/55759577e4b029ae6015ac20`
720 * @param {Object} [options.query] query string dict
721 * @param {Object} [options.data] HTTP body
722 * @param {AuthOptions} [options.authOptions]
723 * @param {String} [options.service = 'api']
724 * @param {String} [options.version = '1.1']
725 */
726var request = function request(_ref2) {
727 var service = _ref2.service,
728 version = _ref2.version,
729 method = _ref2.method,
730 path = _ref2.path,
731 query = _ref2.query,
732 data = _ref2.data,
733 authOptions = _ref2.authOptions,
734 _ref2$signKey = _ref2.signKey,
735 signKey = _ref2$signKey === undefined ? true : _ref2$signKey;
736
737 if (!(AV.applicationId && (AV.applicationKey || AV.masterKey))) {
738 throw new Error('Not initialized');
739 }
740 if (AV._appRouter) {
741 AV._appRouter.refresh();
742 }
743 var timeout = AV._config.requestTimeout;
744
745 var url = createApiUrl({ service: service, path: path, version: version });
746 return setHeaders(authOptions, signKey).then(function (headers) {
747 return ajax({ method: method, url: url, query: query, data: data, headers: headers, timeout: timeout }).catch(function (error) {
748 var errorJSON = {
749 code: error.code || -1,
750 error: error.message || error.responseText
751 };
752 if (error.response && error.response.code) {
753 errorJSON = error.response;
754 } else if (error.responseText) {
755 try {
756 errorJSON = JSON.parse(error.responseText);
757 } catch (e) {
758 // If we fail to parse the error text, that's okay.
759 }
760 }
761 errorJSON.rawMessage = errorJSON.rawMessage || errorJSON.error;
762 if (!AV._sharedConfig.keepErrorRawMessage) {
763 errorJSON.error += ' [' + (error.statusCode || 'N/A') + ' ' + method + ' ' + url + ']';
764 }
765 // Transform the error into an instance of AVError by trying to parse
766 // the error string as JSON.
767 var err = new Error(errorJSON.error);
768 delete errorJSON.error;
769 throw _.extend(err, errorJSON);
770 });
771 });
772};
773
774// lagecy request
775var _request = function _request(route, className, objectId, method, data, authOptions, query) {
776 var path = '';
777 if (route) path += '/' + route;
778 if (className) path += '/' + className;
779 if (objectId) path += '/' + objectId;
780 // for migeration
781 if (data && data._fetchWhenSave) throw new Error('_fetchWhenSave should be in the query');
782 if (data && data._where) throw new Error('_where should be in the query');
783 if (method && method.toLowerCase() === 'get') {
784 query = extend({}, query, data);
785 data = null;
786 }
787 return request({
788 method: method,
789 path: path,
790 query: query,
791 data: data,
792 authOptions: authOptions
793 });
794};
795
796AV.request = request;
797
798module.exports = {
799 _request: _request,
800 request: request
801};
802
803/***/ }),
804/* 15 */
805/***/ (function(module, exports, __webpack_require__) {
806
807var isObject = __webpack_require__(9);
808module.exports = function (it) {
809 if (!isObject(it)) throw TypeError(it + ' is not an object!');
810 return it;
811};
812
813
814/***/ }),
815/* 16 */
816/***/ (function(module, exports, __webpack_require__) {
817
818// Thank's IE8 for his funny defineProperty
819module.exports = !__webpack_require__(28)(function () {
820 return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
821});
822
823
824/***/ }),
825/* 17 */
826/***/ (function(module, __webpack_exports__, __webpack_require__) {
827
828"use strict";
829/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
830/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__setup_js__ = __webpack_require__(2);
831
832
833
834var isFunction = Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Function');
835
836// Optimize `isFunction` if appropriate. Work around some `typeof` bugs in old
837// v8, IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
838var nodelist = __WEBPACK_IMPORTED_MODULE_1__setup_js__["p" /* root */].document && __WEBPACK_IMPORTED_MODULE_1__setup_js__["p" /* root */].document.childNodes;
839if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
840 isFunction = function(obj) {
841 return typeof obj == 'function' || false;
842 };
843}
844
845/* harmony default export */ __webpack_exports__["a"] = (isFunction);
846
847
848/***/ }),
849/* 18 */
850/***/ (function(module, __webpack_exports__, __webpack_require__) {
851
852"use strict";
853/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__shallowProperty_js__ = __webpack_require__(138);
854
855
856// Internal helper to obtain the `length` property of an object.
857/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__shallowProperty_js__["a" /* default */])('length'));
858
859
860/***/ }),
861/* 19 */
862/***/ (function(module, exports, __webpack_require__) {
863
864"use strict";
865
866
867var _promise = __webpack_require__(3);
868
869var _promise2 = _interopRequireDefault(_promise);
870
871var _getPrototypeOf = __webpack_require__(178);
872
873var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
874
875function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
876
877var _ = __webpack_require__(0);
878
879// Helper function to check null or undefined.
880var isNullOrUndefined = function isNullOrUndefined(x) {
881 return _.isNull(x) || _.isUndefined(x);
882};
883
884var ensureArray = function ensureArray(target) {
885 if (_.isArray(target)) {
886 return target;
887 }
888 if (target === undefined || target === null) {
889 return [];
890 }
891 return [target];
892};
893
894var transformFetchOptions = function transformFetchOptions() {
895 var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
896 keys = _ref.keys,
897 include = _ref.include,
898 includeACL = _ref.includeACL;
899
900 var fetchOptions = {};
901 if (keys) {
902 fetchOptions.keys = ensureArray(keys).join(',');
903 }
904 if (include) {
905 fetchOptions.include = ensureArray(include).join(',');
906 }
907 if (includeACL) {
908 fetchOptions.returnACL = includeACL;
909 }
910 return fetchOptions;
911};
912
913var getSessionToken = function getSessionToken(authOptions) {
914 if (authOptions.sessionToken) {
915 return authOptions.sessionToken;
916 }
917 if (authOptions.user && typeof authOptions.user.getSessionToken === 'function') {
918 return authOptions.user.getSessionToken();
919 }
920};
921
922var tap = function tap(interceptor) {
923 return function (value) {
924 return interceptor(value), value;
925 };
926};
927
928// Shared empty constructor function to aid in prototype-chain creation.
929var EmptyConstructor = function EmptyConstructor() {};
930
931// Helper function to correctly set up the prototype chain, for subclasses.
932// Similar to `goog.inherits`, but uses a hash of prototype properties and
933// class properties to be extended.
934var inherits = function inherits(parent, protoProps, staticProps) {
935 var child;
936
937 // The constructor function for the new subclass is either defined by you
938 // (the "constructor" property in your `extend` definition), or defaulted
939 // by us to simply call the parent's constructor.
940 if (protoProps && protoProps.hasOwnProperty('constructor')) {
941 child = protoProps.constructor;
942 } else {
943 /** @ignore */
944 child = function child() {
945 parent.apply(this, arguments);
946 };
947 }
948
949 // Inherit class (static) properties from parent.
950 _.extend(child, parent);
951
952 // Set the prototype chain to inherit from `parent`, without calling
953 // `parent`'s constructor function.
954 EmptyConstructor.prototype = parent.prototype;
955 child.prototype = new EmptyConstructor();
956
957 // Add prototype properties (instance properties) to the subclass,
958 // if supplied.
959 if (protoProps) {
960 _.extend(child.prototype, protoProps);
961 }
962
963 // Add static properties to the constructor function, if supplied.
964 if (staticProps) {
965 _.extend(child, staticProps);
966 }
967
968 // Correctly set child's `prototype.constructor`.
969 child.prototype.constructor = child;
970
971 // Set a convenience property in case the parent's prototype is
972 // needed later.
973 child.__super__ = parent.prototype;
974
975 return child;
976};
977
978var parseDate = function parseDate(iso8601) {
979 return new Date(iso8601);
980};
981
982var setValue = function setValue(target, key, value) {
983 // '.' is not allowed in Class keys, escaping is not in concern now.
984 var segs = key.split('.');
985 var lastSeg = segs.pop();
986 var currentTarget = target;
987 segs.forEach(function (seg) {
988 if (currentTarget[seg] === undefined) currentTarget[seg] = {};
989 currentTarget = currentTarget[seg];
990 });
991 currentTarget[lastSeg] = value;
992 return target;
993};
994
995var findValue = function findValue(target, key) {
996 var segs = key.split('.');
997 var firstSeg = segs[0];
998 var lastSeg = segs.pop();
999 var currentTarget = target;
1000 for (var i = 0; i < segs.length; i++) {
1001 currentTarget = currentTarget[segs[i]];
1002 if (currentTarget === undefined) {
1003 return [undefined, undefined, lastSeg];
1004 }
1005 }
1006 var value = currentTarget[lastSeg];
1007 return [value, currentTarget, lastSeg, firstSeg];
1008};
1009
1010var isPlainObject = function isPlainObject(obj) {
1011 return _.isObject(obj) && (0, _getPrototypeOf2.default)(obj) === Object.prototype;
1012};
1013
1014var continueWhile = function continueWhile(predicate, asyncFunction) {
1015 if (predicate()) {
1016 return asyncFunction().then(function () {
1017 return continueWhile(predicate, asyncFunction);
1018 });
1019 }
1020 return _promise2.default.resolve();
1021};
1022
1023module.exports = {
1024 isNullOrUndefined: isNullOrUndefined,
1025 ensureArray: ensureArray,
1026 transformFetchOptions: transformFetchOptions,
1027 getSessionToken: getSessionToken,
1028 tap: tap,
1029 inherits: inherits,
1030 parseDate: parseDate,
1031 setValue: setValue,
1032 findValue: findValue,
1033 isPlainObject: isPlainObject,
1034 continueWhile: continueWhile
1035};
1036
1037/***/ }),
1038/* 20 */
1039/***/ (function(module, exports, __webpack_require__) {
1040
1041var anObject = __webpack_require__(15);
1042var IE8_DOM_DEFINE = __webpack_require__(115);
1043var toPrimitive = __webpack_require__(84);
1044var dP = Object.defineProperty;
1045
1046exports.f = __webpack_require__(16) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
1047 anObject(O);
1048 P = toPrimitive(P, true);
1049 anObject(Attributes);
1050 if (IE8_DOM_DEFINE) try {
1051 return dP(O, P, Attributes);
1052 } catch (e) { /* empty */ }
1053 if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
1054 if ('value' in Attributes) O[P] = Attributes.value;
1055 return O;
1056};
1057
1058
1059/***/ }),
1060/* 21 */
1061/***/ (function(module, exports, __webpack_require__) {
1062
1063module.exports = { "default": __webpack_require__(301), __esModule: true };
1064
1065/***/ }),
1066/* 22 */
1067/***/ (function(module, exports, __webpack_require__) {
1068
1069// optional / simple context binding
1070var aFunction = __webpack_require__(47);
1071module.exports = function (fn, that, length) {
1072 aFunction(fn);
1073 if (that === undefined) return fn;
1074 switch (length) {
1075 case 1: return function (a) {
1076 return fn.call(that, a);
1077 };
1078 case 2: return function (a, b) {
1079 return fn.call(that, a, b);
1080 };
1081 case 3: return function (a, b, c) {
1082 return fn.call(that, a, b, c);
1083 };
1084 }
1085 return function (/* ...args */) {
1086 return fn.apply(that, arguments);
1087 };
1088};
1089
1090
1091/***/ }),
1092/* 23 */
1093/***/ (function(module, exports, __webpack_require__) {
1094
1095"use strict";
1096
1097
1098exports.__esModule = true;
1099
1100var _iterator = __webpack_require__(73);
1101
1102var _iterator2 = _interopRequireDefault(_iterator);
1103
1104var _symbol = __webpack_require__(44);
1105
1106var _symbol2 = _interopRequireDefault(_symbol);
1107
1108var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; };
1109
1110function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
1111
1112exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) {
1113 return typeof obj === "undefined" ? "undefined" : _typeof(obj);
1114} : function (obj) {
1115 return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
1116};
1117
1118/***/ }),
1119/* 24 */
1120/***/ (function(module, exports, __webpack_require__) {
1121
1122var dP = __webpack_require__(20);
1123var createDesc = __webpack_require__(48);
1124module.exports = __webpack_require__(16) ? function (object, key, value) {
1125 return dP.f(object, key, createDesc(1, value));
1126} : function (object, key, value) {
1127 object[key] = value;
1128 return object;
1129};
1130
1131
1132/***/ }),
1133/* 25 */
1134/***/ (function(module, exports) {
1135
1136var hasOwnProperty = {}.hasOwnProperty;
1137module.exports = function (it, key) {
1138 return hasOwnProperty.call(it, key);
1139};
1140
1141
1142/***/ }),
1143/* 26 */
1144/***/ (function(module, exports, __webpack_require__) {
1145
1146// to indexed object, toObject with fallback for non-array-like ES3 strings
1147var IObject = __webpack_require__(86);
1148var defined = __webpack_require__(81);
1149module.exports = function (it) {
1150 return IObject(defined(it));
1151};
1152
1153
1154/***/ }),
1155/* 27 */
1156/***/ (function(module, __webpack_exports__, __webpack_require__) {
1157
1158"use strict";
1159/* harmony export (immutable) */ __webpack_exports__["a"] = has;
1160/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
1161
1162
1163// Internal function to check whether `key` is an own property name of `obj`.
1164function has(obj, key) {
1165 return obj != null && __WEBPACK_IMPORTED_MODULE_0__setup_js__["i" /* hasOwnProperty */].call(obj, key);
1166}
1167
1168
1169/***/ }),
1170/* 28 */
1171/***/ (function(module, exports) {
1172
1173module.exports = function (exec) {
1174 try {
1175 return !!exec();
1176 } catch (e) {
1177 return true;
1178 }
1179};
1180
1181
1182/***/ }),
1183/* 29 */
1184/***/ (function(module, exports, __webpack_require__) {
1185
1186// 7.1.13 ToObject(argument)
1187var defined = __webpack_require__(81);
1188module.exports = function (it) {
1189 return Object(defined(it));
1190};
1191
1192
1193/***/ }),
1194/* 30 */
1195/***/ (function(module, __webpack_exports__, __webpack_require__) {
1196
1197"use strict";
1198/* harmony export (immutable) */ __webpack_exports__["a"] = isObject;
1199// Is a given variable an object?
1200function isObject(obj) {
1201 var type = typeof obj;
1202 return type === 'function' || type === 'object' && !!obj;
1203}
1204
1205
1206/***/ }),
1207/* 31 */
1208/***/ (function(module, __webpack_exports__, __webpack_require__) {
1209
1210"use strict";
1211/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
1212/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__tagTester_js__ = __webpack_require__(7);
1213
1214
1215
1216// Is a given value an array?
1217// Delegates to ECMA5's native `Array.isArray`.
1218/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_0__setup_js__["k" /* nativeIsArray */] || Object(__WEBPACK_IMPORTED_MODULE_1__tagTester_js__["a" /* default */])('Array'));
1219
1220
1221/***/ }),
1222/* 32 */
1223/***/ (function(module, __webpack_exports__, __webpack_require__) {
1224
1225"use strict";
1226/* harmony export (immutable) */ __webpack_exports__["a"] = each;
1227/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__optimizeCb_js__ = __webpack_require__(55);
1228/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__ = __webpack_require__(13);
1229/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__keys_js__ = __webpack_require__(6);
1230
1231
1232
1233
1234// The cornerstone for collection functions, an `each`
1235// implementation, aka `forEach`.
1236// Handles raw objects in addition to array-likes. Treats all
1237// sparse array-likes as if they were dense.
1238function each(obj, iteratee, context) {
1239 iteratee = Object(__WEBPACK_IMPORTED_MODULE_0__optimizeCb_js__["a" /* default */])(iteratee, context);
1240 var i, length;
1241 if (Object(__WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__["a" /* default */])(obj)) {
1242 for (i = 0, length = obj.length; i < length; i++) {
1243 iteratee(obj[i], i, obj);
1244 }
1245 } else {
1246 var _keys = Object(__WEBPACK_IMPORTED_MODULE_2__keys_js__["a" /* default */])(obj);
1247 for (i = 0, length = _keys.length; i < length; i++) {
1248 iteratee(obj[_keys[i]], _keys[i], obj);
1249 }
1250 }
1251 return obj;
1252}
1253
1254
1255/***/ }),
1256/* 33 */
1257/***/ (function(module, exports, __webpack_require__) {
1258
1259"use strict";
1260
1261
1262function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
1263
1264/* eslint-env browser */
1265
1266/**
1267 * This is the web browser implementation of `debug()`.
1268 */
1269exports.log = log;
1270exports.formatArgs = formatArgs;
1271exports.save = save;
1272exports.load = load;
1273exports.useColors = useColors;
1274exports.storage = localstorage();
1275/**
1276 * Colors.
1277 */
1278
1279exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
1280/**
1281 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
1282 * and the Firebug extension (any Firefox version) are known
1283 * to support "%c" CSS customizations.
1284 *
1285 * TODO: add a `localStorage` variable to explicitly enable/disable colors
1286 */
1287// eslint-disable-next-line complexity
1288
1289function useColors() {
1290 // NB: In an Electron preload script, document will be defined but not fully
1291 // initialized. Since we know we're in Chrome, we'll just detect this case
1292 // explicitly
1293 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
1294 return true;
1295 } // Internet Explorer and Edge do not support colors.
1296
1297
1298 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
1299 return false;
1300 } // Is webkit? http://stackoverflow.com/a/16459606/376773
1301 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
1302
1303
1304 return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
1305 typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
1306 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
1307 typeof navigator !== 'undefined' && 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
1308 typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
1309}
1310/**
1311 * Colorize log arguments if enabled.
1312 *
1313 * @api public
1314 */
1315
1316
1317function formatArgs(args) {
1318 args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
1319
1320 if (!this.useColors) {
1321 return;
1322 }
1323
1324 var c = 'color: ' + this.color;
1325 args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
1326 // arguments passed either before or after the %c, so we need to
1327 // figure out the correct index to insert the CSS into
1328
1329 var index = 0;
1330 var lastC = 0;
1331 args[0].replace(/%[a-zA-Z%]/g, function (match) {
1332 if (match === '%%') {
1333 return;
1334 }
1335
1336 index++;
1337
1338 if (match === '%c') {
1339 // We only are interested in the *last* %c
1340 // (the user may have provided their own)
1341 lastC = index;
1342 }
1343 });
1344 args.splice(lastC, 0, c);
1345}
1346/**
1347 * Invokes `console.log()` when available.
1348 * No-op when `console.log` is not a "function".
1349 *
1350 * @api public
1351 */
1352
1353
1354function log() {
1355 var _console;
1356
1357 // This hackery is required for IE8/9, where
1358 // the `console.log` function doesn't have 'apply'
1359 return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
1360}
1361/**
1362 * Save `namespaces`.
1363 *
1364 * @param {String} namespaces
1365 * @api private
1366 */
1367
1368
1369function save(namespaces) {
1370 try {
1371 if (namespaces) {
1372 exports.storage.setItem('debug', namespaces);
1373 } else {
1374 exports.storage.removeItem('debug');
1375 }
1376 } catch (error) {// Swallow
1377 // XXX (@Qix-) should we be logging these?
1378 }
1379}
1380/**
1381 * Load `namespaces`.
1382 *
1383 * @return {String} returns the previously persisted debug modes
1384 * @api private
1385 */
1386
1387
1388function load() {
1389 var r;
1390
1391 try {
1392 r = exports.storage.getItem('debug');
1393 } catch (error) {} // Swallow
1394 // XXX (@Qix-) should we be logging these?
1395 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
1396
1397
1398 if (!r && typeof process !== 'undefined' && 'env' in process) {
1399 r = process.env.DEBUG;
1400 }
1401
1402 return r;
1403}
1404/**
1405 * Localstorage attempts to return the localstorage.
1406 *
1407 * This is necessary because safari throws
1408 * when a user disables cookies/localstorage
1409 * and you attempt to access it.
1410 *
1411 * @return {LocalStorage}
1412 * @api private
1413 */
1414
1415
1416function localstorage() {
1417 try {
1418 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
1419 // The Browser also has localStorage in the global context.
1420 return localStorage;
1421 } catch (error) {// Swallow
1422 // XXX (@Qix-) should we be logging these?
1423 }
1424}
1425
1426module.exports = __webpack_require__(306)(exports);
1427var formatters = module.exports.formatters;
1428/**
1429 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
1430 */
1431
1432formatters.j = function (v) {
1433 try {
1434 return JSON.stringify(v);
1435 } catch (error) {
1436 return '[UnexpectedJSONParseError]: ' + error.message;
1437 }
1438};
1439
1440
1441
1442/***/ }),
1443/* 34 */
1444/***/ (function(module, exports, __webpack_require__) {
1445
1446"use strict";
1447
1448
1449var _ = __webpack_require__(0);
1450
1451/**
1452 * @class AV.Error
1453 */
1454
1455function AVError(code, message) {
1456 var error = new Error(message);
1457 error.code = code;
1458 return error;
1459}
1460
1461_.extend(AVError,
1462/** @lends AV.Error */{
1463 /**
1464 * Error code indicating some error other than those enumerated here.
1465 * @constant
1466 */
1467 OTHER_CAUSE: -1,
1468
1469 /**
1470 * Error code indicating that something has gone wrong with the server.
1471 * If you get this error code, it is AV's fault. Contact us at
1472 * https://avoscloud.com/help
1473 * @constant
1474 */
1475 INTERNAL_SERVER_ERROR: 1,
1476
1477 /**
1478 * Error code indicating the connection to the AV servers failed.
1479 * @constant
1480 */
1481 CONNECTION_FAILED: 100,
1482
1483 /**
1484 * Error code indicating the specified object doesn't exist.
1485 * @constant
1486 */
1487 OBJECT_NOT_FOUND: 101,
1488
1489 /**
1490 * Error code indicating you tried to query with a datatype that doesn't
1491 * support it, like exact matching an array or object.
1492 * @constant
1493 */
1494 INVALID_QUERY: 102,
1495
1496 /**
1497 * Error code indicating a missing or invalid classname. Classnames are
1498 * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the
1499 * only valid characters.
1500 * @constant
1501 */
1502 INVALID_CLASS_NAME: 103,
1503
1504 /**
1505 * Error code indicating an unspecified object id.
1506 * @constant
1507 */
1508 MISSING_OBJECT_ID: 104,
1509
1510 /**
1511 * Error code indicating an invalid key name. Keys are case-sensitive. They
1512 * must start with a letter, and a-zA-Z0-9_ are the only valid characters.
1513 * @constant
1514 */
1515 INVALID_KEY_NAME: 105,
1516
1517 /**
1518 * Error code indicating a malformed pointer. You should not see this unless
1519 * you have been mucking about changing internal AV code.
1520 * @constant
1521 */
1522 INVALID_POINTER: 106,
1523
1524 /**
1525 * Error code indicating that badly formed JSON was received upstream. This
1526 * either indicates you have done something unusual with modifying how
1527 * things encode to JSON, or the network is failing badly.
1528 * @constant
1529 */
1530 INVALID_JSON: 107,
1531
1532 /**
1533 * Error code indicating that the feature you tried to access is only
1534 * available internally for testing purposes.
1535 * @constant
1536 */
1537 COMMAND_UNAVAILABLE: 108,
1538
1539 /**
1540 * You must call AV.initialize before using the AV library.
1541 * @constant
1542 */
1543 NOT_INITIALIZED: 109,
1544
1545 /**
1546 * Error code indicating that a field was set to an inconsistent type.
1547 * @constant
1548 */
1549 INCORRECT_TYPE: 111,
1550
1551 /**
1552 * Error code indicating an invalid channel name. A channel name is either
1553 * an empty string (the broadcast channel) or contains only a-zA-Z0-9_
1554 * characters.
1555 * @constant
1556 */
1557 INVALID_CHANNEL_NAME: 112,
1558
1559 /**
1560 * Error code indicating that push is misconfigured.
1561 * @constant
1562 */
1563 PUSH_MISCONFIGURED: 115,
1564
1565 /**
1566 * Error code indicating that the object is too large.
1567 * @constant
1568 */
1569 OBJECT_TOO_LARGE: 116,
1570
1571 /**
1572 * Error code indicating that the operation isn't allowed for clients.
1573 * @constant
1574 */
1575 OPERATION_FORBIDDEN: 119,
1576
1577 /**
1578 * Error code indicating the result was not found in the cache.
1579 * @constant
1580 */
1581 CACHE_MISS: 120,
1582
1583 /**
1584 * Error code indicating that an invalid key was used in a nested
1585 * JSONObject.
1586 * @constant
1587 */
1588 INVALID_NESTED_KEY: 121,
1589
1590 /**
1591 * Error code indicating that an invalid filename was used for AVFile.
1592 * A valid file name contains only a-zA-Z0-9_. characters and is between 1
1593 * and 128 characters.
1594 * @constant
1595 */
1596 INVALID_FILE_NAME: 122,
1597
1598 /**
1599 * Error code indicating an invalid ACL was provided.
1600 * @constant
1601 */
1602 INVALID_ACL: 123,
1603
1604 /**
1605 * Error code indicating that the request timed out on the server. Typically
1606 * this indicates that the request is too expensive to run.
1607 * @constant
1608 */
1609 TIMEOUT: 124,
1610
1611 /**
1612 * Error code indicating that the email address was invalid.
1613 * @constant
1614 */
1615 INVALID_EMAIL_ADDRESS: 125,
1616
1617 /**
1618 * Error code indicating a missing content type.
1619 * @constant
1620 */
1621 MISSING_CONTENT_TYPE: 126,
1622
1623 /**
1624 * Error code indicating a missing content length.
1625 * @constant
1626 */
1627 MISSING_CONTENT_LENGTH: 127,
1628
1629 /**
1630 * Error code indicating an invalid content length.
1631 * @constant
1632 */
1633 INVALID_CONTENT_LENGTH: 128,
1634
1635 /**
1636 * Error code indicating a file that was too large.
1637 * @constant
1638 */
1639 FILE_TOO_LARGE: 129,
1640
1641 /**
1642 * Error code indicating an error saving a file.
1643 * @constant
1644 */
1645 FILE_SAVE_ERROR: 130,
1646
1647 /**
1648 * Error code indicating an error deleting a file.
1649 * @constant
1650 */
1651 FILE_DELETE_ERROR: 153,
1652
1653 /**
1654 * Error code indicating that a unique field was given a value that is
1655 * already taken.
1656 * @constant
1657 */
1658 DUPLICATE_VALUE: 137,
1659
1660 /**
1661 * Error code indicating that a role's name is invalid.
1662 * @constant
1663 */
1664 INVALID_ROLE_NAME: 139,
1665
1666 /**
1667 * Error code indicating that an application quota was exceeded. Upgrade to
1668 * resolve.
1669 * @constant
1670 */
1671 EXCEEDED_QUOTA: 140,
1672
1673 /**
1674 * Error code indicating that a Cloud Code script failed.
1675 * @constant
1676 */
1677 SCRIPT_FAILED: 141,
1678
1679 /**
1680 * Error code indicating that a Cloud Code validation failed.
1681 * @constant
1682 */
1683 VALIDATION_ERROR: 142,
1684
1685 /**
1686 * Error code indicating that invalid image data was provided.
1687 * @constant
1688 */
1689 INVALID_IMAGE_DATA: 150,
1690
1691 /**
1692 * Error code indicating an unsaved file.
1693 * @constant
1694 */
1695 UNSAVED_FILE_ERROR: 151,
1696
1697 /**
1698 * Error code indicating an invalid push time.
1699 */
1700 INVALID_PUSH_TIME_ERROR: 152,
1701
1702 /**
1703 * Error code indicating that the username is missing or empty.
1704 * @constant
1705 */
1706 USERNAME_MISSING: 200,
1707
1708 /**
1709 * Error code indicating that the password is missing or empty.
1710 * @constant
1711 */
1712 PASSWORD_MISSING: 201,
1713
1714 /**
1715 * Error code indicating that the username has already been taken.
1716 * @constant
1717 */
1718 USERNAME_TAKEN: 202,
1719
1720 /**
1721 * Error code indicating that the email has already been taken.
1722 * @constant
1723 */
1724 EMAIL_TAKEN: 203,
1725
1726 /**
1727 * Error code indicating that the email is missing, but must be specified.
1728 * @constant
1729 */
1730 EMAIL_MISSING: 204,
1731
1732 /**
1733 * Error code indicating that a user with the specified email was not found.
1734 * @constant
1735 */
1736 EMAIL_NOT_FOUND: 205,
1737
1738 /**
1739 * Error code indicating that a user object without a valid session could
1740 * not be altered.
1741 * @constant
1742 */
1743 SESSION_MISSING: 206,
1744
1745 /**
1746 * Error code indicating that a user can only be created through signup.
1747 * @constant
1748 */
1749 MUST_CREATE_USER_THROUGH_SIGNUP: 207,
1750
1751 /**
1752 * Error code indicating that an an account being linked is already linked
1753 * to another user.
1754 * @constant
1755 */
1756 ACCOUNT_ALREADY_LINKED: 208,
1757
1758 /**
1759 * Error code indicating that a user cannot be linked to an account because
1760 * that account's id could not be found.
1761 * @constant
1762 */
1763 LINKED_ID_MISSING: 250,
1764
1765 /**
1766 * Error code indicating that a user with a linked (e.g. Facebook) account
1767 * has an invalid session.
1768 * @constant
1769 */
1770 INVALID_LINKED_SESSION: 251,
1771
1772 /**
1773 * Error code indicating that a service being linked (e.g. Facebook or
1774 * Twitter) is unsupported.
1775 * @constant
1776 */
1777 UNSUPPORTED_SERVICE: 252,
1778 /**
1779 * Error code indicating a real error code is unavailable because
1780 * we had to use an XDomainRequest object to allow CORS requests in
1781 * Internet Explorer, which strips the body from HTTP responses that have
1782 * a non-2XX status code.
1783 * @constant
1784 */
1785 X_DOMAIN_REQUEST: 602
1786});
1787
1788module.exports = AVError;
1789
1790/***/ }),
1791/* 35 */
1792/***/ (function(module, exports, __webpack_require__) {
1793
1794"use strict";
1795
1796var $at = __webpack_require__(217)(true);
1797
1798// 21.1.3.27 String.prototype[@@iterator]()
1799__webpack_require__(82)(String, 'String', function (iterated) {
1800 this._t = String(iterated); // target
1801 this._i = 0; // next index
1802// 21.1.5.2.1 %StringIteratorPrototype%.next()
1803}, function () {
1804 var O = this._t;
1805 var index = this._i;
1806 var point;
1807 if (index >= O.length) return { value: undefined, done: true };
1808 point = $at(O, index);
1809 this._i += point.length;
1810 return { value: point, done: false };
1811});
1812
1813
1814/***/ }),
1815/* 36 */
1816/***/ (function(module, exports) {
1817
1818module.exports = {};
1819
1820
1821/***/ }),
1822/* 37 */
1823/***/ (function(module, exports, __webpack_require__) {
1824
1825__webpack_require__(221);
1826var global = __webpack_require__(5);
1827var hide = __webpack_require__(24);
1828var Iterators = __webpack_require__(36);
1829var TO_STRING_TAG = __webpack_require__(8)('toStringTag');
1830
1831var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' +
1832 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' +
1833 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' +
1834 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' +
1835 'TextTrackList,TouchList').split(',');
1836
1837for (var i = 0; i < DOMIterables.length; i++) {
1838 var NAME = DOMIterables[i];
1839 var Collection = global[NAME];
1840 var proto = Collection && Collection.prototype;
1841 if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
1842 Iterators[NAME] = Iterators.Array;
1843}
1844
1845
1846/***/ }),
1847/* 38 */
1848/***/ (function(module, exports, __webpack_require__) {
1849
1850var ctx = __webpack_require__(22);
1851var call = __webpack_require__(121);
1852var isArrayIter = __webpack_require__(122);
1853var anObject = __webpack_require__(15);
1854var toLength = __webpack_require__(61);
1855var getIterFn = __webpack_require__(90);
1856var BREAK = {};
1857var RETURN = {};
1858var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {
1859 var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable);
1860 var f = ctx(fn, that, entries ? 2 : 1);
1861 var index = 0;
1862 var length, step, iterator, result;
1863 if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');
1864 // fast case for arrays with default iterator
1865 if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {
1866 result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
1867 if (result === BREAK || result === RETURN) return result;
1868 } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {
1869 result = call(iterator, f, step.value, entries);
1870 if (result === BREAK || result === RETURN) return result;
1871 }
1872};
1873exports.BREAK = BREAK;
1874exports.RETURN = RETURN;
1875
1876
1877/***/ }),
1878/* 39 */
1879/***/ (function(module, __webpack_exports__, __webpack_require__) {
1880
1881"use strict";
1882/* harmony export (immutable) */ __webpack_exports__["a"] = values;
1883/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__keys_js__ = __webpack_require__(6);
1884
1885
1886// Retrieve the values of an object's properties.
1887function values(obj) {
1888 var _keys = Object(__WEBPACK_IMPORTED_MODULE_0__keys_js__["a" /* default */])(obj);
1889 var length = _keys.length;
1890 var values = Array(length);
1891 for (var i = 0; i < length; i++) {
1892 values[i] = obj[_keys[i]];
1893 }
1894 return values;
1895}
1896
1897
1898/***/ }),
1899/* 40 */
1900/***/ (function(module, __webpack_exports__, __webpack_require__) {
1901
1902"use strict";
1903/* harmony export (immutable) */ __webpack_exports__["a"] = flatten;
1904/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__getLength_js__ = __webpack_require__(18);
1905/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__ = __webpack_require__(13);
1906/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isArray_js__ = __webpack_require__(31);
1907/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isArguments_js__ = __webpack_require__(95);
1908
1909
1910
1911
1912
1913// Internal implementation of a recursive `flatten` function.
1914function flatten(input, depth, strict, output) {
1915 output = output || [];
1916 if (!depth && depth !== 0) {
1917 depth = Infinity;
1918 } else if (depth <= 0) {
1919 return output.concat(input);
1920 }
1921 var idx = output.length;
1922 for (var i = 0, length = Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(input); i < length; i++) {
1923 var value = input[i];
1924 if (Object(__WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__["a" /* default */])(value) && (Object(__WEBPACK_IMPORTED_MODULE_2__isArray_js__["a" /* default */])(value) || Object(__WEBPACK_IMPORTED_MODULE_3__isArguments_js__["a" /* default */])(value))) {
1925 // Flatten current level of array or arguments object.
1926 if (depth > 1) {
1927 flatten(value, depth - 1, strict, output);
1928 idx = output.length;
1929 } else {
1930 var j = 0, len = value.length;
1931 while (j < len) output[idx++] = value[j++];
1932 }
1933 } else if (!strict) {
1934 output[idx++] = value;
1935 }
1936 }
1937 return output;
1938}
1939
1940
1941/***/ }),
1942/* 41 */
1943/***/ (function(module, __webpack_exports__, __webpack_require__) {
1944
1945"use strict";
1946/* harmony export (immutable) */ __webpack_exports__["a"] = map;
1947/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(10);
1948/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__ = __webpack_require__(13);
1949/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__keys_js__ = __webpack_require__(6);
1950
1951
1952
1953
1954// Return the results of applying the iteratee to each element.
1955function map(obj, iteratee, context) {
1956 iteratee = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(iteratee, context);
1957 var _keys = !Object(__WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__["a" /* default */])(obj) && Object(__WEBPACK_IMPORTED_MODULE_2__keys_js__["a" /* default */])(obj),
1958 length = (_keys || obj).length,
1959 results = Array(length);
1960 for (var index = 0; index < length; index++) {
1961 var currentKey = _keys ? _keys[index] : index;
1962 results[index] = iteratee(obj[currentKey], currentKey, obj);
1963 }
1964 return results;
1965}
1966
1967
1968/***/ }),
1969/* 42 */
1970/***/ (function(module, exports, __webpack_require__) {
1971
1972"use strict";
1973/* WEBPACK VAR INJECTION */(function(global) {
1974
1975var _stringify = __webpack_require__(21);
1976
1977var _stringify2 = _interopRequireDefault(_stringify);
1978
1979var _keys = __webpack_require__(107);
1980
1981var _keys2 = _interopRequireDefault(_keys);
1982
1983var _promise = __webpack_require__(3);
1984
1985var _promise2 = _interopRequireDefault(_promise);
1986
1987function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
1988
1989var _ = __webpack_require__(0);
1990var uuid = __webpack_require__(177);
1991var debug = __webpack_require__(33);
1992
1993var _require = __webpack_require__(19),
1994 inherits = _require.inherits,
1995 parseDate = _require.parseDate;
1996
1997var version = __webpack_require__(179);
1998
1999var _require2 = __webpack_require__(43),
2000 setAdapters = _require2.setAdapters,
2001 adapterManager = _require2.adapterManager;
2002
2003var AV = global.AV || {};
2004
2005// All internal configuration items
2006AV._config = {
2007 serverURLs: {},
2008 useMasterKey: false,
2009 production: null,
2010 realtime: null,
2011 requestTimeout: null
2012};
2013
2014var initialUserAgent = 'LeanCloud-JS-SDK/' + version;
2015
2016// configs shared by all AV instances
2017AV._sharedConfig = {
2018 userAgent: initialUserAgent,
2019 liveQueryRealtime: null
2020};
2021
2022adapterManager.on('platformInfo', function (platformInfo) {
2023 var ua = initialUserAgent;
2024 if (platformInfo) {
2025 if (platformInfo.userAgent) {
2026 ua = platformInfo.userAgent;
2027 } else {
2028 var comments = platformInfo.name;
2029 if (platformInfo.version) {
2030 comments += '/' + platformInfo.version;
2031 }
2032 if (platformInfo.extra) {
2033 comments += '; ' + platformInfo.extra;
2034 }
2035 ua += ' (' + comments + ')';
2036 }
2037 }
2038 AV._sharedConfig.userAgent = ua;
2039});
2040
2041/**
2042 * Contains all AV API classes and functions.
2043 * @namespace AV
2044 */
2045
2046/**
2047 * Returns prefix for localStorage keys used by this instance of AV.
2048 * @param {String} path The relative suffix to append to it.
2049 * null or undefined is treated as the empty string.
2050 * @return {String} The full key name.
2051 * @private
2052 */
2053AV._getAVPath = function (path) {
2054 if (!AV.applicationId) {
2055 throw new Error('You need to call AV.initialize before using AV.');
2056 }
2057 if (!path) {
2058 path = '';
2059 }
2060 if (!_.isString(path)) {
2061 throw new Error("Tried to get a localStorage path that wasn't a String.");
2062 }
2063 if (path[0] === '/') {
2064 path = path.substring(1);
2065 }
2066 return 'AV/' + AV.applicationId + '/' + path;
2067};
2068
2069/**
2070 * Returns the unique string for this app on this machine.
2071 * Gets reset when localStorage is cleared.
2072 * @private
2073 */
2074AV._installationId = null;
2075AV._getInstallationId = function () {
2076 // See if it's cached in RAM.
2077 if (AV._installationId) {
2078 return _promise2.default.resolve(AV._installationId);
2079 }
2080
2081 // Try to get it from localStorage.
2082 var path = AV._getAVPath('installationId');
2083 return AV.localStorage.getItemAsync(path).then(function (_installationId) {
2084 AV._installationId = _installationId;
2085 if (!AV._installationId) {
2086 // It wasn't in localStorage, so create a new one.
2087 AV._installationId = _installationId = uuid();
2088 return AV.localStorage.setItemAsync(path, _installationId).then(function () {
2089 return _installationId;
2090 });
2091 }
2092 return _installationId;
2093 });
2094};
2095
2096AV._subscriptionId = null;
2097AV._refreshSubscriptionId = function () {
2098 var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : AV._getAVPath('subscriptionId');
2099
2100 var subscriptionId = AV._subscriptionId = uuid();
2101 return AV.localStorage.setItemAsync(path, subscriptionId).then(function () {
2102 return subscriptionId;
2103 });
2104};
2105AV._getSubscriptionId = function () {
2106 // See if it's cached in RAM.
2107 if (AV._subscriptionId) {
2108 return _promise2.default.resolve(AV._subscriptionId);
2109 }
2110
2111 // Try to get it from localStorage.
2112 var path = AV._getAVPath('subscriptionId');
2113 return AV.localStorage.getItemAsync(path).then(function (_subscriptionId) {
2114 AV._subscriptionId = _subscriptionId;
2115 if (!AV._subscriptionId) {
2116 // It wasn't in localStorage, so create a new one.
2117 _subscriptionId = AV._refreshSubscriptionId(path);
2118 }
2119 return _subscriptionId;
2120 });
2121};
2122
2123AV._parseDate = parseDate;
2124
2125// A self-propagating extend function.
2126AV._extend = function (protoProps, classProps) {
2127 var child = inherits(this, protoProps, classProps);
2128 child.extend = this.extend;
2129 return child;
2130};
2131
2132/**
2133 * Converts a value in a AV Object into the appropriate representation.
2134 * This is the JS equivalent of Java's AV.maybeReferenceAndEncode(Object)
2135 * if seenObjects is falsey. Otherwise any AV.Objects not in
2136 * seenObjects will be fully embedded rather than encoded
2137 * as a pointer. This array will be used to prevent going into an infinite
2138 * loop because we have circular references. If <seenObjects>
2139 * is set, then none of the AV Objects that are serialized can be dirty.
2140 * @private
2141 */
2142AV._encode = function (value, seenObjects, disallowObjects) {
2143 var full = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
2144
2145 if (value instanceof AV.Object) {
2146 if (disallowObjects) {
2147 throw new Error('AV.Objects not allowed here');
2148 }
2149 if (!seenObjects || _.include(seenObjects, value) || !value._hasData) {
2150 return value._toPointer();
2151 }
2152 return value._toFullJSON(seenObjects.concat(value), full);
2153 }
2154 if (value instanceof AV.ACL) {
2155 return value.toJSON();
2156 }
2157 if (_.isDate(value)) {
2158 return full ? { __type: 'Date', iso: value.toJSON() } : value.toJSON();
2159 }
2160 if (value instanceof AV.GeoPoint) {
2161 return value.toJSON();
2162 }
2163 if (_.isArray(value)) {
2164 return _.map(value, function (x) {
2165 return AV._encode(x, seenObjects, disallowObjects, full);
2166 });
2167 }
2168 if (_.isRegExp(value)) {
2169 return value.source;
2170 }
2171 if (value instanceof AV.Relation) {
2172 return value.toJSON();
2173 }
2174 if (value instanceof AV.Op) {
2175 return value.toJSON();
2176 }
2177 if (value instanceof AV.File) {
2178 if (!value.url() && !value.id) {
2179 throw new Error('Tried to save an object containing an unsaved file.');
2180 }
2181 return value._toFullJSON(seenObjects, full);
2182 }
2183 if (_.isObject(value)) {
2184 return _.mapObject(value, function (v, k) {
2185 return AV._encode(v, seenObjects, disallowObjects, full);
2186 });
2187 }
2188 return value;
2189};
2190
2191/**
2192 * The inverse function of AV._encode.
2193 * @private
2194 */
2195AV._decode = function (value, key) {
2196 if (!_.isObject(value) || _.isDate(value)) {
2197 return value;
2198 }
2199 if (_.isArray(value)) {
2200 return _.map(value, function (v) {
2201 return AV._decode(v);
2202 });
2203 }
2204 if (value instanceof AV.Object) {
2205 return value;
2206 }
2207 if (value instanceof AV.File) {
2208 return value;
2209 }
2210 if (value instanceof AV.Op) {
2211 return value;
2212 }
2213 if (value instanceof AV.GeoPoint) {
2214 return value;
2215 }
2216 if (value instanceof AV.ACL) {
2217 return value;
2218 }
2219 if (key === 'ACL') {
2220 return new AV.ACL(value);
2221 }
2222 if (value.__op) {
2223 return AV.Op._decode(value);
2224 }
2225 var className;
2226 if (value.__type === 'Pointer') {
2227 className = value.className;
2228 var pointer = AV.Object._create(className);
2229 if ((0, _keys2.default)(value).length > 3) {
2230 var v = _.clone(value);
2231 delete v.__type;
2232 delete v.className;
2233 pointer._finishFetch(v, true);
2234 } else {
2235 pointer._finishFetch({ objectId: value.objectId }, false);
2236 }
2237 return pointer;
2238 }
2239 if (value.__type === 'Object') {
2240 // It's an Object included in a query result.
2241 className = value.className;
2242 var _v = _.clone(value);
2243 delete _v.__type;
2244 delete _v.className;
2245 var object = AV.Object._create(className);
2246 object._finishFetch(_v, true);
2247 return object;
2248 }
2249 if (value.__type === 'Date') {
2250 return AV._parseDate(value.iso);
2251 }
2252 if (value.__type === 'GeoPoint') {
2253 return new AV.GeoPoint({
2254 latitude: value.latitude,
2255 longitude: value.longitude
2256 });
2257 }
2258 if (value.__type === 'Relation') {
2259 if (!key) throw new Error('key missing decoding a Relation');
2260 var relation = new AV.Relation(null, key);
2261 relation.targetClassName = value.className;
2262 return relation;
2263 }
2264 if (value.__type === 'File') {
2265 var file = new AV.File(value.name);
2266 var _v2 = _.clone(value);
2267 delete _v2.__type;
2268 file._finishFetch(_v2);
2269 return file;
2270 }
2271 return _.mapObject(value, AV._decode);
2272};
2273
2274/**
2275 * The inverse function of {@link AV.Object#toFullJSON}.
2276 * @since 3.0.0
2277 * @method
2278 * @param {Object}
2279 * return {AV.Object|AV.File|any}
2280 */
2281AV.parseJSON = AV._decode;
2282
2283/**
2284 * Similar to JSON.parse, except that AV internal types will be used if possible.
2285 * Inverse to {@link AV.stringify}
2286 * @since 3.14.0
2287 * @param {string} text the string to parse.
2288 * @return {AV.Object|AV.File|any}
2289 */
2290AV.parse = function (text) {
2291 return AV.parseJSON(JSON.parse(text));
2292};
2293/**
2294 * Serialize a target containing AV.Object, similar to JSON.stringify.
2295 * Inverse to {@link AV.parse}
2296 * @since 3.14.0
2297 * @return {string}
2298 */
2299AV.stringify = function (target) {
2300 return (0, _stringify2.default)(AV._encode(target, [], false, true));
2301};
2302
2303AV._encodeObjectOrArray = function (value) {
2304 var encodeAVObject = function encodeAVObject(object) {
2305 if (object && object._toFullJSON) {
2306 object = object._toFullJSON([]);
2307 }
2308
2309 return _.mapObject(object, function (value) {
2310 return AV._encode(value, []);
2311 });
2312 };
2313
2314 if (_.isArray(value)) {
2315 return value.map(function (object) {
2316 return encodeAVObject(object);
2317 });
2318 } else {
2319 return encodeAVObject(value);
2320 }
2321};
2322
2323AV._arrayEach = _.each;
2324
2325/**
2326 * Does a deep traversal of every item in object, calling func on every one.
2327 * @param {Object} object The object or array to traverse deeply.
2328 * @param {Function} func The function to call for every item. It will
2329 * be passed the item as an argument. If it returns a truthy value, that
2330 * value will replace the item in its parent container.
2331 * @returns {} the result of calling func on the top-level object itself.
2332 * @private
2333 */
2334AV._traverse = function (object, func, seen) {
2335 if (object instanceof AV.Object) {
2336 seen = seen || [];
2337 if (_.indexOf(seen, object) >= 0) {
2338 // We've already visited this object in this call.
2339 return;
2340 }
2341 seen.push(object);
2342 AV._traverse(object.attributes, func, seen);
2343 return func(object);
2344 }
2345 if (object instanceof AV.Relation || object instanceof AV.File) {
2346 // Nothing needs to be done, but we don't want to recurse into the
2347 // object's parent infinitely, so we catch this case.
2348 return func(object);
2349 }
2350 if (_.isArray(object)) {
2351 _.each(object, function (child, index) {
2352 var newChild = AV._traverse(child, func, seen);
2353 if (newChild) {
2354 object[index] = newChild;
2355 }
2356 });
2357 return func(object);
2358 }
2359 if (_.isObject(object)) {
2360 AV._each(object, function (child, key) {
2361 var newChild = AV._traverse(child, func, seen);
2362 if (newChild) {
2363 object[key] = newChild;
2364 }
2365 });
2366 return func(object);
2367 }
2368 return func(object);
2369};
2370
2371/**
2372 * This is like _.each, except:
2373 * * it doesn't work for so-called array-like objects,
2374 * * it does work for dictionaries with a "length" attribute.
2375 * @private
2376 */
2377AV._objectEach = AV._each = function (obj, callback) {
2378 if (_.isObject(obj)) {
2379 _.each(_.keys(obj), function (key) {
2380 callback(obj[key], key);
2381 });
2382 } else {
2383 _.each(obj, callback);
2384 }
2385};
2386
2387/**
2388 * @namespace
2389 * @since 3.14.0
2390 */
2391AV.debug = {
2392 /**
2393 * Enable debug
2394 */
2395 enable: function enable() {
2396 var namespaces = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'leancloud*';
2397 return debug.enable(namespaces);
2398 },
2399 /**
2400 * Disable debug
2401 */
2402 disable: debug.disable
2403};
2404
2405/**
2406 * Specify Adapters
2407 * @since 4.4.0
2408 * @function
2409 * @param {Adapters} newAdapters See {@link https://url.leanapp.cn/adapter-type-definitions @leancloud/adapter-types} for detailed definitions.
2410 */
2411AV.setAdapters = setAdapters;
2412
2413module.exports = AV;
2414/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(66)))
2415
2416/***/ }),
2417/* 43 */
2418/***/ (function(module, exports, __webpack_require__) {
2419
2420"use strict";
2421
2422
2423var _ = __webpack_require__(0);
2424var EventEmitter = __webpack_require__(180);
2425
2426var _require = __webpack_require__(19),
2427 inherits = _require.inherits;
2428
2429var AdapterManager = inherits(EventEmitter, {
2430 constructor: function constructor() {
2431 EventEmitter.apply(this);
2432 this._adapters = {};
2433 },
2434 getAdapter: function getAdapter(name) {
2435 var adapter = this._adapters[name];
2436 if (adapter === undefined) {
2437 throw new Error(name + ' adapter is not configured');
2438 }
2439 return adapter;
2440 },
2441 setAdapters: function setAdapters(newAdapters) {
2442 var _this = this;
2443
2444 _.extend(this._adapters, newAdapters);
2445 _.keys(newAdapters).forEach(function (name) {
2446 return _this.emit(name, newAdapters[name]);
2447 });
2448 }
2449});
2450
2451var adapterManager = new AdapterManager();
2452
2453module.exports = {
2454 getAdapter: adapterManager.getAdapter.bind(adapterManager),
2455 setAdapters: adapterManager.setAdapters.bind(adapterManager),
2456 adapterManager: adapterManager
2457};
2458
2459/***/ }),
2460/* 44 */
2461/***/ (function(module, exports, __webpack_require__) {
2462
2463module.exports = { "default": __webpack_require__(315), __esModule: true };
2464
2465/***/ }),
2466/* 45 */
2467/***/ (function(module, exports, __webpack_require__) {
2468
2469var META = __webpack_require__(62)('meta');
2470var isObject = __webpack_require__(9);
2471var has = __webpack_require__(25);
2472var setDesc = __webpack_require__(20).f;
2473var id = 0;
2474var isExtensible = Object.isExtensible || function () {
2475 return true;
2476};
2477var FREEZE = !__webpack_require__(28)(function () {
2478 return isExtensible(Object.preventExtensions({}));
2479});
2480var setMeta = function (it) {
2481 setDesc(it, META, { value: {
2482 i: 'O' + ++id, // object ID
2483 w: {} // weak collections IDs
2484 } });
2485};
2486var fastKey = function (it, create) {
2487 // return primitive with prefix
2488 if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
2489 if (!has(it, META)) {
2490 // can't set metadata to uncaught frozen object
2491 if (!isExtensible(it)) return 'F';
2492 // not necessary to add metadata
2493 if (!create) return 'E';
2494 // add missing metadata
2495 setMeta(it);
2496 // return object ID
2497 } return it[META].i;
2498};
2499var getWeak = function (it, create) {
2500 if (!has(it, META)) {
2501 // can't set metadata to uncaught frozen object
2502 if (!isExtensible(it)) return true;
2503 // not necessary to add metadata
2504 if (!create) return false;
2505 // add missing metadata
2506 setMeta(it);
2507 // return hash weak collections IDs
2508 } return it[META].w;
2509};
2510// add metadata on freeze-family methods calling
2511var onFreeze = function (it) {
2512 if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);
2513 return it;
2514};
2515var meta = module.exports = {
2516 KEY: META,
2517 NEED: false,
2518 fastKey: fastKey,
2519 getWeak: getWeak,
2520 onFreeze: onFreeze
2521};
2522
2523
2524/***/ }),
2525/* 46 */
2526/***/ (function(module, exports) {
2527
2528module.exports = true;
2529
2530
2531/***/ }),
2532/* 47 */
2533/***/ (function(module, exports) {
2534
2535module.exports = function (it) {
2536 if (typeof it != 'function') throw TypeError(it + ' is not a function!');
2537 return it;
2538};
2539
2540
2541/***/ }),
2542/* 48 */
2543/***/ (function(module, exports) {
2544
2545module.exports = function (bitmap, value) {
2546 return {
2547 enumerable: !(bitmap & 1),
2548 configurable: !(bitmap & 2),
2549 writable: !(bitmap & 4),
2550 value: value
2551 };
2552};
2553
2554
2555/***/ }),
2556/* 49 */
2557/***/ (function(module, exports, __webpack_require__) {
2558
2559// 19.1.2.14 / 15.2.3.14 Object.keys(O)
2560var $keys = __webpack_require__(117);
2561var enumBugKeys = __webpack_require__(89);
2562
2563module.exports = Object.keys || function keys(O) {
2564 return $keys(O, enumBugKeys);
2565};
2566
2567
2568/***/ }),
2569/* 50 */
2570/***/ (function(module, exports) {
2571
2572var toString = {}.toString;
2573
2574module.exports = function (it) {
2575 return toString.call(it).slice(8, -1);
2576};
2577
2578
2579/***/ }),
2580/* 51 */
2581/***/ (function(module, exports, __webpack_require__) {
2582
2583var def = __webpack_require__(20).f;
2584var has = __webpack_require__(25);
2585var TAG = __webpack_require__(8)('toStringTag');
2586
2587module.exports = function (it, tag, stat) {
2588 if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
2589};
2590
2591
2592/***/ }),
2593/* 52 */
2594/***/ (function(module, __webpack_exports__, __webpack_require__) {
2595
2596"use strict";
2597/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return hasStringTagBug; });
2598/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isIE11; });
2599/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
2600/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__hasObjectTag_js__ = __webpack_require__(235);
2601
2602
2603
2604// In IE 10 - Edge 13, `DataView` has string tag `'[object Object]'`.
2605// In IE 11, the most common among them, this problem also applies to
2606// `Map`, `WeakMap` and `Set`.
2607var hasStringTagBug = (
2608 __WEBPACK_IMPORTED_MODULE_0__setup_js__["s" /* supportsDataView */] && Object(__WEBPACK_IMPORTED_MODULE_1__hasObjectTag_js__["a" /* default */])(new DataView(new ArrayBuffer(8)))
2609 ),
2610 isIE11 = (typeof Map !== 'undefined' && Object(__WEBPACK_IMPORTED_MODULE_1__hasObjectTag_js__["a" /* default */])(new Map));
2611
2612
2613/***/ }),
2614/* 53 */
2615/***/ (function(module, __webpack_exports__, __webpack_require__) {
2616
2617"use strict";
2618/* harmony export (immutable) */ __webpack_exports__["a"] = allKeys;
2619/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isObject_js__ = __webpack_require__(30);
2620/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__setup_js__ = __webpack_require__(2);
2621/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__collectNonEnumProps_js__ = __webpack_require__(139);
2622
2623
2624
2625
2626// Retrieve all the enumerable property names of an object.
2627function allKeys(obj) {
2628 if (!Object(__WEBPACK_IMPORTED_MODULE_0__isObject_js__["a" /* default */])(obj)) return [];
2629 var keys = [];
2630 for (var key in obj) keys.push(key);
2631 // Ahem, IE < 9.
2632 if (__WEBPACK_IMPORTED_MODULE_1__setup_js__["h" /* hasEnumBug */]) Object(__WEBPACK_IMPORTED_MODULE_2__collectNonEnumProps_js__["a" /* default */])(obj, keys);
2633 return keys;
2634}
2635
2636
2637/***/ }),
2638/* 54 */
2639/***/ (function(module, __webpack_exports__, __webpack_require__) {
2640
2641"use strict";
2642/* harmony export (immutable) */ __webpack_exports__["a"] = toPath;
2643/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(12);
2644/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__toPath_js__ = __webpack_require__(148);
2645
2646
2647
2648// Internal wrapper for `_.toPath` to enable minification.
2649// Similar to `cb` for `_.iteratee`.
2650function toPath(path) {
2651 return __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].toPath(path);
2652}
2653
2654
2655/***/ }),
2656/* 55 */
2657/***/ (function(module, __webpack_exports__, __webpack_require__) {
2658
2659"use strict";
2660/* harmony export (immutable) */ __webpack_exports__["a"] = optimizeCb;
2661// Internal function that returns an efficient (for current engines) version
2662// of the passed-in callback, to be repeatedly applied in other Underscore
2663// functions.
2664function optimizeCb(func, context, argCount) {
2665 if (context === void 0) return func;
2666 switch (argCount == null ? 3 : argCount) {
2667 case 1: return function(value) {
2668 return func.call(context, value);
2669 };
2670 // The 2-argument case is omitted because we’re not using it.
2671 case 3: return function(value, index, collection) {
2672 return func.call(context, value, index, collection);
2673 };
2674 case 4: return function(accumulator, value, index, collection) {
2675 return func.call(context, accumulator, value, index, collection);
2676 };
2677 }
2678 return function() {
2679 return func.apply(context, arguments);
2680 };
2681}
2682
2683
2684/***/ }),
2685/* 56 */
2686/***/ (function(module, __webpack_exports__, __webpack_require__) {
2687
2688"use strict";
2689/* harmony export (immutable) */ __webpack_exports__["a"] = filter;
2690/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(10);
2691/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__each_js__ = __webpack_require__(32);
2692
2693
2694
2695// Return all the elements that pass a truth test.
2696function filter(obj, predicate, context) {
2697 var results = [];
2698 predicate = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(predicate, context);
2699 Object(__WEBPACK_IMPORTED_MODULE_1__each_js__["a" /* default */])(obj, function(value, index, list) {
2700 if (predicate(value, index, list)) results.push(value);
2701 });
2702 return results;
2703}
2704
2705
2706/***/ }),
2707/* 57 */
2708/***/ (function(module, __webpack_exports__, __webpack_require__) {
2709
2710"use strict";
2711/* harmony export (immutable) */ __webpack_exports__["a"] = contains;
2712/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__ = __webpack_require__(13);
2713/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__values_js__ = __webpack_require__(39);
2714/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__indexOf_js__ = __webpack_require__(164);
2715
2716
2717
2718
2719// Determine if the array or object contains a given item (using `===`).
2720function contains(obj, item, fromIndex, guard) {
2721 if (!Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj)) obj = Object(__WEBPACK_IMPORTED_MODULE_1__values_js__["a" /* default */])(obj);
2722 if (typeof fromIndex != 'number' || guard) fromIndex = 0;
2723 return Object(__WEBPACK_IMPORTED_MODULE_2__indexOf_js__["a" /* default */])(obj, item, fromIndex) >= 0;
2724}
2725
2726
2727/***/ }),
2728/* 58 */
2729/***/ (function(module, exports, __webpack_require__) {
2730
2731var isObject = __webpack_require__(9);
2732module.exports = function (it, TYPE) {
2733 if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!');
2734 return it;
2735};
2736
2737
2738/***/ }),
2739/* 59 */
2740/***/ (function(module, exports) {
2741
2742
2743
2744/***/ }),
2745/* 60 */
2746/***/ (function(module, exports, __webpack_require__) {
2747
2748// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
2749var anObject = __webpack_require__(15);
2750var dPs = __webpack_require__(116);
2751var enumBugKeys = __webpack_require__(89);
2752var IE_PROTO = __webpack_require__(87)('IE_PROTO');
2753var Empty = function () { /* empty */ };
2754var PROTOTYPE = 'prototype';
2755
2756// Create object with fake `null` prototype: use iframe Object with cleared prototype
2757var createDict = function () {
2758 // Thrash, waste and sodomy: IE GC bug
2759 var iframe = __webpack_require__(83)('iframe');
2760 var i = enumBugKeys.length;
2761 var lt = '<';
2762 var gt = '>';
2763 var iframeDocument;
2764 iframe.style.display = 'none';
2765 __webpack_require__(118).appendChild(iframe);
2766 iframe.src = 'javascript:'; // eslint-disable-line no-script-url
2767 // createDict = iframe.contentWindow.Object;
2768 // html.removeChild(iframe);
2769 iframeDocument = iframe.contentWindow.document;
2770 iframeDocument.open();
2771 iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
2772 iframeDocument.close();
2773 createDict = iframeDocument.F;
2774 while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
2775 return createDict();
2776};
2777
2778module.exports = Object.create || function create(O, Properties) {
2779 var result;
2780 if (O !== null) {
2781 Empty[PROTOTYPE] = anObject(O);
2782 result = new Empty();
2783 Empty[PROTOTYPE] = null;
2784 // add "__proto__" for Object.getPrototypeOf polyfill
2785 result[IE_PROTO] = O;
2786 } else result = createDict();
2787 return Properties === undefined ? result : dPs(result, Properties);
2788};
2789
2790
2791/***/ }),
2792/* 61 */
2793/***/ (function(module, exports, __webpack_require__) {
2794
2795// 7.1.15 ToLength
2796var toInteger = __webpack_require__(80);
2797var min = Math.min;
2798module.exports = function (it) {
2799 return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
2800};
2801
2802
2803/***/ }),
2804/* 62 */
2805/***/ (function(module, exports) {
2806
2807var id = 0;
2808var px = Math.random();
2809module.exports = function (key) {
2810 return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
2811};
2812
2813
2814/***/ }),
2815/* 63 */
2816/***/ (function(module, exports, __webpack_require__) {
2817
2818// getting tag from 19.1.3.6 Object.prototype.toString()
2819var cof = __webpack_require__(50);
2820var TAG = __webpack_require__(8)('toStringTag');
2821// ES3 wrong here
2822var ARG = cof(function () { return arguments; }()) == 'Arguments';
2823
2824// fallback for IE11 Script Access Denied error
2825var tryGet = function (it, key) {
2826 try {
2827 return it[key];
2828 } catch (e) { /* empty */ }
2829};
2830
2831module.exports = function (it) {
2832 var O, T, B;
2833 return it === undefined ? 'Undefined' : it === null ? 'Null'
2834 // @@toStringTag case
2835 : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
2836 // builtinTag case
2837 : ARG ? cof(O)
2838 // ES3 arguments fallback
2839 : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
2840};
2841
2842
2843/***/ }),
2844/* 64 */
2845/***/ (function(module, exports) {
2846
2847module.exports = function (it, Constructor, name, forbiddenField) {
2848 if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) {
2849 throw TypeError(name + ': incorrect invocation!');
2850 } return it;
2851};
2852
2853
2854/***/ }),
2855/* 65 */
2856/***/ (function(module, exports, __webpack_require__) {
2857
2858var hide = __webpack_require__(24);
2859module.exports = function (target, src, safe) {
2860 for (var key in src) {
2861 if (safe && target[key]) target[key] = src[key];
2862 else hide(target, key, src[key]);
2863 } return target;
2864};
2865
2866
2867/***/ }),
2868/* 66 */
2869/***/ (function(module, exports) {
2870
2871var g;
2872
2873// This works in non-strict mode
2874g = (function() {
2875 return this;
2876})();
2877
2878try {
2879 // This works if eval is allowed (see CSP)
2880 g = g || Function("return this")() || (1,eval)("this");
2881} catch(e) {
2882 // This works if the window reference is available
2883 if(typeof window === "object")
2884 g = window;
2885}
2886
2887// g can still be undefined, but nothing to do about it...
2888// We return undefined, instead of nothing here, so it's
2889// easier to handle this case. if(!global) { ...}
2890
2891module.exports = g;
2892
2893
2894/***/ }),
2895/* 67 */
2896/***/ (function(module, __webpack_exports__, __webpack_require__) {
2897
2898"use strict";
2899/* harmony export (immutable) */ __webpack_exports__["a"] = matcher;
2900/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__extendOwn_js__ = __webpack_require__(99);
2901/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isMatch_js__ = __webpack_require__(140);
2902
2903
2904
2905// Returns a predicate for checking whether an object has a given set of
2906// `key:value` pairs.
2907function matcher(attrs) {
2908 attrs = Object(__WEBPACK_IMPORTED_MODULE_0__extendOwn_js__["a" /* default */])({}, attrs);
2909 return function(obj) {
2910 return Object(__WEBPACK_IMPORTED_MODULE_1__isMatch_js__["a" /* default */])(obj, attrs);
2911 };
2912}
2913
2914
2915/***/ }),
2916/* 68 */
2917/***/ (function(module, __webpack_exports__, __webpack_require__) {
2918
2919"use strict";
2920/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(11);
2921/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__executeBound_js__ = __webpack_require__(156);
2922/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__underscore_js__ = __webpack_require__(12);
2923
2924
2925
2926
2927// Partially apply a function by creating a version that has had some of its
2928// arguments pre-filled, without changing its dynamic `this` context. `_` acts
2929// as a placeholder by default, allowing any combination of arguments to be
2930// pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
2931var partial = Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(func, boundArgs) {
2932 var placeholder = partial.placeholder;
2933 var bound = function() {
2934 var position = 0, length = boundArgs.length;
2935 var args = Array(length);
2936 for (var i = 0; i < length; i++) {
2937 args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
2938 }
2939 while (position < arguments.length) args.push(arguments[position++]);
2940 return Object(__WEBPACK_IMPORTED_MODULE_1__executeBound_js__["a" /* default */])(func, bound, this, this, args);
2941 };
2942 return bound;
2943});
2944
2945partial.placeholder = __WEBPACK_IMPORTED_MODULE_2__underscore_js__["a" /* default */];
2946/* harmony default export */ __webpack_exports__["a"] = (partial);
2947
2948
2949/***/ }),
2950/* 69 */
2951/***/ (function(module, __webpack_exports__, __webpack_require__) {
2952
2953"use strict";
2954/* harmony export (immutable) */ __webpack_exports__["a"] = group;
2955/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(10);
2956/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__each_js__ = __webpack_require__(32);
2957
2958
2959
2960// An internal function used for aggregate "group by" operations.
2961function group(behavior, partition) {
2962 return function(obj, iteratee, context) {
2963 var result = partition ? [[], []] : {};
2964 iteratee = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(iteratee, context);
2965 Object(__WEBPACK_IMPORTED_MODULE_1__each_js__["a" /* default */])(obj, function(value, index) {
2966 var key = iteratee(value, index, obj);
2967 behavior(result, value, key);
2968 });
2969 return result;
2970 };
2971}
2972
2973
2974/***/ }),
2975/* 70 */
2976/***/ (function(module, exports, __webpack_require__) {
2977
2978// most Object methods by ES6 should accept primitives
2979var $export = __webpack_require__(4);
2980var core = __webpack_require__(1);
2981var fails = __webpack_require__(28);
2982module.exports = function (KEY, exec) {
2983 var fn = (core.Object || {})[KEY] || Object[KEY];
2984 var exp = {};
2985 exp[KEY] = exec(fn);
2986 $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
2987};
2988
2989
2990/***/ }),
2991/* 71 */
2992/***/ (function(module, exports, __webpack_require__) {
2993
2994module.exports = { "default": __webpack_require__(311), __esModule: true };
2995
2996/***/ }),
2997/* 72 */
2998/***/ (function(module, exports, __webpack_require__) {
2999
3000"use strict";
3001
3002
3003var _stringify = __webpack_require__(21);
3004
3005var _stringify2 = _interopRequireDefault(_stringify);
3006
3007var _typeof2 = __webpack_require__(23);
3008
3009var _typeof3 = _interopRequireDefault(_typeof2);
3010
3011var _keys = __webpack_require__(107);
3012
3013var _keys2 = _interopRequireDefault(_keys);
3014
3015function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
3016
3017var _ = __webpack_require__(0);
3018
3019var _require = __webpack_require__(185),
3020 timeout = _require.timeout;
3021
3022var debug = __webpack_require__(33);
3023var debugRequest = debug('leancloud:request');
3024var debugRequestError = debug('leancloud:request:error');
3025
3026var _require2 = __webpack_require__(43),
3027 getAdapter = _require2.getAdapter;
3028
3029var requestsCount = 0;
3030
3031var ajax = function ajax(_ref) {
3032 var method = _ref.method,
3033 url = _ref.url,
3034 query = _ref.query,
3035 data = _ref.data,
3036 _ref$headers = _ref.headers,
3037 headers = _ref$headers === undefined ? {} : _ref$headers,
3038 time = _ref.timeout,
3039 onprogress = _ref.onprogress;
3040
3041 if (query) {
3042 var queryString = (0, _keys2.default)(query).map(function (key) {
3043 var value = query[key];
3044 if (value === undefined) return undefined;
3045 var v = (typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value)) === 'object' ? (0, _stringify2.default)(value) : value;
3046 return encodeURIComponent(key) + '=' + encodeURIComponent(v);
3047 }).filter(function (qs) {
3048 return qs;
3049 }).join('&');
3050 url = url + '?' + queryString;
3051 }
3052
3053 var count = requestsCount++;
3054 debugRequest('request(%d) %s %s %o %o %o', count, method, url, query, data, headers);
3055
3056 var request = getAdapter('request');
3057 var promise = request(url, { method: method, headers: headers, data: data, onprogress: onprogress }).then(function (response) {
3058 debugRequest('response(%d) %d %O %o', count, response.status, response.data || response.text, response.header);
3059 if (response.ok === false) {
3060 var error = new Error();
3061 error.response = response;
3062 throw error;
3063 }
3064 return response.data;
3065 }).catch(function (error) {
3066 if (error.response) {
3067 if (!debug.enabled('leancloud:request')) {
3068 debugRequestError('request(%d) %s %s %o %o %o', count, method, url, query, data, headers);
3069 }
3070 debugRequestError('response(%d) %d %O %o', count, error.response.status, error.response.data || error.response.text, error.response.header);
3071 error.statusCode = error.response.status;
3072 error.responseText = error.response.text;
3073 error.response = error.response.data;
3074 }
3075 throw error;
3076 });
3077 return time ? timeout(promise, time) : promise;
3078};
3079
3080module.exports = ajax;
3081
3082/***/ }),
3083/* 73 */
3084/***/ (function(module, exports, __webpack_require__) {
3085
3086module.exports = { "default": __webpack_require__(314), __esModule: true };
3087
3088/***/ }),
3089/* 74 */
3090/***/ (function(module, exports) {
3091
3092exports.f = Object.getOwnPropertySymbols;
3093
3094
3095/***/ }),
3096/* 75 */
3097/***/ (function(module, exports) {
3098
3099exports.f = {}.propertyIsEnumerable;
3100
3101
3102/***/ }),
3103/* 76 */
3104/***/ (function(module, exports, __webpack_require__) {
3105
3106var pIE = __webpack_require__(75);
3107var createDesc = __webpack_require__(48);
3108var toIObject = __webpack_require__(26);
3109var toPrimitive = __webpack_require__(84);
3110var has = __webpack_require__(25);
3111var IE8_DOM_DEFINE = __webpack_require__(115);
3112var gOPD = Object.getOwnPropertyDescriptor;
3113
3114exports.f = __webpack_require__(16) ? gOPD : function getOwnPropertyDescriptor(O, P) {
3115 O = toIObject(O);
3116 P = toPrimitive(P, true);
3117 if (IE8_DOM_DEFINE) try {
3118 return gOPD(O, P);
3119 } catch (e) { /* empty */ }
3120 if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
3121};
3122
3123
3124/***/ }),
3125/* 77 */
3126/***/ (function(module, exports) {
3127
3128/* (ignored) */
3129
3130/***/ }),
3131/* 78 */
3132/***/ (function(module, exports, __webpack_require__) {
3133
3134var Symbol = __webpack_require__(205),
3135 getRawTag = __webpack_require__(437),
3136 objectToString = __webpack_require__(438);
3137
3138/** `Object#toString` result references. */
3139var nullTag = '[object Null]',
3140 undefinedTag = '[object Undefined]';
3141
3142/** Built-in value references. */
3143var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
3144
3145/**
3146 * The base implementation of `getTag` without fallbacks for buggy environments.
3147 *
3148 * @private
3149 * @param {*} value The value to query.
3150 * @returns {string} Returns the `toStringTag`.
3151 */
3152function baseGetTag(value) {
3153 if (value == null) {
3154 return value === undefined ? undefinedTag : nullTag;
3155 }
3156 return (symToStringTag && symToStringTag in Object(value))
3157 ? getRawTag(value)
3158 : objectToString(value);
3159}
3160
3161module.exports = baseGetTag;
3162
3163
3164/***/ }),
3165/* 79 */
3166/***/ (function(module, exports) {
3167
3168/**
3169 * Checks if `value` is object-like. A value is object-like if it's not `null`
3170 * and has a `typeof` result of "object".
3171 *
3172 * @static
3173 * @memberOf _
3174 * @since 4.0.0
3175 * @category Lang
3176 * @param {*} value The value to check.
3177 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
3178 * @example
3179 *
3180 * _.isObjectLike({});
3181 * // => true
3182 *
3183 * _.isObjectLike([1, 2, 3]);
3184 * // => true
3185 *
3186 * _.isObjectLike(_.noop);
3187 * // => false
3188 *
3189 * _.isObjectLike(null);
3190 * // => false
3191 */
3192function isObjectLike(value) {
3193 return value != null && typeof value == 'object';
3194}
3195
3196module.exports = isObjectLike;
3197
3198
3199/***/ }),
3200/* 80 */
3201/***/ (function(module, exports) {
3202
3203// 7.1.4 ToInteger
3204var ceil = Math.ceil;
3205var floor = Math.floor;
3206module.exports = function (it) {
3207 return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
3208};
3209
3210
3211/***/ }),
3212/* 81 */
3213/***/ (function(module, exports) {
3214
3215// 7.2.1 RequireObjectCoercible(argument)
3216module.exports = function (it) {
3217 if (it == undefined) throw TypeError("Can't call method on " + it);
3218 return it;
3219};
3220
3221
3222/***/ }),
3223/* 82 */
3224/***/ (function(module, exports, __webpack_require__) {
3225
3226"use strict";
3227
3228var LIBRARY = __webpack_require__(46);
3229var $export = __webpack_require__(4);
3230var redefine = __webpack_require__(85);
3231var hide = __webpack_require__(24);
3232var Iterators = __webpack_require__(36);
3233var $iterCreate = __webpack_require__(218);
3234var setToStringTag = __webpack_require__(51);
3235var getPrototypeOf = __webpack_require__(119);
3236var ITERATOR = __webpack_require__(8)('iterator');
3237var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
3238var FF_ITERATOR = '@@iterator';
3239var KEYS = 'keys';
3240var VALUES = 'values';
3241
3242var returnThis = function () { return this; };
3243
3244module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
3245 $iterCreate(Constructor, NAME, next);
3246 var getMethod = function (kind) {
3247 if (!BUGGY && kind in proto) return proto[kind];
3248 switch (kind) {
3249 case KEYS: return function keys() { return new Constructor(this, kind); };
3250 case VALUES: return function values() { return new Constructor(this, kind); };
3251 } return function entries() { return new Constructor(this, kind); };
3252 };
3253 var TAG = NAME + ' Iterator';
3254 var DEF_VALUES = DEFAULT == VALUES;
3255 var VALUES_BUG = false;
3256 var proto = Base.prototype;
3257 var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
3258 var $default = $native || getMethod(DEFAULT);
3259 var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
3260 var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
3261 var methods, key, IteratorPrototype;
3262 // Fix native
3263 if ($anyNative) {
3264 IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
3265 if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
3266 // Set @@toStringTag to native iterators
3267 setToStringTag(IteratorPrototype, TAG, true);
3268 // fix for some old engines
3269 if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);
3270 }
3271 }
3272 // fix Array#{values, @@iterator}.name in V8 / FF
3273 if (DEF_VALUES && $native && $native.name !== VALUES) {
3274 VALUES_BUG = true;
3275 $default = function values() { return $native.call(this); };
3276 }
3277 // Define iterator
3278 if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
3279 hide(proto, ITERATOR, $default);
3280 }
3281 // Plug for library
3282 Iterators[NAME] = $default;
3283 Iterators[TAG] = returnThis;
3284 if (DEFAULT) {
3285 methods = {
3286 values: DEF_VALUES ? $default : getMethod(VALUES),
3287 keys: IS_SET ? $default : getMethod(KEYS),
3288 entries: $entries
3289 };
3290 if (FORCED) for (key in methods) {
3291 if (!(key in proto)) redefine(proto, key, methods[key]);
3292 } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
3293 }
3294 return methods;
3295};
3296
3297
3298/***/ }),
3299/* 83 */
3300/***/ (function(module, exports, __webpack_require__) {
3301
3302var isObject = __webpack_require__(9);
3303var document = __webpack_require__(5).document;
3304// typeof document.createElement is 'object' in old IE
3305var is = isObject(document) && isObject(document.createElement);
3306module.exports = function (it) {
3307 return is ? document.createElement(it) : {};
3308};
3309
3310
3311/***/ }),
3312/* 84 */
3313/***/ (function(module, exports, __webpack_require__) {
3314
3315// 7.1.1 ToPrimitive(input [, PreferredType])
3316var isObject = __webpack_require__(9);
3317// instead of the ES6 spec version, we didn't implement @@toPrimitive case
3318// and the second argument - flag - preferred type is a string
3319module.exports = function (it, S) {
3320 if (!isObject(it)) return it;
3321 var fn, val;
3322 if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
3323 if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
3324 if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
3325 throw TypeError("Can't convert object to primitive value");
3326};
3327
3328
3329/***/ }),
3330/* 85 */
3331/***/ (function(module, exports, __webpack_require__) {
3332
3333module.exports = __webpack_require__(24);
3334
3335
3336/***/ }),
3337/* 86 */
3338/***/ (function(module, exports, __webpack_require__) {
3339
3340// fallback for non-array-like ES3 and non-enumerable old V8 strings
3341var cof = __webpack_require__(50);
3342// eslint-disable-next-line no-prototype-builtins
3343module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
3344 return cof(it) == 'String' ? it.split('') : Object(it);
3345};
3346
3347
3348/***/ }),
3349/* 87 */
3350/***/ (function(module, exports, __webpack_require__) {
3351
3352var shared = __webpack_require__(88)('keys');
3353var uid = __webpack_require__(62);
3354module.exports = function (key) {
3355 return shared[key] || (shared[key] = uid(key));
3356};
3357
3358
3359/***/ }),
3360/* 88 */
3361/***/ (function(module, exports, __webpack_require__) {
3362
3363var core = __webpack_require__(1);
3364var global = __webpack_require__(5);
3365var SHARED = '__core-js_shared__';
3366var store = global[SHARED] || (global[SHARED] = {});
3367
3368(module.exports = function (key, value) {
3369 return store[key] || (store[key] = value !== undefined ? value : {});
3370})('versions', []).push({
3371 version: core.version,
3372 mode: __webpack_require__(46) ? 'pure' : 'global',
3373 copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
3374});
3375
3376
3377/***/ }),
3378/* 89 */
3379/***/ (function(module, exports) {
3380
3381// IE 8- don't enum bug keys
3382module.exports = (
3383 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
3384).split(',');
3385
3386
3387/***/ }),
3388/* 90 */
3389/***/ (function(module, exports, __webpack_require__) {
3390
3391var classof = __webpack_require__(63);
3392var ITERATOR = __webpack_require__(8)('iterator');
3393var Iterators = __webpack_require__(36);
3394module.exports = __webpack_require__(1).getIteratorMethod = function (it) {
3395 if (it != undefined) return it[ITERATOR]
3396 || it['@@iterator']
3397 || Iterators[classof(it)];
3398};
3399
3400
3401/***/ }),
3402/* 91 */
3403/***/ (function(module, exports, __webpack_require__) {
3404
3405"use strict";
3406
3407// 25.4.1.5 NewPromiseCapability(C)
3408var aFunction = __webpack_require__(47);
3409
3410function PromiseCapability(C) {
3411 var resolve, reject;
3412 this.promise = new C(function ($$resolve, $$reject) {
3413 if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
3414 resolve = $$resolve;
3415 reject = $$reject;
3416 });
3417 this.resolve = aFunction(resolve);
3418 this.reject = aFunction(reject);
3419}
3420
3421module.exports.f = function (C) {
3422 return new PromiseCapability(C);
3423};
3424
3425
3426/***/ }),
3427/* 92 */
3428/***/ (function(module, __webpack_exports__, __webpack_require__) {
3429
3430"use strict";
3431Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
3432/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
3433/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "VERSION", function() { return __WEBPACK_IMPORTED_MODULE_0__setup_js__["e"]; });
3434/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__restArguments_js__ = __webpack_require__(11);
3435/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "restArguments", function() { return __WEBPACK_IMPORTED_MODULE_1__restArguments_js__["a"]; });
3436/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isObject_js__ = __webpack_require__(30);
3437/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isObject", function() { return __WEBPACK_IMPORTED_MODULE_2__isObject_js__["a"]; });
3438/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isNull_js__ = __webpack_require__(230);
3439/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isNull", function() { return __WEBPACK_IMPORTED_MODULE_3__isNull_js__["a"]; });
3440/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__isUndefined_js__ = __webpack_require__(129);
3441/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isUndefined", function() { return __WEBPACK_IMPORTED_MODULE_4__isUndefined_js__["a"]; });
3442/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__isBoolean_js__ = __webpack_require__(130);
3443/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isBoolean", function() { return __WEBPACK_IMPORTED_MODULE_5__isBoolean_js__["a"]; });
3444/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__isElement_js__ = __webpack_require__(231);
3445/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isElement", function() { return __WEBPACK_IMPORTED_MODULE_6__isElement_js__["a"]; });
3446/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__isString_js__ = __webpack_require__(93);
3447/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isString", function() { return __WEBPACK_IMPORTED_MODULE_7__isString_js__["a"]; });
3448/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__isNumber_js__ = __webpack_require__(131);
3449/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isNumber", function() { return __WEBPACK_IMPORTED_MODULE_8__isNumber_js__["a"]; });
3450/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__isDate_js__ = __webpack_require__(232);
3451/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isDate", function() { return __WEBPACK_IMPORTED_MODULE_9__isDate_js__["a"]; });
3452/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__isRegExp_js__ = __webpack_require__(233);
3453/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isRegExp", function() { return __WEBPACK_IMPORTED_MODULE_10__isRegExp_js__["a"]; });
3454/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__isError_js__ = __webpack_require__(234);
3455/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isError", function() { return __WEBPACK_IMPORTED_MODULE_11__isError_js__["a"]; });
3456/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__isSymbol_js__ = __webpack_require__(132);
3457/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isSymbol", function() { return __WEBPACK_IMPORTED_MODULE_12__isSymbol_js__["a"]; });
3458/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__isArrayBuffer_js__ = __webpack_require__(133);
3459/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isArrayBuffer", function() { return __WEBPACK_IMPORTED_MODULE_13__isArrayBuffer_js__["a"]; });
3460/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__isDataView_js__ = __webpack_require__(94);
3461/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isDataView", function() { return __WEBPACK_IMPORTED_MODULE_14__isDataView_js__["a"]; });
3462/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__isArray_js__ = __webpack_require__(31);
3463/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isArray", function() { return __WEBPACK_IMPORTED_MODULE_15__isArray_js__["a"]; });
3464/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__isFunction_js__ = __webpack_require__(17);
3465/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isFunction", function() { return __WEBPACK_IMPORTED_MODULE_16__isFunction_js__["a"]; });
3466/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__isArguments_js__ = __webpack_require__(95);
3467/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isArguments", function() { return __WEBPACK_IMPORTED_MODULE_17__isArguments_js__["a"]; });
3468/* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__isFinite_js__ = __webpack_require__(236);
3469/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isFinite", function() { return __WEBPACK_IMPORTED_MODULE_18__isFinite_js__["a"]; });
3470/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__isNaN_js__ = __webpack_require__(134);
3471/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isNaN", function() { return __WEBPACK_IMPORTED_MODULE_19__isNaN_js__["a"]; });
3472/* harmony import */ var __WEBPACK_IMPORTED_MODULE_20__isTypedArray_js__ = __webpack_require__(135);
3473/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isTypedArray", function() { return __WEBPACK_IMPORTED_MODULE_20__isTypedArray_js__["a"]; });
3474/* harmony import */ var __WEBPACK_IMPORTED_MODULE_21__isEmpty_js__ = __webpack_require__(238);
3475/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isEmpty", function() { return __WEBPACK_IMPORTED_MODULE_21__isEmpty_js__["a"]; });
3476/* harmony import */ var __WEBPACK_IMPORTED_MODULE_22__isMatch_js__ = __webpack_require__(140);
3477/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isMatch", function() { return __WEBPACK_IMPORTED_MODULE_22__isMatch_js__["a"]; });
3478/* harmony import */ var __WEBPACK_IMPORTED_MODULE_23__isEqual_js__ = __webpack_require__(239);
3479/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isEqual", function() { return __WEBPACK_IMPORTED_MODULE_23__isEqual_js__["a"]; });
3480/* harmony import */ var __WEBPACK_IMPORTED_MODULE_24__isMap_js__ = __webpack_require__(241);
3481/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isMap", function() { return __WEBPACK_IMPORTED_MODULE_24__isMap_js__["a"]; });
3482/* harmony import */ var __WEBPACK_IMPORTED_MODULE_25__isWeakMap_js__ = __webpack_require__(242);
3483/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isWeakMap", function() { return __WEBPACK_IMPORTED_MODULE_25__isWeakMap_js__["a"]; });
3484/* harmony import */ var __WEBPACK_IMPORTED_MODULE_26__isSet_js__ = __webpack_require__(243);
3485/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isSet", function() { return __WEBPACK_IMPORTED_MODULE_26__isSet_js__["a"]; });
3486/* harmony import */ var __WEBPACK_IMPORTED_MODULE_27__isWeakSet_js__ = __webpack_require__(244);
3487/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isWeakSet", function() { return __WEBPACK_IMPORTED_MODULE_27__isWeakSet_js__["a"]; });
3488/* harmony import */ var __WEBPACK_IMPORTED_MODULE_28__keys_js__ = __webpack_require__(6);
3489/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "keys", function() { return __WEBPACK_IMPORTED_MODULE_28__keys_js__["a"]; });
3490/* harmony import */ var __WEBPACK_IMPORTED_MODULE_29__allKeys_js__ = __webpack_require__(53);
3491/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "allKeys", function() { return __WEBPACK_IMPORTED_MODULE_29__allKeys_js__["a"]; });
3492/* harmony import */ var __WEBPACK_IMPORTED_MODULE_30__values_js__ = __webpack_require__(39);
3493/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "values", function() { return __WEBPACK_IMPORTED_MODULE_30__values_js__["a"]; });
3494/* harmony import */ var __WEBPACK_IMPORTED_MODULE_31__pairs_js__ = __webpack_require__(245);
3495/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "pairs", function() { return __WEBPACK_IMPORTED_MODULE_31__pairs_js__["a"]; });
3496/* harmony import */ var __WEBPACK_IMPORTED_MODULE_32__invert_js__ = __webpack_require__(141);
3497/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "invert", function() { return __WEBPACK_IMPORTED_MODULE_32__invert_js__["a"]; });
3498/* harmony import */ var __WEBPACK_IMPORTED_MODULE_33__functions_js__ = __webpack_require__(142);
3499/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "functions", function() { return __WEBPACK_IMPORTED_MODULE_33__functions_js__["a"]; });
3500/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "methods", function() { return __WEBPACK_IMPORTED_MODULE_33__functions_js__["a"]; });
3501/* harmony import */ var __WEBPACK_IMPORTED_MODULE_34__extend_js__ = __webpack_require__(143);
3502/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "extend", function() { return __WEBPACK_IMPORTED_MODULE_34__extend_js__["a"]; });
3503/* harmony import */ var __WEBPACK_IMPORTED_MODULE_35__extendOwn_js__ = __webpack_require__(99);
3504/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "extendOwn", function() { return __WEBPACK_IMPORTED_MODULE_35__extendOwn_js__["a"]; });
3505/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "assign", function() { return __WEBPACK_IMPORTED_MODULE_35__extendOwn_js__["a"]; });
3506/* harmony import */ var __WEBPACK_IMPORTED_MODULE_36__defaults_js__ = __webpack_require__(144);
3507/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "defaults", function() { return __WEBPACK_IMPORTED_MODULE_36__defaults_js__["a"]; });
3508/* harmony import */ var __WEBPACK_IMPORTED_MODULE_37__create_js__ = __webpack_require__(246);
3509/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "create", function() { return __WEBPACK_IMPORTED_MODULE_37__create_js__["a"]; });
3510/* harmony import */ var __WEBPACK_IMPORTED_MODULE_38__clone_js__ = __webpack_require__(146);
3511/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "clone", function() { return __WEBPACK_IMPORTED_MODULE_38__clone_js__["a"]; });
3512/* harmony import */ var __WEBPACK_IMPORTED_MODULE_39__tap_js__ = __webpack_require__(247);
3513/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "tap", function() { return __WEBPACK_IMPORTED_MODULE_39__tap_js__["a"]; });
3514/* harmony import */ var __WEBPACK_IMPORTED_MODULE_40__get_js__ = __webpack_require__(147);
3515/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "get", function() { return __WEBPACK_IMPORTED_MODULE_40__get_js__["a"]; });
3516/* harmony import */ var __WEBPACK_IMPORTED_MODULE_41__has_js__ = __webpack_require__(248);
3517/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "has", function() { return __WEBPACK_IMPORTED_MODULE_41__has_js__["a"]; });
3518/* harmony import */ var __WEBPACK_IMPORTED_MODULE_42__mapObject_js__ = __webpack_require__(249);
3519/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "mapObject", function() { return __WEBPACK_IMPORTED_MODULE_42__mapObject_js__["a"]; });
3520/* harmony import */ var __WEBPACK_IMPORTED_MODULE_43__identity_js__ = __webpack_require__(101);
3521/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "identity", function() { return __WEBPACK_IMPORTED_MODULE_43__identity_js__["a"]; });
3522/* harmony import */ var __WEBPACK_IMPORTED_MODULE_44__constant_js__ = __webpack_require__(136);
3523/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "constant", function() { return __WEBPACK_IMPORTED_MODULE_44__constant_js__["a"]; });
3524/* harmony import */ var __WEBPACK_IMPORTED_MODULE_45__noop_js__ = __webpack_require__(151);
3525/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "noop", function() { return __WEBPACK_IMPORTED_MODULE_45__noop_js__["a"]; });
3526/* harmony import */ var __WEBPACK_IMPORTED_MODULE_46__toPath_js__ = __webpack_require__(148);
3527/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "toPath", function() { return __WEBPACK_IMPORTED_MODULE_46__toPath_js__["a"]; });
3528/* harmony import */ var __WEBPACK_IMPORTED_MODULE_47__property_js__ = __webpack_require__(102);
3529/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "property", function() { return __WEBPACK_IMPORTED_MODULE_47__property_js__["a"]; });
3530/* harmony import */ var __WEBPACK_IMPORTED_MODULE_48__propertyOf_js__ = __webpack_require__(250);
3531/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "propertyOf", function() { return __WEBPACK_IMPORTED_MODULE_48__propertyOf_js__["a"]; });
3532/* harmony import */ var __WEBPACK_IMPORTED_MODULE_49__matcher_js__ = __webpack_require__(67);
3533/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "matcher", function() { return __WEBPACK_IMPORTED_MODULE_49__matcher_js__["a"]; });
3534/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "matches", function() { return __WEBPACK_IMPORTED_MODULE_49__matcher_js__["a"]; });
3535/* harmony import */ var __WEBPACK_IMPORTED_MODULE_50__times_js__ = __webpack_require__(251);
3536/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "times", function() { return __WEBPACK_IMPORTED_MODULE_50__times_js__["a"]; });
3537/* harmony import */ var __WEBPACK_IMPORTED_MODULE_51__random_js__ = __webpack_require__(152);
3538/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "random", function() { return __WEBPACK_IMPORTED_MODULE_51__random_js__["a"]; });
3539/* harmony import */ var __WEBPACK_IMPORTED_MODULE_52__now_js__ = __webpack_require__(103);
3540/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "now", function() { return __WEBPACK_IMPORTED_MODULE_52__now_js__["a"]; });
3541/* harmony import */ var __WEBPACK_IMPORTED_MODULE_53__escape_js__ = __webpack_require__(252);
3542/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "escape", function() { return __WEBPACK_IMPORTED_MODULE_53__escape_js__["a"]; });
3543/* harmony import */ var __WEBPACK_IMPORTED_MODULE_54__unescape_js__ = __webpack_require__(253);
3544/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "unescape", function() { return __WEBPACK_IMPORTED_MODULE_54__unescape_js__["a"]; });
3545/* harmony import */ var __WEBPACK_IMPORTED_MODULE_55__templateSettings_js__ = __webpack_require__(155);
3546/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "templateSettings", function() { return __WEBPACK_IMPORTED_MODULE_55__templateSettings_js__["a"]; });
3547/* harmony import */ var __WEBPACK_IMPORTED_MODULE_56__template_js__ = __webpack_require__(255);
3548/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "template", function() { return __WEBPACK_IMPORTED_MODULE_56__template_js__["a"]; });
3549/* harmony import */ var __WEBPACK_IMPORTED_MODULE_57__result_js__ = __webpack_require__(256);
3550/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "result", function() { return __WEBPACK_IMPORTED_MODULE_57__result_js__["a"]; });
3551/* harmony import */ var __WEBPACK_IMPORTED_MODULE_58__uniqueId_js__ = __webpack_require__(257);
3552/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "uniqueId", function() { return __WEBPACK_IMPORTED_MODULE_58__uniqueId_js__["a"]; });
3553/* harmony import */ var __WEBPACK_IMPORTED_MODULE_59__chain_js__ = __webpack_require__(258);
3554/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "chain", function() { return __WEBPACK_IMPORTED_MODULE_59__chain_js__["a"]; });
3555/* harmony import */ var __WEBPACK_IMPORTED_MODULE_60__iteratee_js__ = __webpack_require__(150);
3556/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "iteratee", function() { return __WEBPACK_IMPORTED_MODULE_60__iteratee_js__["a"]; });
3557/* harmony import */ var __WEBPACK_IMPORTED_MODULE_61__partial_js__ = __webpack_require__(68);
3558/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "partial", function() { return __WEBPACK_IMPORTED_MODULE_61__partial_js__["a"]; });
3559/* harmony import */ var __WEBPACK_IMPORTED_MODULE_62__bind_js__ = __webpack_require__(157);
3560/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "bind", function() { return __WEBPACK_IMPORTED_MODULE_62__bind_js__["a"]; });
3561/* harmony import */ var __WEBPACK_IMPORTED_MODULE_63__bindAll_js__ = __webpack_require__(259);
3562/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "bindAll", function() { return __WEBPACK_IMPORTED_MODULE_63__bindAll_js__["a"]; });
3563/* harmony import */ var __WEBPACK_IMPORTED_MODULE_64__memoize_js__ = __webpack_require__(260);
3564/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "memoize", function() { return __WEBPACK_IMPORTED_MODULE_64__memoize_js__["a"]; });
3565/* harmony import */ var __WEBPACK_IMPORTED_MODULE_65__delay_js__ = __webpack_require__(158);
3566/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "delay", function() { return __WEBPACK_IMPORTED_MODULE_65__delay_js__["a"]; });
3567/* harmony import */ var __WEBPACK_IMPORTED_MODULE_66__defer_js__ = __webpack_require__(261);
3568/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "defer", function() { return __WEBPACK_IMPORTED_MODULE_66__defer_js__["a"]; });
3569/* harmony import */ var __WEBPACK_IMPORTED_MODULE_67__throttle_js__ = __webpack_require__(262);
3570/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "throttle", function() { return __WEBPACK_IMPORTED_MODULE_67__throttle_js__["a"]; });
3571/* harmony import */ var __WEBPACK_IMPORTED_MODULE_68__debounce_js__ = __webpack_require__(263);
3572/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "debounce", function() { return __WEBPACK_IMPORTED_MODULE_68__debounce_js__["a"]; });
3573/* harmony import */ var __WEBPACK_IMPORTED_MODULE_69__wrap_js__ = __webpack_require__(264);
3574/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "wrap", function() { return __WEBPACK_IMPORTED_MODULE_69__wrap_js__["a"]; });
3575/* harmony import */ var __WEBPACK_IMPORTED_MODULE_70__negate_js__ = __webpack_require__(104);
3576/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "negate", function() { return __WEBPACK_IMPORTED_MODULE_70__negate_js__["a"]; });
3577/* harmony import */ var __WEBPACK_IMPORTED_MODULE_71__compose_js__ = __webpack_require__(265);
3578/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "compose", function() { return __WEBPACK_IMPORTED_MODULE_71__compose_js__["a"]; });
3579/* harmony import */ var __WEBPACK_IMPORTED_MODULE_72__after_js__ = __webpack_require__(266);
3580/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "after", function() { return __WEBPACK_IMPORTED_MODULE_72__after_js__["a"]; });
3581/* harmony import */ var __WEBPACK_IMPORTED_MODULE_73__before_js__ = __webpack_require__(159);
3582/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "before", function() { return __WEBPACK_IMPORTED_MODULE_73__before_js__["a"]; });
3583/* harmony import */ var __WEBPACK_IMPORTED_MODULE_74__once_js__ = __webpack_require__(267);
3584/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "once", function() { return __WEBPACK_IMPORTED_MODULE_74__once_js__["a"]; });
3585/* harmony import */ var __WEBPACK_IMPORTED_MODULE_75__findKey_js__ = __webpack_require__(160);
3586/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "findKey", function() { return __WEBPACK_IMPORTED_MODULE_75__findKey_js__["a"]; });
3587/* harmony import */ var __WEBPACK_IMPORTED_MODULE_76__findIndex_js__ = __webpack_require__(105);
3588/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "findIndex", function() { return __WEBPACK_IMPORTED_MODULE_76__findIndex_js__["a"]; });
3589/* harmony import */ var __WEBPACK_IMPORTED_MODULE_77__findLastIndex_js__ = __webpack_require__(162);
3590/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "findLastIndex", function() { return __WEBPACK_IMPORTED_MODULE_77__findLastIndex_js__["a"]; });
3591/* harmony import */ var __WEBPACK_IMPORTED_MODULE_78__sortedIndex_js__ = __webpack_require__(163);
3592/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "sortedIndex", function() { return __WEBPACK_IMPORTED_MODULE_78__sortedIndex_js__["a"]; });
3593/* harmony import */ var __WEBPACK_IMPORTED_MODULE_79__indexOf_js__ = __webpack_require__(164);
3594/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "indexOf", function() { return __WEBPACK_IMPORTED_MODULE_79__indexOf_js__["a"]; });
3595/* harmony import */ var __WEBPACK_IMPORTED_MODULE_80__lastIndexOf_js__ = __webpack_require__(268);
3596/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "lastIndexOf", function() { return __WEBPACK_IMPORTED_MODULE_80__lastIndexOf_js__["a"]; });
3597/* harmony import */ var __WEBPACK_IMPORTED_MODULE_81__find_js__ = __webpack_require__(166);
3598/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "find", function() { return __WEBPACK_IMPORTED_MODULE_81__find_js__["a"]; });
3599/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "detect", function() { return __WEBPACK_IMPORTED_MODULE_81__find_js__["a"]; });
3600/* harmony import */ var __WEBPACK_IMPORTED_MODULE_82__findWhere_js__ = __webpack_require__(269);
3601/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "findWhere", function() { return __WEBPACK_IMPORTED_MODULE_82__findWhere_js__["a"]; });
3602/* harmony import */ var __WEBPACK_IMPORTED_MODULE_83__each_js__ = __webpack_require__(32);
3603/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "each", function() { return __WEBPACK_IMPORTED_MODULE_83__each_js__["a"]; });
3604/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "forEach", function() { return __WEBPACK_IMPORTED_MODULE_83__each_js__["a"]; });
3605/* harmony import */ var __WEBPACK_IMPORTED_MODULE_84__map_js__ = __webpack_require__(41);
3606/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "map", function() { return __WEBPACK_IMPORTED_MODULE_84__map_js__["a"]; });
3607/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "collect", function() { return __WEBPACK_IMPORTED_MODULE_84__map_js__["a"]; });
3608/* harmony import */ var __WEBPACK_IMPORTED_MODULE_85__reduce_js__ = __webpack_require__(270);
3609/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "reduce", function() { return __WEBPACK_IMPORTED_MODULE_85__reduce_js__["a"]; });
3610/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "foldl", function() { return __WEBPACK_IMPORTED_MODULE_85__reduce_js__["a"]; });
3611/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "inject", function() { return __WEBPACK_IMPORTED_MODULE_85__reduce_js__["a"]; });
3612/* harmony import */ var __WEBPACK_IMPORTED_MODULE_86__reduceRight_js__ = __webpack_require__(271);
3613/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "reduceRight", function() { return __WEBPACK_IMPORTED_MODULE_86__reduceRight_js__["a"]; });
3614/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "foldr", function() { return __WEBPACK_IMPORTED_MODULE_86__reduceRight_js__["a"]; });
3615/* harmony import */ var __WEBPACK_IMPORTED_MODULE_87__filter_js__ = __webpack_require__(56);
3616/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "filter", function() { return __WEBPACK_IMPORTED_MODULE_87__filter_js__["a"]; });
3617/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "select", function() { return __WEBPACK_IMPORTED_MODULE_87__filter_js__["a"]; });
3618/* harmony import */ var __WEBPACK_IMPORTED_MODULE_88__reject_js__ = __webpack_require__(272);
3619/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "reject", function() { return __WEBPACK_IMPORTED_MODULE_88__reject_js__["a"]; });
3620/* harmony import */ var __WEBPACK_IMPORTED_MODULE_89__every_js__ = __webpack_require__(273);
3621/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "every", function() { return __WEBPACK_IMPORTED_MODULE_89__every_js__["a"]; });
3622/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "all", function() { return __WEBPACK_IMPORTED_MODULE_89__every_js__["a"]; });
3623/* harmony import */ var __WEBPACK_IMPORTED_MODULE_90__some_js__ = __webpack_require__(274);
3624/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "some", function() { return __WEBPACK_IMPORTED_MODULE_90__some_js__["a"]; });
3625/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "any", function() { return __WEBPACK_IMPORTED_MODULE_90__some_js__["a"]; });
3626/* harmony import */ var __WEBPACK_IMPORTED_MODULE_91__contains_js__ = __webpack_require__(57);
3627/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "contains", function() { return __WEBPACK_IMPORTED_MODULE_91__contains_js__["a"]; });
3628/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "includes", function() { return __WEBPACK_IMPORTED_MODULE_91__contains_js__["a"]; });
3629/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "include", function() { return __WEBPACK_IMPORTED_MODULE_91__contains_js__["a"]; });
3630/* harmony import */ var __WEBPACK_IMPORTED_MODULE_92__invoke_js__ = __webpack_require__(275);
3631/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "invoke", function() { return __WEBPACK_IMPORTED_MODULE_92__invoke_js__["a"]; });
3632/* harmony import */ var __WEBPACK_IMPORTED_MODULE_93__pluck_js__ = __webpack_require__(106);
3633/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "pluck", function() { return __WEBPACK_IMPORTED_MODULE_93__pluck_js__["a"]; });
3634/* harmony import */ var __WEBPACK_IMPORTED_MODULE_94__where_js__ = __webpack_require__(276);
3635/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "where", function() { return __WEBPACK_IMPORTED_MODULE_94__where_js__["a"]; });
3636/* harmony import */ var __WEBPACK_IMPORTED_MODULE_95__max_js__ = __webpack_require__(168);
3637/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "max", function() { return __WEBPACK_IMPORTED_MODULE_95__max_js__["a"]; });
3638/* harmony import */ var __WEBPACK_IMPORTED_MODULE_96__min_js__ = __webpack_require__(277);
3639/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "min", function() { return __WEBPACK_IMPORTED_MODULE_96__min_js__["a"]; });
3640/* harmony import */ var __WEBPACK_IMPORTED_MODULE_97__shuffle_js__ = __webpack_require__(278);
3641/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "shuffle", function() { return __WEBPACK_IMPORTED_MODULE_97__shuffle_js__["a"]; });
3642/* harmony import */ var __WEBPACK_IMPORTED_MODULE_98__sample_js__ = __webpack_require__(169);
3643/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "sample", function() { return __WEBPACK_IMPORTED_MODULE_98__sample_js__["a"]; });
3644/* harmony import */ var __WEBPACK_IMPORTED_MODULE_99__sortBy_js__ = __webpack_require__(279);
3645/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "sortBy", function() { return __WEBPACK_IMPORTED_MODULE_99__sortBy_js__["a"]; });
3646/* harmony import */ var __WEBPACK_IMPORTED_MODULE_100__groupBy_js__ = __webpack_require__(280);
3647/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "groupBy", function() { return __WEBPACK_IMPORTED_MODULE_100__groupBy_js__["a"]; });
3648/* harmony import */ var __WEBPACK_IMPORTED_MODULE_101__indexBy_js__ = __webpack_require__(281);
3649/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "indexBy", function() { return __WEBPACK_IMPORTED_MODULE_101__indexBy_js__["a"]; });
3650/* harmony import */ var __WEBPACK_IMPORTED_MODULE_102__countBy_js__ = __webpack_require__(282);
3651/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "countBy", function() { return __WEBPACK_IMPORTED_MODULE_102__countBy_js__["a"]; });
3652/* harmony import */ var __WEBPACK_IMPORTED_MODULE_103__partition_js__ = __webpack_require__(283);
3653/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return __WEBPACK_IMPORTED_MODULE_103__partition_js__["a"]; });
3654/* harmony import */ var __WEBPACK_IMPORTED_MODULE_104__toArray_js__ = __webpack_require__(284);
3655/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "toArray", function() { return __WEBPACK_IMPORTED_MODULE_104__toArray_js__["a"]; });
3656/* harmony import */ var __WEBPACK_IMPORTED_MODULE_105__size_js__ = __webpack_require__(285);
3657/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "size", function() { return __WEBPACK_IMPORTED_MODULE_105__size_js__["a"]; });
3658/* harmony import */ var __WEBPACK_IMPORTED_MODULE_106__pick_js__ = __webpack_require__(170);
3659/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "pick", function() { return __WEBPACK_IMPORTED_MODULE_106__pick_js__["a"]; });
3660/* harmony import */ var __WEBPACK_IMPORTED_MODULE_107__omit_js__ = __webpack_require__(287);
3661/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "omit", function() { return __WEBPACK_IMPORTED_MODULE_107__omit_js__["a"]; });
3662/* harmony import */ var __WEBPACK_IMPORTED_MODULE_108__first_js__ = __webpack_require__(288);
3663/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "first", function() { return __WEBPACK_IMPORTED_MODULE_108__first_js__["a"]; });
3664/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "head", function() { return __WEBPACK_IMPORTED_MODULE_108__first_js__["a"]; });
3665/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "take", function() { return __WEBPACK_IMPORTED_MODULE_108__first_js__["a"]; });
3666/* harmony import */ var __WEBPACK_IMPORTED_MODULE_109__initial_js__ = __webpack_require__(171);
3667/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "initial", function() { return __WEBPACK_IMPORTED_MODULE_109__initial_js__["a"]; });
3668/* harmony import */ var __WEBPACK_IMPORTED_MODULE_110__last_js__ = __webpack_require__(289);
3669/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "last", function() { return __WEBPACK_IMPORTED_MODULE_110__last_js__["a"]; });
3670/* harmony import */ var __WEBPACK_IMPORTED_MODULE_111__rest_js__ = __webpack_require__(172);
3671/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "rest", function() { return __WEBPACK_IMPORTED_MODULE_111__rest_js__["a"]; });
3672/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "tail", function() { return __WEBPACK_IMPORTED_MODULE_111__rest_js__["a"]; });
3673/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "drop", function() { return __WEBPACK_IMPORTED_MODULE_111__rest_js__["a"]; });
3674/* harmony import */ var __WEBPACK_IMPORTED_MODULE_112__compact_js__ = __webpack_require__(290);
3675/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "compact", function() { return __WEBPACK_IMPORTED_MODULE_112__compact_js__["a"]; });
3676/* harmony import */ var __WEBPACK_IMPORTED_MODULE_113__flatten_js__ = __webpack_require__(291);
3677/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "flatten", function() { return __WEBPACK_IMPORTED_MODULE_113__flatten_js__["a"]; });
3678/* harmony import */ var __WEBPACK_IMPORTED_MODULE_114__without_js__ = __webpack_require__(292);
3679/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "without", function() { return __WEBPACK_IMPORTED_MODULE_114__without_js__["a"]; });
3680/* harmony import */ var __WEBPACK_IMPORTED_MODULE_115__uniq_js__ = __webpack_require__(174);
3681/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "uniq", function() { return __WEBPACK_IMPORTED_MODULE_115__uniq_js__["a"]; });
3682/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "unique", function() { return __WEBPACK_IMPORTED_MODULE_115__uniq_js__["a"]; });
3683/* harmony import */ var __WEBPACK_IMPORTED_MODULE_116__union_js__ = __webpack_require__(293);
3684/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "union", function() { return __WEBPACK_IMPORTED_MODULE_116__union_js__["a"]; });
3685/* harmony import */ var __WEBPACK_IMPORTED_MODULE_117__intersection_js__ = __webpack_require__(294);
3686/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "intersection", function() { return __WEBPACK_IMPORTED_MODULE_117__intersection_js__["a"]; });
3687/* harmony import */ var __WEBPACK_IMPORTED_MODULE_118__difference_js__ = __webpack_require__(173);
3688/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "difference", function() { return __WEBPACK_IMPORTED_MODULE_118__difference_js__["a"]; });
3689/* harmony import */ var __WEBPACK_IMPORTED_MODULE_119__unzip_js__ = __webpack_require__(175);
3690/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "unzip", function() { return __WEBPACK_IMPORTED_MODULE_119__unzip_js__["a"]; });
3691/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "transpose", function() { return __WEBPACK_IMPORTED_MODULE_119__unzip_js__["a"]; });
3692/* harmony import */ var __WEBPACK_IMPORTED_MODULE_120__zip_js__ = __webpack_require__(295);
3693/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return __WEBPACK_IMPORTED_MODULE_120__zip_js__["a"]; });
3694/* harmony import */ var __WEBPACK_IMPORTED_MODULE_121__object_js__ = __webpack_require__(296);
3695/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "object", function() { return __WEBPACK_IMPORTED_MODULE_121__object_js__["a"]; });
3696/* harmony import */ var __WEBPACK_IMPORTED_MODULE_122__range_js__ = __webpack_require__(297);
3697/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "range", function() { return __WEBPACK_IMPORTED_MODULE_122__range_js__["a"]; });
3698/* harmony import */ var __WEBPACK_IMPORTED_MODULE_123__chunk_js__ = __webpack_require__(298);
3699/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "chunk", function() { return __WEBPACK_IMPORTED_MODULE_123__chunk_js__["a"]; });
3700/* harmony import */ var __WEBPACK_IMPORTED_MODULE_124__mixin_js__ = __webpack_require__(299);
3701/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "mixin", function() { return __WEBPACK_IMPORTED_MODULE_124__mixin_js__["a"]; });
3702/* harmony import */ var __WEBPACK_IMPORTED_MODULE_125__underscore_array_methods_js__ = __webpack_require__(300);
3703/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return __WEBPACK_IMPORTED_MODULE_125__underscore_array_methods_js__["a"]; });
3704// Named Exports
3705// =============
3706
3707// Underscore.js 1.12.1
3708// https://underscorejs.org
3709// (c) 2009-2020 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
3710// Underscore may be freely distributed under the MIT license.
3711
3712// Baseline setup.
3713
3714
3715
3716// Object Functions
3717// ----------------
3718// Our most fundamental functions operate on any JavaScript object.
3719// Most functions in Underscore depend on at least one function in this section.
3720
3721// A group of functions that check the types of core JavaScript values.
3722// These are often informally referred to as the "isType" functions.
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750// Functions that treat an object as a dictionary of key-value pairs.
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767// Utility Functions
3768// -----------------
3769// A bit of a grab bag: Predicate-generating functions for use with filters and
3770// loops, string escaping and templating, create random numbers and unique ids,
3771// and functions that facilitate Underscore's chaining and iteration conventions.
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791// Function (ahem) Functions
3792// -------------------------
3793// These functions take a function as an argument and return a new function
3794// as the result. Also known as higher-order functions.
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810// Finders
3811// -------
3812// Functions that extract (the position of) a single element from an object
3813// or array based on some criterion.
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823// Collection Functions
3824// --------------------
3825// Functions that work on any collection of elements: either an array, or
3826// an object of key-value pairs.
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851// `_.pick` and `_.omit` are actually object functions, but we put
3852// them here in order to create a more natural reading order in the
3853// monolithic build as they depend on `_.contains`.
3854
3855
3856
3857// Array Functions
3858// ---------------
3859// Functions that operate on arrays (and array-likes) only, because they’re
3860// expressed in terms of operations on an ordered list of values.
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878// OOP
3879// ---
3880// These modules support the "object-oriented" calling style. See also
3881// `underscore.js` and `index-default.js`.
3882
3883
3884
3885
3886/***/ }),
3887/* 93 */
3888/***/ (function(module, __webpack_exports__, __webpack_require__) {
3889
3890"use strict";
3891/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
3892
3893
3894/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('String'));
3895
3896
3897/***/ }),
3898/* 94 */
3899/***/ (function(module, __webpack_exports__, __webpack_require__) {
3900
3901"use strict";
3902/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
3903/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(17);
3904/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isArrayBuffer_js__ = __webpack_require__(133);
3905/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__stringTagBug_js__ = __webpack_require__(52);
3906
3907
3908
3909
3910
3911var isDataView = Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('DataView');
3912
3913// In IE 10 - Edge 13, we need a different heuristic
3914// to determine whether an object is a `DataView`.
3915function ie10IsDataView(obj) {
3916 return obj != null && Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(obj.getInt8) && Object(__WEBPACK_IMPORTED_MODULE_2__isArrayBuffer_js__["a" /* default */])(obj.buffer);
3917}
3918
3919/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_3__stringTagBug_js__["a" /* hasStringTagBug */] ? ie10IsDataView : isDataView);
3920
3921
3922/***/ }),
3923/* 95 */
3924/***/ (function(module, __webpack_exports__, __webpack_require__) {
3925
3926"use strict";
3927/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
3928/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__has_js__ = __webpack_require__(27);
3929
3930
3931
3932var isArguments = Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Arguments');
3933
3934// Define a fallback version of the method in browsers (ahem, IE < 9), where
3935// there isn't any inspectable "Arguments" type.
3936(function() {
3937 if (!isArguments(arguments)) {
3938 isArguments = function(obj) {
3939 return Object(__WEBPACK_IMPORTED_MODULE_1__has_js__["a" /* default */])(obj, 'callee');
3940 };
3941 }
3942}());
3943
3944/* harmony default export */ __webpack_exports__["a"] = (isArguments);
3945
3946
3947/***/ }),
3948/* 96 */
3949/***/ (function(module, __webpack_exports__, __webpack_require__) {
3950
3951"use strict";
3952/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__shallowProperty_js__ = __webpack_require__(138);
3953
3954
3955// Internal helper to obtain the `byteLength` property of an object.
3956/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__shallowProperty_js__["a" /* default */])('byteLength'));
3957
3958
3959/***/ }),
3960/* 97 */
3961/***/ (function(module, __webpack_exports__, __webpack_require__) {
3962
3963"use strict";
3964/* harmony export (immutable) */ __webpack_exports__["a"] = ie11fingerprint;
3965/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return mapMethods; });
3966/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return weakMapMethods; });
3967/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return setMethods; });
3968/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__getLength_js__ = __webpack_require__(18);
3969/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(17);
3970/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__allKeys_js__ = __webpack_require__(53);
3971
3972
3973
3974
3975// Since the regular `Object.prototype.toString` type tests don't work for
3976// some types in IE 11, we use a fingerprinting heuristic instead, based
3977// on the methods. It's not great, but it's the best we got.
3978// The fingerprint method lists are defined below.
3979function ie11fingerprint(methods) {
3980 var length = Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(methods);
3981 return function(obj) {
3982 if (obj == null) return false;
3983 // `Map`, `WeakMap` and `Set` have no enumerable keys.
3984 var keys = Object(__WEBPACK_IMPORTED_MODULE_2__allKeys_js__["a" /* default */])(obj);
3985 if (Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(keys)) return false;
3986 for (var i = 0; i < length; i++) {
3987 if (!Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(obj[methods[i]])) return false;
3988 }
3989 // If we are testing against `WeakMap`, we need to ensure that
3990 // `obj` doesn't have a `forEach` method in order to distinguish
3991 // it from a regular `Map`.
3992 return methods !== weakMapMethods || !Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(obj[forEachName]);
3993 };
3994}
3995
3996// In the interest of compact minification, we write
3997// each string in the fingerprints only once.
3998var forEachName = 'forEach',
3999 hasName = 'has',
4000 commonInit = ['clear', 'delete'],
4001 mapTail = ['get', hasName, 'set'];
4002
4003// `Map`, `WeakMap` and `Set` each have slightly different
4004// combinations of the above sublists.
4005var mapMethods = commonInit.concat(forEachName, mapTail),
4006 weakMapMethods = commonInit.concat(mapTail),
4007 setMethods = ['add'].concat(commonInit, forEachName, hasName);
4008
4009
4010/***/ }),
4011/* 98 */
4012/***/ (function(module, __webpack_exports__, __webpack_require__) {
4013
4014"use strict";
4015/* harmony export (immutable) */ __webpack_exports__["a"] = createAssigner;
4016// An internal function for creating assigner functions.
4017function createAssigner(keysFunc, defaults) {
4018 return function(obj) {
4019 var length = arguments.length;
4020 if (defaults) obj = Object(obj);
4021 if (length < 2 || obj == null) return obj;
4022 for (var index = 1; index < length; index++) {
4023 var source = arguments[index],
4024 keys = keysFunc(source),
4025 l = keys.length;
4026 for (var i = 0; i < l; i++) {
4027 var key = keys[i];
4028 if (!defaults || obj[key] === void 0) obj[key] = source[key];
4029 }
4030 }
4031 return obj;
4032 };
4033}
4034
4035
4036/***/ }),
4037/* 99 */
4038/***/ (function(module, __webpack_exports__, __webpack_require__) {
4039
4040"use strict";
4041/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createAssigner_js__ = __webpack_require__(98);
4042/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__keys_js__ = __webpack_require__(6);
4043
4044
4045
4046// Assigns a given object with all the own properties in the passed-in
4047// object(s).
4048// (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
4049/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createAssigner_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__keys_js__["a" /* default */]));
4050
4051
4052/***/ }),
4053/* 100 */
4054/***/ (function(module, __webpack_exports__, __webpack_require__) {
4055
4056"use strict";
4057/* harmony export (immutable) */ __webpack_exports__["a"] = deepGet;
4058// Internal function to obtain a nested property in `obj` along `path`.
4059function deepGet(obj, path) {
4060 var length = path.length;
4061 for (var i = 0; i < length; i++) {
4062 if (obj == null) return void 0;
4063 obj = obj[path[i]];
4064 }
4065 return length ? obj : void 0;
4066}
4067
4068
4069/***/ }),
4070/* 101 */
4071/***/ (function(module, __webpack_exports__, __webpack_require__) {
4072
4073"use strict";
4074/* harmony export (immutable) */ __webpack_exports__["a"] = identity;
4075// Keep the identity function around for default iteratees.
4076function identity(value) {
4077 return value;
4078}
4079
4080
4081/***/ }),
4082/* 102 */
4083/***/ (function(module, __webpack_exports__, __webpack_require__) {
4084
4085"use strict";
4086/* harmony export (immutable) */ __webpack_exports__["a"] = property;
4087/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__deepGet_js__ = __webpack_require__(100);
4088/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__toPath_js__ = __webpack_require__(54);
4089
4090
4091
4092// Creates a function that, when passed an object, will traverse that object’s
4093// properties down the given `path`, specified as an array of keys or indices.
4094function property(path) {
4095 path = Object(__WEBPACK_IMPORTED_MODULE_1__toPath_js__["a" /* default */])(path);
4096 return function(obj) {
4097 return Object(__WEBPACK_IMPORTED_MODULE_0__deepGet_js__["a" /* default */])(obj, path);
4098 };
4099}
4100
4101
4102/***/ }),
4103/* 103 */
4104/***/ (function(module, __webpack_exports__, __webpack_require__) {
4105
4106"use strict";
4107// A (possibly faster) way to get the current timestamp as an integer.
4108/* harmony default export */ __webpack_exports__["a"] = (Date.now || function() {
4109 return new Date().getTime();
4110});
4111
4112
4113/***/ }),
4114/* 104 */
4115/***/ (function(module, __webpack_exports__, __webpack_require__) {
4116
4117"use strict";
4118/* harmony export (immutable) */ __webpack_exports__["a"] = negate;
4119// Returns a negated version of the passed-in predicate.
4120function negate(predicate) {
4121 return function() {
4122 return !predicate.apply(this, arguments);
4123 };
4124}
4125
4126
4127/***/ }),
4128/* 105 */
4129/***/ (function(module, __webpack_exports__, __webpack_require__) {
4130
4131"use strict";
4132/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createPredicateIndexFinder_js__ = __webpack_require__(161);
4133
4134
4135// Returns the first index on an array-like that passes a truth test.
4136/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createPredicateIndexFinder_js__["a" /* default */])(1));
4137
4138
4139/***/ }),
4140/* 106 */
4141/***/ (function(module, __webpack_exports__, __webpack_require__) {
4142
4143"use strict";
4144/* harmony export (immutable) */ __webpack_exports__["a"] = pluck;
4145/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__map_js__ = __webpack_require__(41);
4146/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__property_js__ = __webpack_require__(102);
4147
4148
4149
4150// Convenience version of a common use case of `_.map`: fetching a property.
4151function pluck(obj, key) {
4152 return Object(__WEBPACK_IMPORTED_MODULE_0__map_js__["a" /* default */])(obj, Object(__WEBPACK_IMPORTED_MODULE_1__property_js__["a" /* default */])(key));
4153}
4154
4155
4156/***/ }),
4157/* 107 */
4158/***/ (function(module, exports, __webpack_require__) {
4159
4160module.exports = { "default": __webpack_require__(302), __esModule: true };
4161
4162/***/ }),
4163/* 108 */
4164/***/ (function(module, exports, __webpack_require__) {
4165
4166exports.f = __webpack_require__(8);
4167
4168
4169/***/ }),
4170/* 109 */
4171/***/ (function(module, exports, __webpack_require__) {
4172
4173var global = __webpack_require__(5);
4174var core = __webpack_require__(1);
4175var LIBRARY = __webpack_require__(46);
4176var wksExt = __webpack_require__(108);
4177var defineProperty = __webpack_require__(20).f;
4178module.exports = function (name) {
4179 var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
4180 if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });
4181};
4182
4183
4184/***/ }),
4185/* 110 */
4186/***/ (function(module, exports, __webpack_require__) {
4187
4188// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
4189var $keys = __webpack_require__(117);
4190var hiddenKeys = __webpack_require__(89).concat('length', 'prototype');
4191
4192exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
4193 return $keys(O, hiddenKeys);
4194};
4195
4196
4197/***/ }),
4198/* 111 */
4199/***/ (function(module, exports, __webpack_require__) {
4200
4201module.exports = { "default": __webpack_require__(334), __esModule: true };
4202
4203/***/ }),
4204/* 112 */
4205/***/ (function(module, exports, __webpack_require__) {
4206
4207module.exports = { "default": __webpack_require__(350), __esModule: true };
4208
4209/***/ }),
4210/* 113 */
4211/***/ (function(module, exports, __webpack_require__) {
4212
4213"use strict";
4214
4215
4216module.exports = __webpack_require__(379);
4217
4218/***/ }),
4219/* 114 */
4220/***/ (function(module, exports, __webpack_require__) {
4221
4222// 0 -> Array#forEach
4223// 1 -> Array#map
4224// 2 -> Array#filter
4225// 3 -> Array#some
4226// 4 -> Array#every
4227// 5 -> Array#find
4228// 6 -> Array#findIndex
4229var ctx = __webpack_require__(22);
4230var IObject = __webpack_require__(86);
4231var toObject = __webpack_require__(29);
4232var toLength = __webpack_require__(61);
4233var asc = __webpack_require__(383);
4234module.exports = function (TYPE, $create) {
4235 var IS_MAP = TYPE == 1;
4236 var IS_FILTER = TYPE == 2;
4237 var IS_SOME = TYPE == 3;
4238 var IS_EVERY = TYPE == 4;
4239 var IS_FIND_INDEX = TYPE == 6;
4240 var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
4241 var create = $create || asc;
4242 return function ($this, callbackfn, that) {
4243 var O = toObject($this);
4244 var self = IObject(O);
4245 var f = ctx(callbackfn, that, 3);
4246 var length = toLength(self.length);
4247 var index = 0;
4248 var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
4249 var val, res;
4250 for (;length > index; index++) if (NO_HOLES || index in self) {
4251 val = self[index];
4252 res = f(val, index, O);
4253 if (TYPE) {
4254 if (IS_MAP) result[index] = res; // map
4255 else if (res) switch (TYPE) {
4256 case 3: return true; // some
4257 case 5: return val; // find
4258 case 6: return index; // findIndex
4259 case 2: result.push(val); // filter
4260 } else if (IS_EVERY) return false; // every
4261 }
4262 }
4263 return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
4264 };
4265};
4266
4267
4268/***/ }),
4269/* 115 */
4270/***/ (function(module, exports, __webpack_require__) {
4271
4272module.exports = !__webpack_require__(16) && !__webpack_require__(28)(function () {
4273 return Object.defineProperty(__webpack_require__(83)('div'), 'a', { get: function () { return 7; } }).a != 7;
4274});
4275
4276
4277/***/ }),
4278/* 116 */
4279/***/ (function(module, exports, __webpack_require__) {
4280
4281var dP = __webpack_require__(20);
4282var anObject = __webpack_require__(15);
4283var getKeys = __webpack_require__(49);
4284
4285module.exports = __webpack_require__(16) ? Object.defineProperties : function defineProperties(O, Properties) {
4286 anObject(O);
4287 var keys = getKeys(Properties);
4288 var length = keys.length;
4289 var i = 0;
4290 var P;
4291 while (length > i) dP.f(O, P = keys[i++], Properties[P]);
4292 return O;
4293};
4294
4295
4296/***/ }),
4297/* 117 */
4298/***/ (function(module, exports, __webpack_require__) {
4299
4300var has = __webpack_require__(25);
4301var toIObject = __webpack_require__(26);
4302var arrayIndexOf = __webpack_require__(219)(false);
4303var IE_PROTO = __webpack_require__(87)('IE_PROTO');
4304
4305module.exports = function (object, names) {
4306 var O = toIObject(object);
4307 var i = 0;
4308 var result = [];
4309 var key;
4310 for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
4311 // Don't enum bug & hidden keys
4312 while (names.length > i) if (has(O, key = names[i++])) {
4313 ~arrayIndexOf(result, key) || result.push(key);
4314 }
4315 return result;
4316};
4317
4318
4319/***/ }),
4320/* 118 */
4321/***/ (function(module, exports, __webpack_require__) {
4322
4323var document = __webpack_require__(5).document;
4324module.exports = document && document.documentElement;
4325
4326
4327/***/ }),
4328/* 119 */
4329/***/ (function(module, exports, __webpack_require__) {
4330
4331// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
4332var has = __webpack_require__(25);
4333var toObject = __webpack_require__(29);
4334var IE_PROTO = __webpack_require__(87)('IE_PROTO');
4335var ObjectProto = Object.prototype;
4336
4337module.exports = Object.getPrototypeOf || function (O) {
4338 O = toObject(O);
4339 if (has(O, IE_PROTO)) return O[IE_PROTO];
4340 if (typeof O.constructor == 'function' && O instanceof O.constructor) {
4341 return O.constructor.prototype;
4342 } return O instanceof Object ? ObjectProto : null;
4343};
4344
4345
4346/***/ }),
4347/* 120 */
4348/***/ (function(module, exports) {
4349
4350module.exports = function (done, value) {
4351 return { value: value, done: !!done };
4352};
4353
4354
4355/***/ }),
4356/* 121 */
4357/***/ (function(module, exports, __webpack_require__) {
4358
4359// call something on iterator step with safe closing on error
4360var anObject = __webpack_require__(15);
4361module.exports = function (iterator, fn, value, entries) {
4362 try {
4363 return entries ? fn(anObject(value)[0], value[1]) : fn(value);
4364 // 7.4.6 IteratorClose(iterator, completion)
4365 } catch (e) {
4366 var ret = iterator['return'];
4367 if (ret !== undefined) anObject(ret.call(iterator));
4368 throw e;
4369 }
4370};
4371
4372
4373/***/ }),
4374/* 122 */
4375/***/ (function(module, exports, __webpack_require__) {
4376
4377// check on default Array iterator
4378var Iterators = __webpack_require__(36);
4379var ITERATOR = __webpack_require__(8)('iterator');
4380var ArrayProto = Array.prototype;
4381
4382module.exports = function (it) {
4383 return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
4384};
4385
4386
4387/***/ }),
4388/* 123 */
4389/***/ (function(module, exports, __webpack_require__) {
4390
4391// 7.3.20 SpeciesConstructor(O, defaultConstructor)
4392var anObject = __webpack_require__(15);
4393var aFunction = __webpack_require__(47);
4394var SPECIES = __webpack_require__(8)('species');
4395module.exports = function (O, D) {
4396 var C = anObject(O).constructor;
4397 var S;
4398 return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
4399};
4400
4401
4402/***/ }),
4403/* 124 */
4404/***/ (function(module, exports, __webpack_require__) {
4405
4406var ctx = __webpack_require__(22);
4407var invoke = __webpack_require__(224);
4408var html = __webpack_require__(118);
4409var cel = __webpack_require__(83);
4410var global = __webpack_require__(5);
4411var process = global.process;
4412var setTask = global.setImmediate;
4413var clearTask = global.clearImmediate;
4414var MessageChannel = global.MessageChannel;
4415var Dispatch = global.Dispatch;
4416var counter = 0;
4417var queue = {};
4418var ONREADYSTATECHANGE = 'onreadystatechange';
4419var defer, channel, port;
4420var run = function () {
4421 var id = +this;
4422 // eslint-disable-next-line no-prototype-builtins
4423 if (queue.hasOwnProperty(id)) {
4424 var fn = queue[id];
4425 delete queue[id];
4426 fn();
4427 }
4428};
4429var listener = function (event) {
4430 run.call(event.data);
4431};
4432// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
4433if (!setTask || !clearTask) {
4434 setTask = function setImmediate(fn) {
4435 var args = [];
4436 var i = 1;
4437 while (arguments.length > i) args.push(arguments[i++]);
4438 queue[++counter] = function () {
4439 // eslint-disable-next-line no-new-func
4440 invoke(typeof fn == 'function' ? fn : Function(fn), args);
4441 };
4442 defer(counter);
4443 return counter;
4444 };
4445 clearTask = function clearImmediate(id) {
4446 delete queue[id];
4447 };
4448 // Node.js 0.8-
4449 if (__webpack_require__(50)(process) == 'process') {
4450 defer = function (id) {
4451 process.nextTick(ctx(run, id, 1));
4452 };
4453 // Sphere (JS game engine) Dispatch API
4454 } else if (Dispatch && Dispatch.now) {
4455 defer = function (id) {
4456 Dispatch.now(ctx(run, id, 1));
4457 };
4458 // Browsers with MessageChannel, includes WebWorkers
4459 } else if (MessageChannel) {
4460 channel = new MessageChannel();
4461 port = channel.port2;
4462 channel.port1.onmessage = listener;
4463 defer = ctx(port.postMessage, port, 1);
4464 // Browsers with postMessage, skip WebWorkers
4465 // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
4466 } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {
4467 defer = function (id) {
4468 global.postMessage(id + '', '*');
4469 };
4470 global.addEventListener('message', listener, false);
4471 // IE8-
4472 } else if (ONREADYSTATECHANGE in cel('script')) {
4473 defer = function (id) {
4474 html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {
4475 html.removeChild(this);
4476 run.call(id);
4477 };
4478 };
4479 // Rest old browsers
4480 } else {
4481 defer = function (id) {
4482 setTimeout(ctx(run, id, 1), 0);
4483 };
4484 }
4485}
4486module.exports = {
4487 set: setTask,
4488 clear: clearTask
4489};
4490
4491
4492/***/ }),
4493/* 125 */
4494/***/ (function(module, exports) {
4495
4496module.exports = function (exec) {
4497 try {
4498 return { e: false, v: exec() };
4499 } catch (e) {
4500 return { e: true, v: e };
4501 }
4502};
4503
4504
4505/***/ }),
4506/* 126 */
4507/***/ (function(module, exports, __webpack_require__) {
4508
4509var anObject = __webpack_require__(15);
4510var isObject = __webpack_require__(9);
4511var newPromiseCapability = __webpack_require__(91);
4512
4513module.exports = function (C, x) {
4514 anObject(C);
4515 if (isObject(x) && x.constructor === C) return x;
4516 var promiseCapability = newPromiseCapability.f(C);
4517 var resolve = promiseCapability.resolve;
4518 resolve(x);
4519 return promiseCapability.promise;
4520};
4521
4522
4523/***/ }),
4524/* 127 */
4525/***/ (function(module, exports, __webpack_require__) {
4526
4527"use strict";
4528
4529var global = __webpack_require__(5);
4530var core = __webpack_require__(1);
4531var dP = __webpack_require__(20);
4532var DESCRIPTORS = __webpack_require__(16);
4533var SPECIES = __webpack_require__(8)('species');
4534
4535module.exports = function (KEY) {
4536 var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY];
4537 if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {
4538 configurable: true,
4539 get: function () { return this; }
4540 });
4541};
4542
4543
4544/***/ }),
4545/* 128 */
4546/***/ (function(module, exports, __webpack_require__) {
4547
4548var ITERATOR = __webpack_require__(8)('iterator');
4549var SAFE_CLOSING = false;
4550
4551try {
4552 var riter = [7][ITERATOR]();
4553 riter['return'] = function () { SAFE_CLOSING = true; };
4554 // eslint-disable-next-line no-throw-literal
4555 Array.from(riter, function () { throw 2; });
4556} catch (e) { /* empty */ }
4557
4558module.exports = function (exec, skipClosing) {
4559 if (!skipClosing && !SAFE_CLOSING) return false;
4560 var safe = false;
4561 try {
4562 var arr = [7];
4563 var iter = arr[ITERATOR]();
4564 iter.next = function () { return { done: safe = true }; };
4565 arr[ITERATOR] = function () { return iter; };
4566 exec(arr);
4567 } catch (e) { /* empty */ }
4568 return safe;
4569};
4570
4571
4572/***/ }),
4573/* 129 */
4574/***/ (function(module, __webpack_exports__, __webpack_require__) {
4575
4576"use strict";
4577/* harmony export (immutable) */ __webpack_exports__["a"] = isUndefined;
4578// Is a given variable undefined?
4579function isUndefined(obj) {
4580 return obj === void 0;
4581}
4582
4583
4584/***/ }),
4585/* 130 */
4586/***/ (function(module, __webpack_exports__, __webpack_require__) {
4587
4588"use strict";
4589/* harmony export (immutable) */ __webpack_exports__["a"] = isBoolean;
4590/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
4591
4592
4593// Is a given value a boolean?
4594function isBoolean(obj) {
4595 return obj === true || obj === false || __WEBPACK_IMPORTED_MODULE_0__setup_js__["t" /* toString */].call(obj) === '[object Boolean]';
4596}
4597
4598
4599/***/ }),
4600/* 131 */
4601/***/ (function(module, __webpack_exports__, __webpack_require__) {
4602
4603"use strict";
4604/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
4605
4606
4607/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Number'));
4608
4609
4610/***/ }),
4611/* 132 */
4612/***/ (function(module, __webpack_exports__, __webpack_require__) {
4613
4614"use strict";
4615/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
4616
4617
4618/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Symbol'));
4619
4620
4621/***/ }),
4622/* 133 */
4623/***/ (function(module, __webpack_exports__, __webpack_require__) {
4624
4625"use strict";
4626/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
4627
4628
4629/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('ArrayBuffer'));
4630
4631
4632/***/ }),
4633/* 134 */
4634/***/ (function(module, __webpack_exports__, __webpack_require__) {
4635
4636"use strict";
4637/* harmony export (immutable) */ __webpack_exports__["a"] = isNaN;
4638/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
4639/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isNumber_js__ = __webpack_require__(131);
4640
4641
4642
4643// Is the given value `NaN`?
4644function isNaN(obj) {
4645 return Object(__WEBPACK_IMPORTED_MODULE_1__isNumber_js__["a" /* default */])(obj) && Object(__WEBPACK_IMPORTED_MODULE_0__setup_js__["g" /* _isNaN */])(obj);
4646}
4647
4648
4649/***/ }),
4650/* 135 */
4651/***/ (function(module, __webpack_exports__, __webpack_require__) {
4652
4653"use strict";
4654/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
4655/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isDataView_js__ = __webpack_require__(94);
4656/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__constant_js__ = __webpack_require__(136);
4657/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isBufferLike_js__ = __webpack_require__(237);
4658
4659
4660
4661
4662
4663// Is a given value a typed array?
4664var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;
4665function isTypedArray(obj) {
4666 // `ArrayBuffer.isView` is the most future-proof, so use it when available.
4667 // Otherwise, fall back on the above regular expression.
4668 return __WEBPACK_IMPORTED_MODULE_0__setup_js__["l" /* nativeIsView */] ? (Object(__WEBPACK_IMPORTED_MODULE_0__setup_js__["l" /* nativeIsView */])(obj) && !Object(__WEBPACK_IMPORTED_MODULE_1__isDataView_js__["a" /* default */])(obj)) :
4669 Object(__WEBPACK_IMPORTED_MODULE_3__isBufferLike_js__["a" /* default */])(obj) && typedArrayPattern.test(__WEBPACK_IMPORTED_MODULE_0__setup_js__["t" /* toString */].call(obj));
4670}
4671
4672/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_0__setup_js__["r" /* supportsArrayBuffer */] ? isTypedArray : Object(__WEBPACK_IMPORTED_MODULE_2__constant_js__["a" /* default */])(false));
4673
4674
4675/***/ }),
4676/* 136 */
4677/***/ (function(module, __webpack_exports__, __webpack_require__) {
4678
4679"use strict";
4680/* harmony export (immutable) */ __webpack_exports__["a"] = constant;
4681// Predicate-generating function. Often useful outside of Underscore.
4682function constant(value) {
4683 return function() {
4684 return value;
4685 };
4686}
4687
4688
4689/***/ }),
4690/* 137 */
4691/***/ (function(module, __webpack_exports__, __webpack_require__) {
4692
4693"use strict";
4694/* harmony export (immutable) */ __webpack_exports__["a"] = createSizePropertyCheck;
4695/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
4696
4697
4698// Common internal logic for `isArrayLike` and `isBufferLike`.
4699function createSizePropertyCheck(getSizeProperty) {
4700 return function(collection) {
4701 var sizeProperty = getSizeProperty(collection);
4702 return typeof sizeProperty == 'number' && sizeProperty >= 0 && sizeProperty <= __WEBPACK_IMPORTED_MODULE_0__setup_js__["b" /* MAX_ARRAY_INDEX */];
4703 }
4704}
4705
4706
4707/***/ }),
4708/* 138 */
4709/***/ (function(module, __webpack_exports__, __webpack_require__) {
4710
4711"use strict";
4712/* harmony export (immutable) */ __webpack_exports__["a"] = shallowProperty;
4713// Internal helper to generate a function to obtain property `key` from `obj`.
4714function shallowProperty(key) {
4715 return function(obj) {
4716 return obj == null ? void 0 : obj[key];
4717 };
4718}
4719
4720
4721/***/ }),
4722/* 139 */
4723/***/ (function(module, __webpack_exports__, __webpack_require__) {
4724
4725"use strict";
4726/* harmony export (immutable) */ __webpack_exports__["a"] = collectNonEnumProps;
4727/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
4728/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(17);
4729/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__has_js__ = __webpack_require__(27);
4730
4731
4732
4733
4734// Internal helper to create a simple lookup structure.
4735// `collectNonEnumProps` used to depend on `_.contains`, but this led to
4736// circular imports. `emulatedSet` is a one-off solution that only works for
4737// arrays of strings.
4738function emulatedSet(keys) {
4739 var hash = {};
4740 for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true;
4741 return {
4742 contains: function(key) { return hash[key]; },
4743 push: function(key) {
4744 hash[key] = true;
4745 return keys.push(key);
4746 }
4747 };
4748}
4749
4750// Internal helper. Checks `keys` for the presence of keys in IE < 9 that won't
4751// be iterated by `for key in ...` and thus missed. Extends `keys` in place if
4752// needed.
4753function collectNonEnumProps(obj, keys) {
4754 keys = emulatedSet(keys);
4755 var nonEnumIdx = __WEBPACK_IMPORTED_MODULE_0__setup_js__["n" /* nonEnumerableProps */].length;
4756 var constructor = obj.constructor;
4757 var proto = Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(constructor) && constructor.prototype || __WEBPACK_IMPORTED_MODULE_0__setup_js__["c" /* ObjProto */];
4758
4759 // Constructor is a special case.
4760 var prop = 'constructor';
4761 if (Object(__WEBPACK_IMPORTED_MODULE_2__has_js__["a" /* default */])(obj, prop) && !keys.contains(prop)) keys.push(prop);
4762
4763 while (nonEnumIdx--) {
4764 prop = __WEBPACK_IMPORTED_MODULE_0__setup_js__["n" /* nonEnumerableProps */][nonEnumIdx];
4765 if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) {
4766 keys.push(prop);
4767 }
4768 }
4769}
4770
4771
4772/***/ }),
4773/* 140 */
4774/***/ (function(module, __webpack_exports__, __webpack_require__) {
4775
4776"use strict";
4777/* harmony export (immutable) */ __webpack_exports__["a"] = isMatch;
4778/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__keys_js__ = __webpack_require__(6);
4779
4780
4781// Returns whether an object has a given set of `key:value` pairs.
4782function isMatch(object, attrs) {
4783 var _keys = Object(__WEBPACK_IMPORTED_MODULE_0__keys_js__["a" /* default */])(attrs), length = _keys.length;
4784 if (object == null) return !length;
4785 var obj = Object(object);
4786 for (var i = 0; i < length; i++) {
4787 var key = _keys[i];
4788 if (attrs[key] !== obj[key] || !(key in obj)) return false;
4789 }
4790 return true;
4791}
4792
4793
4794/***/ }),
4795/* 141 */
4796/***/ (function(module, __webpack_exports__, __webpack_require__) {
4797
4798"use strict";
4799/* harmony export (immutable) */ __webpack_exports__["a"] = invert;
4800/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__keys_js__ = __webpack_require__(6);
4801
4802
4803// Invert the keys and values of an object. The values must be serializable.
4804function invert(obj) {
4805 var result = {};
4806 var _keys = Object(__WEBPACK_IMPORTED_MODULE_0__keys_js__["a" /* default */])(obj);
4807 for (var i = 0, length = _keys.length; i < length; i++) {
4808 result[obj[_keys[i]]] = _keys[i];
4809 }
4810 return result;
4811}
4812
4813
4814/***/ }),
4815/* 142 */
4816/***/ (function(module, __webpack_exports__, __webpack_require__) {
4817
4818"use strict";
4819/* harmony export (immutable) */ __webpack_exports__["a"] = functions;
4820/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isFunction_js__ = __webpack_require__(17);
4821
4822
4823// Return a sorted list of the function names available on the object.
4824function functions(obj) {
4825 var names = [];
4826 for (var key in obj) {
4827 if (Object(__WEBPACK_IMPORTED_MODULE_0__isFunction_js__["a" /* default */])(obj[key])) names.push(key);
4828 }
4829 return names.sort();
4830}
4831
4832
4833/***/ }),
4834/* 143 */
4835/***/ (function(module, __webpack_exports__, __webpack_require__) {
4836
4837"use strict";
4838/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createAssigner_js__ = __webpack_require__(98);
4839/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__allKeys_js__ = __webpack_require__(53);
4840
4841
4842
4843// Extend a given object with all the properties in passed-in object(s).
4844/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createAssigner_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__allKeys_js__["a" /* default */]));
4845
4846
4847/***/ }),
4848/* 144 */
4849/***/ (function(module, __webpack_exports__, __webpack_require__) {
4850
4851"use strict";
4852/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createAssigner_js__ = __webpack_require__(98);
4853/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__allKeys_js__ = __webpack_require__(53);
4854
4855
4856
4857// Fill in a given object with default properties.
4858/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createAssigner_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__allKeys_js__["a" /* default */], true));
4859
4860
4861/***/ }),
4862/* 145 */
4863/***/ (function(module, __webpack_exports__, __webpack_require__) {
4864
4865"use strict";
4866/* harmony export (immutable) */ __webpack_exports__["a"] = baseCreate;
4867/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isObject_js__ = __webpack_require__(30);
4868/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__setup_js__ = __webpack_require__(2);
4869
4870
4871
4872// Create a naked function reference for surrogate-prototype-swapping.
4873function ctor() {
4874 return function(){};
4875}
4876
4877// An internal function for creating a new object that inherits from another.
4878function baseCreate(prototype) {
4879 if (!Object(__WEBPACK_IMPORTED_MODULE_0__isObject_js__["a" /* default */])(prototype)) return {};
4880 if (__WEBPACK_IMPORTED_MODULE_1__setup_js__["j" /* nativeCreate */]) return Object(__WEBPACK_IMPORTED_MODULE_1__setup_js__["j" /* nativeCreate */])(prototype);
4881 var Ctor = ctor();
4882 Ctor.prototype = prototype;
4883 var result = new Ctor;
4884 Ctor.prototype = null;
4885 return result;
4886}
4887
4888
4889/***/ }),
4890/* 146 */
4891/***/ (function(module, __webpack_exports__, __webpack_require__) {
4892
4893"use strict";
4894/* harmony export (immutable) */ __webpack_exports__["a"] = clone;
4895/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isObject_js__ = __webpack_require__(30);
4896/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArray_js__ = __webpack_require__(31);
4897/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__extend_js__ = __webpack_require__(143);
4898
4899
4900
4901
4902// Create a (shallow-cloned) duplicate of an object.
4903function clone(obj) {
4904 if (!Object(__WEBPACK_IMPORTED_MODULE_0__isObject_js__["a" /* default */])(obj)) return obj;
4905 return Object(__WEBPACK_IMPORTED_MODULE_1__isArray_js__["a" /* default */])(obj) ? obj.slice() : Object(__WEBPACK_IMPORTED_MODULE_2__extend_js__["a" /* default */])({}, obj);
4906}
4907
4908
4909/***/ }),
4910/* 147 */
4911/***/ (function(module, __webpack_exports__, __webpack_require__) {
4912
4913"use strict";
4914/* harmony export (immutable) */ __webpack_exports__["a"] = get;
4915/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__toPath_js__ = __webpack_require__(54);
4916/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__deepGet_js__ = __webpack_require__(100);
4917/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isUndefined_js__ = __webpack_require__(129);
4918
4919
4920
4921
4922// Get the value of the (deep) property on `path` from `object`.
4923// If any property in `path` does not exist or if the value is
4924// `undefined`, return `defaultValue` instead.
4925// The `path` is normalized through `_.toPath`.
4926function get(object, path, defaultValue) {
4927 var value = Object(__WEBPACK_IMPORTED_MODULE_1__deepGet_js__["a" /* default */])(object, Object(__WEBPACK_IMPORTED_MODULE_0__toPath_js__["a" /* default */])(path));
4928 return Object(__WEBPACK_IMPORTED_MODULE_2__isUndefined_js__["a" /* default */])(value) ? defaultValue : value;
4929}
4930
4931
4932/***/ }),
4933/* 148 */
4934/***/ (function(module, __webpack_exports__, __webpack_require__) {
4935
4936"use strict";
4937/* harmony export (immutable) */ __webpack_exports__["a"] = toPath;
4938/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(12);
4939/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArray_js__ = __webpack_require__(31);
4940
4941
4942
4943// Normalize a (deep) property `path` to array.
4944// Like `_.iteratee`, this function can be customized.
4945function toPath(path) {
4946 return Object(__WEBPACK_IMPORTED_MODULE_1__isArray_js__["a" /* default */])(path) ? path : [path];
4947}
4948__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].toPath = toPath;
4949
4950
4951/***/ }),
4952/* 149 */
4953/***/ (function(module, __webpack_exports__, __webpack_require__) {
4954
4955"use strict";
4956/* harmony export (immutable) */ __webpack_exports__["a"] = baseIteratee;
4957/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__identity_js__ = __webpack_require__(101);
4958/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(17);
4959/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isObject_js__ = __webpack_require__(30);
4960/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isArray_js__ = __webpack_require__(31);
4961/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__matcher_js__ = __webpack_require__(67);
4962/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__property_js__ = __webpack_require__(102);
4963/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__optimizeCb_js__ = __webpack_require__(55);
4964
4965
4966
4967
4968
4969
4970
4971
4972// An internal function to generate callbacks that can be applied to each
4973// element in a collection, returning the desired result — either `_.identity`,
4974// an arbitrary callback, a property matcher, or a property accessor.
4975function baseIteratee(value, context, argCount) {
4976 if (value == null) return __WEBPACK_IMPORTED_MODULE_0__identity_js__["a" /* default */];
4977 if (Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(value)) return Object(__WEBPACK_IMPORTED_MODULE_6__optimizeCb_js__["a" /* default */])(value, context, argCount);
4978 if (Object(__WEBPACK_IMPORTED_MODULE_2__isObject_js__["a" /* default */])(value) && !Object(__WEBPACK_IMPORTED_MODULE_3__isArray_js__["a" /* default */])(value)) return Object(__WEBPACK_IMPORTED_MODULE_4__matcher_js__["a" /* default */])(value);
4979 return Object(__WEBPACK_IMPORTED_MODULE_5__property_js__["a" /* default */])(value);
4980}
4981
4982
4983/***/ }),
4984/* 150 */
4985/***/ (function(module, __webpack_exports__, __webpack_require__) {
4986
4987"use strict";
4988/* harmony export (immutable) */ __webpack_exports__["a"] = iteratee;
4989/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(12);
4990/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__baseIteratee_js__ = __webpack_require__(149);
4991
4992
4993
4994// External wrapper for our callback generator. Users may customize
4995// `_.iteratee` if they want additional predicate/iteratee shorthand styles.
4996// This abstraction hides the internal-only `argCount` argument.
4997function iteratee(value, context) {
4998 return Object(__WEBPACK_IMPORTED_MODULE_1__baseIteratee_js__["a" /* default */])(value, context, Infinity);
4999}
5000__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].iteratee = iteratee;
5001
5002
5003/***/ }),
5004/* 151 */
5005/***/ (function(module, __webpack_exports__, __webpack_require__) {
5006
5007"use strict";
5008/* harmony export (immutable) */ __webpack_exports__["a"] = noop;
5009// Predicate-generating function. Often useful outside of Underscore.
5010function noop(){}
5011
5012
5013/***/ }),
5014/* 152 */
5015/***/ (function(module, __webpack_exports__, __webpack_require__) {
5016
5017"use strict";
5018/* harmony export (immutable) */ __webpack_exports__["a"] = random;
5019// Return a random integer between `min` and `max` (inclusive).
5020function random(min, max) {
5021 if (max == null) {
5022 max = min;
5023 min = 0;
5024 }
5025 return min + Math.floor(Math.random() * (max - min + 1));
5026}
5027
5028
5029/***/ }),
5030/* 153 */
5031/***/ (function(module, __webpack_exports__, __webpack_require__) {
5032
5033"use strict";
5034/* harmony export (immutable) */ __webpack_exports__["a"] = createEscaper;
5035/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__keys_js__ = __webpack_require__(6);
5036
5037
5038// Internal helper to generate functions for escaping and unescaping strings
5039// to/from HTML interpolation.
5040function createEscaper(map) {
5041 var escaper = function(match) {
5042 return map[match];
5043 };
5044 // Regexes for identifying a key that needs to be escaped.
5045 var source = '(?:' + Object(__WEBPACK_IMPORTED_MODULE_0__keys_js__["a" /* default */])(map).join('|') + ')';
5046 var testRegexp = RegExp(source);
5047 var replaceRegexp = RegExp(source, 'g');
5048 return function(string) {
5049 string = string == null ? '' : '' + string;
5050 return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
5051 };
5052}
5053
5054
5055/***/ }),
5056/* 154 */
5057/***/ (function(module, __webpack_exports__, __webpack_require__) {
5058
5059"use strict";
5060// Internal list of HTML entities for escaping.
5061/* harmony default export */ __webpack_exports__["a"] = ({
5062 '&': '&amp;',
5063 '<': '&lt;',
5064 '>': '&gt;',
5065 '"': '&quot;',
5066 "'": '&#x27;',
5067 '`': '&#x60;'
5068});
5069
5070
5071/***/ }),
5072/* 155 */
5073/***/ (function(module, __webpack_exports__, __webpack_require__) {
5074
5075"use strict";
5076/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(12);
5077
5078
5079// By default, Underscore uses ERB-style template delimiters. Change the
5080// following template settings to use alternative delimiters.
5081/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].templateSettings = {
5082 evaluate: /<%([\s\S]+?)%>/g,
5083 interpolate: /<%=([\s\S]+?)%>/g,
5084 escape: /<%-([\s\S]+?)%>/g
5085});
5086
5087
5088/***/ }),
5089/* 156 */
5090/***/ (function(module, __webpack_exports__, __webpack_require__) {
5091
5092"use strict";
5093/* harmony export (immutable) */ __webpack_exports__["a"] = executeBound;
5094/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__baseCreate_js__ = __webpack_require__(145);
5095/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isObject_js__ = __webpack_require__(30);
5096
5097
5098
5099// Internal function to execute `sourceFunc` bound to `context` with optional
5100// `args`. Determines whether to execute a function as a constructor or as a
5101// normal function.
5102function executeBound(sourceFunc, boundFunc, context, callingContext, args) {
5103 if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
5104 var self = Object(__WEBPACK_IMPORTED_MODULE_0__baseCreate_js__["a" /* default */])(sourceFunc.prototype);
5105 var result = sourceFunc.apply(self, args);
5106 if (Object(__WEBPACK_IMPORTED_MODULE_1__isObject_js__["a" /* default */])(result)) return result;
5107 return self;
5108}
5109
5110
5111/***/ }),
5112/* 157 */
5113/***/ (function(module, __webpack_exports__, __webpack_require__) {
5114
5115"use strict";
5116/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(11);
5117/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(17);
5118/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__executeBound_js__ = __webpack_require__(156);
5119
5120
5121
5122
5123// Create a function bound to a given object (assigning `this`, and arguments,
5124// optionally).
5125/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(func, context, args) {
5126 if (!Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(func)) throw new TypeError('Bind must be called on a function');
5127 var bound = Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(callArgs) {
5128 return Object(__WEBPACK_IMPORTED_MODULE_2__executeBound_js__["a" /* default */])(func, bound, context, this, args.concat(callArgs));
5129 });
5130 return bound;
5131}));
5132
5133
5134/***/ }),
5135/* 158 */
5136/***/ (function(module, __webpack_exports__, __webpack_require__) {
5137
5138"use strict";
5139/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(11);
5140
5141
5142// Delays a function for the given number of milliseconds, and then calls
5143// it with the arguments supplied.
5144/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(func, wait, args) {
5145 return setTimeout(function() {
5146 return func.apply(null, args);
5147 }, wait);
5148}));
5149
5150
5151/***/ }),
5152/* 159 */
5153/***/ (function(module, __webpack_exports__, __webpack_require__) {
5154
5155"use strict";
5156/* harmony export (immutable) */ __webpack_exports__["a"] = before;
5157// Returns a function that will only be executed up to (but not including) the
5158// Nth call.
5159function before(times, func) {
5160 var memo;
5161 return function() {
5162 if (--times > 0) {
5163 memo = func.apply(this, arguments);
5164 }
5165 if (times <= 1) func = null;
5166 return memo;
5167 };
5168}
5169
5170
5171/***/ }),
5172/* 160 */
5173/***/ (function(module, __webpack_exports__, __webpack_require__) {
5174
5175"use strict";
5176/* harmony export (immutable) */ __webpack_exports__["a"] = findKey;
5177/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(10);
5178/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__keys_js__ = __webpack_require__(6);
5179
5180
5181
5182// Returns the first key on an object that passes a truth test.
5183function findKey(obj, predicate, context) {
5184 predicate = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(predicate, context);
5185 var _keys = Object(__WEBPACK_IMPORTED_MODULE_1__keys_js__["a" /* default */])(obj), key;
5186 for (var i = 0, length = _keys.length; i < length; i++) {
5187 key = _keys[i];
5188 if (predicate(obj[key], key, obj)) return key;
5189 }
5190}
5191
5192
5193/***/ }),
5194/* 161 */
5195/***/ (function(module, __webpack_exports__, __webpack_require__) {
5196
5197"use strict";
5198/* harmony export (immutable) */ __webpack_exports__["a"] = createPredicateIndexFinder;
5199/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(10);
5200/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__getLength_js__ = __webpack_require__(18);
5201
5202
5203
5204// Internal function to generate `_.findIndex` and `_.findLastIndex`.
5205function createPredicateIndexFinder(dir) {
5206 return function(array, predicate, context) {
5207 predicate = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(predicate, context);
5208 var length = Object(__WEBPACK_IMPORTED_MODULE_1__getLength_js__["a" /* default */])(array);
5209 var index = dir > 0 ? 0 : length - 1;
5210 for (; index >= 0 && index < length; index += dir) {
5211 if (predicate(array[index], index, array)) return index;
5212 }
5213 return -1;
5214 };
5215}
5216
5217
5218/***/ }),
5219/* 162 */
5220/***/ (function(module, __webpack_exports__, __webpack_require__) {
5221
5222"use strict";
5223/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createPredicateIndexFinder_js__ = __webpack_require__(161);
5224
5225
5226// Returns the last index on an array-like that passes a truth test.
5227/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createPredicateIndexFinder_js__["a" /* default */])(-1));
5228
5229
5230/***/ }),
5231/* 163 */
5232/***/ (function(module, __webpack_exports__, __webpack_require__) {
5233
5234"use strict";
5235/* harmony export (immutable) */ __webpack_exports__["a"] = sortedIndex;
5236/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(10);
5237/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__getLength_js__ = __webpack_require__(18);
5238
5239
5240
5241// Use a comparator function to figure out the smallest index at which
5242// an object should be inserted so as to maintain order. Uses binary search.
5243function sortedIndex(array, obj, iteratee, context) {
5244 iteratee = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(iteratee, context, 1);
5245 var value = iteratee(obj);
5246 var low = 0, high = Object(__WEBPACK_IMPORTED_MODULE_1__getLength_js__["a" /* default */])(array);
5247 while (low < high) {
5248 var mid = Math.floor((low + high) / 2);
5249 if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
5250 }
5251 return low;
5252}
5253
5254
5255/***/ }),
5256/* 164 */
5257/***/ (function(module, __webpack_exports__, __webpack_require__) {
5258
5259"use strict";
5260/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__sortedIndex_js__ = __webpack_require__(163);
5261/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__findIndex_js__ = __webpack_require__(105);
5262/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__createIndexFinder_js__ = __webpack_require__(165);
5263
5264
5265
5266
5267// Return the position of the first occurrence of an item in an array,
5268// or -1 if the item is not included in the array.
5269// If the array is large and already in sort order, pass `true`
5270// for **isSorted** to use binary search.
5271/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_2__createIndexFinder_js__["a" /* default */])(1, __WEBPACK_IMPORTED_MODULE_1__findIndex_js__["a" /* default */], __WEBPACK_IMPORTED_MODULE_0__sortedIndex_js__["a" /* default */]));
5272
5273
5274/***/ }),
5275/* 165 */
5276/***/ (function(module, __webpack_exports__, __webpack_require__) {
5277
5278"use strict";
5279/* harmony export (immutable) */ __webpack_exports__["a"] = createIndexFinder;
5280/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__getLength_js__ = __webpack_require__(18);
5281/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__setup_js__ = __webpack_require__(2);
5282/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isNaN_js__ = __webpack_require__(134);
5283
5284
5285
5286
5287// Internal function to generate the `_.indexOf` and `_.lastIndexOf` functions.
5288function createIndexFinder(dir, predicateFind, sortedIndex) {
5289 return function(array, item, idx) {
5290 var i = 0, length = Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(array);
5291 if (typeof idx == 'number') {
5292 if (dir > 0) {
5293 i = idx >= 0 ? idx : Math.max(idx + length, i);
5294 } else {
5295 length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
5296 }
5297 } else if (sortedIndex && idx && length) {
5298 idx = sortedIndex(array, item);
5299 return array[idx] === item ? idx : -1;
5300 }
5301 if (item !== item) {
5302 idx = predicateFind(__WEBPACK_IMPORTED_MODULE_1__setup_js__["q" /* slice */].call(array, i, length), __WEBPACK_IMPORTED_MODULE_2__isNaN_js__["a" /* default */]);
5303 return idx >= 0 ? idx + i : -1;
5304 }
5305 for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
5306 if (array[idx] === item) return idx;
5307 }
5308 return -1;
5309 };
5310}
5311
5312
5313/***/ }),
5314/* 166 */
5315/***/ (function(module, __webpack_exports__, __webpack_require__) {
5316
5317"use strict";
5318/* harmony export (immutable) */ __webpack_exports__["a"] = find;
5319/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__ = __webpack_require__(13);
5320/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__findIndex_js__ = __webpack_require__(105);
5321/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__findKey_js__ = __webpack_require__(160);
5322
5323
5324
5325
5326// Return the first value which passes a truth test.
5327function find(obj, predicate, context) {
5328 var keyFinder = Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj) ? __WEBPACK_IMPORTED_MODULE_1__findIndex_js__["a" /* default */] : __WEBPACK_IMPORTED_MODULE_2__findKey_js__["a" /* default */];
5329 var key = keyFinder(obj, predicate, context);
5330 if (key !== void 0 && key !== -1) return obj[key];
5331}
5332
5333
5334/***/ }),
5335/* 167 */
5336/***/ (function(module, __webpack_exports__, __webpack_require__) {
5337
5338"use strict";
5339/* harmony export (immutable) */ __webpack_exports__["a"] = createReduce;
5340/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__ = __webpack_require__(13);
5341/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__keys_js__ = __webpack_require__(6);
5342/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__optimizeCb_js__ = __webpack_require__(55);
5343
5344
5345
5346
5347// Internal helper to create a reducing function, iterating left or right.
5348function createReduce(dir) {
5349 // Wrap code that reassigns argument variables in a separate function than
5350 // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
5351 var reducer = function(obj, iteratee, memo, initial) {
5352 var _keys = !Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj) && Object(__WEBPACK_IMPORTED_MODULE_1__keys_js__["a" /* default */])(obj),
5353 length = (_keys || obj).length,
5354 index = dir > 0 ? 0 : length - 1;
5355 if (!initial) {
5356 memo = obj[_keys ? _keys[index] : index];
5357 index += dir;
5358 }
5359 for (; index >= 0 && index < length; index += dir) {
5360 var currentKey = _keys ? _keys[index] : index;
5361 memo = iteratee(memo, obj[currentKey], currentKey, obj);
5362 }
5363 return memo;
5364 };
5365
5366 return function(obj, iteratee, memo, context) {
5367 var initial = arguments.length >= 3;
5368 return reducer(obj, Object(__WEBPACK_IMPORTED_MODULE_2__optimizeCb_js__["a" /* default */])(iteratee, context, 4), memo, initial);
5369 };
5370}
5371
5372
5373/***/ }),
5374/* 168 */
5375/***/ (function(module, __webpack_exports__, __webpack_require__) {
5376
5377"use strict";
5378/* harmony export (immutable) */ __webpack_exports__["a"] = max;
5379/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__ = __webpack_require__(13);
5380/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__values_js__ = __webpack_require__(39);
5381/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__cb_js__ = __webpack_require__(10);
5382/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__each_js__ = __webpack_require__(32);
5383
5384
5385
5386
5387
5388// Return the maximum element (or element-based computation).
5389function max(obj, iteratee, context) {
5390 var result = -Infinity, lastComputed = -Infinity,
5391 value, computed;
5392 if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
5393 obj = Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj) ? obj : Object(__WEBPACK_IMPORTED_MODULE_1__values_js__["a" /* default */])(obj);
5394 for (var i = 0, length = obj.length; i < length; i++) {
5395 value = obj[i];
5396 if (value != null && value > result) {
5397 result = value;
5398 }
5399 }
5400 } else {
5401 iteratee = Object(__WEBPACK_IMPORTED_MODULE_2__cb_js__["a" /* default */])(iteratee, context);
5402 Object(__WEBPACK_IMPORTED_MODULE_3__each_js__["a" /* default */])(obj, function(v, index, list) {
5403 computed = iteratee(v, index, list);
5404 if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
5405 result = v;
5406 lastComputed = computed;
5407 }
5408 });
5409 }
5410 return result;
5411}
5412
5413
5414/***/ }),
5415/* 169 */
5416/***/ (function(module, __webpack_exports__, __webpack_require__) {
5417
5418"use strict";
5419/* harmony export (immutable) */ __webpack_exports__["a"] = sample;
5420/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__ = __webpack_require__(13);
5421/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__clone_js__ = __webpack_require__(146);
5422/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__values_js__ = __webpack_require__(39);
5423/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__getLength_js__ = __webpack_require__(18);
5424/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__random_js__ = __webpack_require__(152);
5425
5426
5427
5428
5429
5430
5431// Sample **n** random values from a collection using the modern version of the
5432// [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
5433// If **n** is not specified, returns a single random element.
5434// The internal `guard` argument allows it to work with `_.map`.
5435function sample(obj, n, guard) {
5436 if (n == null || guard) {
5437 if (!Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj)) obj = Object(__WEBPACK_IMPORTED_MODULE_2__values_js__["a" /* default */])(obj);
5438 return obj[Object(__WEBPACK_IMPORTED_MODULE_4__random_js__["a" /* default */])(obj.length - 1)];
5439 }
5440 var sample = Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj) ? Object(__WEBPACK_IMPORTED_MODULE_1__clone_js__["a" /* default */])(obj) : Object(__WEBPACK_IMPORTED_MODULE_2__values_js__["a" /* default */])(obj);
5441 var length = Object(__WEBPACK_IMPORTED_MODULE_3__getLength_js__["a" /* default */])(sample);
5442 n = Math.max(Math.min(n, length), 0);
5443 var last = length - 1;
5444 for (var index = 0; index < n; index++) {
5445 var rand = Object(__WEBPACK_IMPORTED_MODULE_4__random_js__["a" /* default */])(index, last);
5446 var temp = sample[index];
5447 sample[index] = sample[rand];
5448 sample[rand] = temp;
5449 }
5450 return sample.slice(0, n);
5451}
5452
5453
5454/***/ }),
5455/* 170 */
5456/***/ (function(module, __webpack_exports__, __webpack_require__) {
5457
5458"use strict";
5459/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(11);
5460/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(17);
5461/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__optimizeCb_js__ = __webpack_require__(55);
5462/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__allKeys_js__ = __webpack_require__(53);
5463/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__keyInObj_js__ = __webpack_require__(286);
5464/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__flatten_js__ = __webpack_require__(40);
5465
5466
5467
5468
5469
5470
5471
5472// Return a copy of the object only containing the allowed properties.
5473/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(obj, keys) {
5474 var result = {}, iteratee = keys[0];
5475 if (obj == null) return result;
5476 if (Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(iteratee)) {
5477 if (keys.length > 1) iteratee = Object(__WEBPACK_IMPORTED_MODULE_2__optimizeCb_js__["a" /* default */])(iteratee, keys[1]);
5478 keys = Object(__WEBPACK_IMPORTED_MODULE_3__allKeys_js__["a" /* default */])(obj);
5479 } else {
5480 iteratee = __WEBPACK_IMPORTED_MODULE_4__keyInObj_js__["a" /* default */];
5481 keys = Object(__WEBPACK_IMPORTED_MODULE_5__flatten_js__["a" /* default */])(keys, false, false);
5482 obj = Object(obj);
5483 }
5484 for (var i = 0, length = keys.length; i < length; i++) {
5485 var key = keys[i];
5486 var value = obj[key];
5487 if (iteratee(value, key, obj)) result[key] = value;
5488 }
5489 return result;
5490}));
5491
5492
5493/***/ }),
5494/* 171 */
5495/***/ (function(module, __webpack_exports__, __webpack_require__) {
5496
5497"use strict";
5498/* harmony export (immutable) */ __webpack_exports__["a"] = initial;
5499/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
5500
5501
5502// Returns everything but the last entry of the array. Especially useful on
5503// the arguments object. Passing **n** will return all the values in
5504// the array, excluding the last N.
5505function initial(array, n, guard) {
5506 return __WEBPACK_IMPORTED_MODULE_0__setup_js__["q" /* slice */].call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
5507}
5508
5509
5510/***/ }),
5511/* 172 */
5512/***/ (function(module, __webpack_exports__, __webpack_require__) {
5513
5514"use strict";
5515/* harmony export (immutable) */ __webpack_exports__["a"] = rest;
5516/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
5517
5518
5519// Returns everything but the first entry of the `array`. Especially useful on
5520// the `arguments` object. Passing an **n** will return the rest N values in the
5521// `array`.
5522function rest(array, n, guard) {
5523 return __WEBPACK_IMPORTED_MODULE_0__setup_js__["q" /* slice */].call(array, n == null || guard ? 1 : n);
5524}
5525
5526
5527/***/ }),
5528/* 173 */
5529/***/ (function(module, __webpack_exports__, __webpack_require__) {
5530
5531"use strict";
5532/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(11);
5533/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__flatten_js__ = __webpack_require__(40);
5534/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__filter_js__ = __webpack_require__(56);
5535/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__contains_js__ = __webpack_require__(57);
5536
5537
5538
5539
5540
5541// Take the difference between one array and a number of other arrays.
5542// Only the elements present in just the first array will remain.
5543/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(array, rest) {
5544 rest = Object(__WEBPACK_IMPORTED_MODULE_1__flatten_js__["a" /* default */])(rest, true, true);
5545 return Object(__WEBPACK_IMPORTED_MODULE_2__filter_js__["a" /* default */])(array, function(value){
5546 return !Object(__WEBPACK_IMPORTED_MODULE_3__contains_js__["a" /* default */])(rest, value);
5547 });
5548}));
5549
5550
5551/***/ }),
5552/* 174 */
5553/***/ (function(module, __webpack_exports__, __webpack_require__) {
5554
5555"use strict";
5556/* harmony export (immutable) */ __webpack_exports__["a"] = uniq;
5557/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isBoolean_js__ = __webpack_require__(130);
5558/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__cb_js__ = __webpack_require__(10);
5559/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__getLength_js__ = __webpack_require__(18);
5560/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__contains_js__ = __webpack_require__(57);
5561
5562
5563
5564
5565
5566// Produce a duplicate-free version of the array. If the array has already
5567// been sorted, you have the option of using a faster algorithm.
5568// The faster algorithm will not work with an iteratee if the iteratee
5569// is not a one-to-one function, so providing an iteratee will disable
5570// the faster algorithm.
5571function uniq(array, isSorted, iteratee, context) {
5572 if (!Object(__WEBPACK_IMPORTED_MODULE_0__isBoolean_js__["a" /* default */])(isSorted)) {
5573 context = iteratee;
5574 iteratee = isSorted;
5575 isSorted = false;
5576 }
5577 if (iteratee != null) iteratee = Object(__WEBPACK_IMPORTED_MODULE_1__cb_js__["a" /* default */])(iteratee, context);
5578 var result = [];
5579 var seen = [];
5580 for (var i = 0, length = Object(__WEBPACK_IMPORTED_MODULE_2__getLength_js__["a" /* default */])(array); i < length; i++) {
5581 var value = array[i],
5582 computed = iteratee ? iteratee(value, i, array) : value;
5583 if (isSorted && !iteratee) {
5584 if (!i || seen !== computed) result.push(value);
5585 seen = computed;
5586 } else if (iteratee) {
5587 if (!Object(__WEBPACK_IMPORTED_MODULE_3__contains_js__["a" /* default */])(seen, computed)) {
5588 seen.push(computed);
5589 result.push(value);
5590 }
5591 } else if (!Object(__WEBPACK_IMPORTED_MODULE_3__contains_js__["a" /* default */])(result, value)) {
5592 result.push(value);
5593 }
5594 }
5595 return result;
5596}
5597
5598
5599/***/ }),
5600/* 175 */
5601/***/ (function(module, __webpack_exports__, __webpack_require__) {
5602
5603"use strict";
5604/* harmony export (immutable) */ __webpack_exports__["a"] = unzip;
5605/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__max_js__ = __webpack_require__(168);
5606/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__getLength_js__ = __webpack_require__(18);
5607/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__pluck_js__ = __webpack_require__(106);
5608
5609
5610
5611
5612// Complement of zip. Unzip accepts an array of arrays and groups
5613// each array's elements on shared indices.
5614function unzip(array) {
5615 var length = array && Object(__WEBPACK_IMPORTED_MODULE_0__max_js__["a" /* default */])(array, __WEBPACK_IMPORTED_MODULE_1__getLength_js__["a" /* default */]).length || 0;
5616 var result = Array(length);
5617
5618 for (var index = 0; index < length; index++) {
5619 result[index] = Object(__WEBPACK_IMPORTED_MODULE_2__pluck_js__["a" /* default */])(array, index);
5620 }
5621 return result;
5622}
5623
5624
5625/***/ }),
5626/* 176 */
5627/***/ (function(module, __webpack_exports__, __webpack_require__) {
5628
5629"use strict";
5630/* harmony export (immutable) */ __webpack_exports__["a"] = chainResult;
5631/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(12);
5632
5633
5634// Helper function to continue chaining intermediate results.
5635function chainResult(instance, obj) {
5636 return instance._chain ? Object(__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */])(obj).chain() : obj;
5637}
5638
5639
5640/***/ }),
5641/* 177 */
5642/***/ (function(module, exports, __webpack_require__) {
5643
5644var rng = __webpack_require__(304);
5645var bytesToUuid = __webpack_require__(305);
5646
5647function v4(options, buf, offset) {
5648 var i = buf && offset || 0;
5649
5650 if (typeof(options) == 'string') {
5651 buf = options === 'binary' ? new Array(16) : null;
5652 options = null;
5653 }
5654 options = options || {};
5655
5656 var rnds = options.random || (options.rng || rng)();
5657
5658 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
5659 rnds[6] = (rnds[6] & 0x0f) | 0x40;
5660 rnds[8] = (rnds[8] & 0x3f) | 0x80;
5661
5662 // Copy bytes to buffer, if provided
5663 if (buf) {
5664 for (var ii = 0; ii < 16; ++ii) {
5665 buf[i + ii] = rnds[ii];
5666 }
5667 }
5668
5669 return buf || bytesToUuid(rnds);
5670}
5671
5672module.exports = v4;
5673
5674
5675/***/ }),
5676/* 178 */
5677/***/ (function(module, exports, __webpack_require__) {
5678
5679module.exports = { "default": __webpack_require__(308), __esModule: true };
5680
5681/***/ }),
5682/* 179 */
5683/***/ (function(module, exports, __webpack_require__) {
5684
5685"use strict";
5686
5687
5688module.exports = '4.12.2';
5689
5690/***/ }),
5691/* 180 */
5692/***/ (function(module, exports, __webpack_require__) {
5693
5694"use strict";
5695
5696
5697var has = Object.prototype.hasOwnProperty
5698 , prefix = '~';
5699
5700/**
5701 * Constructor to create a storage for our `EE` objects.
5702 * An `Events` instance is a plain object whose properties are event names.
5703 *
5704 * @constructor
5705 * @api private
5706 */
5707function Events() {}
5708
5709//
5710// We try to not inherit from `Object.prototype`. In some engines creating an
5711// instance in this way is faster than calling `Object.create(null)` directly.
5712// If `Object.create(null)` is not supported we prefix the event names with a
5713// character to make sure that the built-in object properties are not
5714// overridden or used as an attack vector.
5715//
5716if (Object.create) {
5717 Events.prototype = Object.create(null);
5718
5719 //
5720 // This hack is needed because the `__proto__` property is still inherited in
5721 // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
5722 //
5723 if (!new Events().__proto__) prefix = false;
5724}
5725
5726/**
5727 * Representation of a single event listener.
5728 *
5729 * @param {Function} fn The listener function.
5730 * @param {Mixed} context The context to invoke the listener with.
5731 * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
5732 * @constructor
5733 * @api private
5734 */
5735function EE(fn, context, once) {
5736 this.fn = fn;
5737 this.context = context;
5738 this.once = once || false;
5739}
5740
5741/**
5742 * Minimal `EventEmitter` interface that is molded against the Node.js
5743 * `EventEmitter` interface.
5744 *
5745 * @constructor
5746 * @api public
5747 */
5748function EventEmitter() {
5749 this._events = new Events();
5750 this._eventsCount = 0;
5751}
5752
5753/**
5754 * Return an array listing the events for which the emitter has registered
5755 * listeners.
5756 *
5757 * @returns {Array}
5758 * @api public
5759 */
5760EventEmitter.prototype.eventNames = function eventNames() {
5761 var names = []
5762 , events
5763 , name;
5764
5765 if (this._eventsCount === 0) return names;
5766
5767 for (name in (events = this._events)) {
5768 if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
5769 }
5770
5771 if (Object.getOwnPropertySymbols) {
5772 return names.concat(Object.getOwnPropertySymbols(events));
5773 }
5774
5775 return names;
5776};
5777
5778/**
5779 * Return the listeners registered for a given event.
5780 *
5781 * @param {String|Symbol} event The event name.
5782 * @param {Boolean} exists Only check if there are listeners.
5783 * @returns {Array|Boolean}
5784 * @api public
5785 */
5786EventEmitter.prototype.listeners = function listeners(event, exists) {
5787 var evt = prefix ? prefix + event : event
5788 , available = this._events[evt];
5789
5790 if (exists) return !!available;
5791 if (!available) return [];
5792 if (available.fn) return [available.fn];
5793
5794 for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) {
5795 ee[i] = available[i].fn;
5796 }
5797
5798 return ee;
5799};
5800
5801/**
5802 * Calls each of the listeners registered for a given event.
5803 *
5804 * @param {String|Symbol} event The event name.
5805 * @returns {Boolean} `true` if the event had listeners, else `false`.
5806 * @api public
5807 */
5808EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
5809 var evt = prefix ? prefix + event : event;
5810
5811 if (!this._events[evt]) return false;
5812
5813 var listeners = this._events[evt]
5814 , len = arguments.length
5815 , args
5816 , i;
5817
5818 if (listeners.fn) {
5819 if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
5820
5821 switch (len) {
5822 case 1: return listeners.fn.call(listeners.context), true;
5823 case 2: return listeners.fn.call(listeners.context, a1), true;
5824 case 3: return listeners.fn.call(listeners.context, a1, a2), true;
5825 case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
5826 case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
5827 case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
5828 }
5829
5830 for (i = 1, args = new Array(len -1); i < len; i++) {
5831 args[i - 1] = arguments[i];
5832 }
5833
5834 listeners.fn.apply(listeners.context, args);
5835 } else {
5836 var length = listeners.length
5837 , j;
5838
5839 for (i = 0; i < length; i++) {
5840 if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
5841
5842 switch (len) {
5843 case 1: listeners[i].fn.call(listeners[i].context); break;
5844 case 2: listeners[i].fn.call(listeners[i].context, a1); break;
5845 case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
5846 case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
5847 default:
5848 if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
5849 args[j - 1] = arguments[j];
5850 }
5851
5852 listeners[i].fn.apply(listeners[i].context, args);
5853 }
5854 }
5855 }
5856
5857 return true;
5858};
5859
5860/**
5861 * Add a listener for a given event.
5862 *
5863 * @param {String|Symbol} event The event name.
5864 * @param {Function} fn The listener function.
5865 * @param {Mixed} [context=this] The context to invoke the listener with.
5866 * @returns {EventEmitter} `this`.
5867 * @api public
5868 */
5869EventEmitter.prototype.on = function on(event, fn, context) {
5870 var listener = new EE(fn, context || this)
5871 , evt = prefix ? prefix + event : event;
5872
5873 if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
5874 else if (!this._events[evt].fn) this._events[evt].push(listener);
5875 else this._events[evt] = [this._events[evt], listener];
5876
5877 return this;
5878};
5879
5880/**
5881 * Add a one-time listener for a given event.
5882 *
5883 * @param {String|Symbol} event The event name.
5884 * @param {Function} fn The listener function.
5885 * @param {Mixed} [context=this] The context to invoke the listener with.
5886 * @returns {EventEmitter} `this`.
5887 * @api public
5888 */
5889EventEmitter.prototype.once = function once(event, fn, context) {
5890 var listener = new EE(fn, context || this, true)
5891 , evt = prefix ? prefix + event : event;
5892
5893 if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
5894 else if (!this._events[evt].fn) this._events[evt].push(listener);
5895 else this._events[evt] = [this._events[evt], listener];
5896
5897 return this;
5898};
5899
5900/**
5901 * Remove the listeners of a given event.
5902 *
5903 * @param {String|Symbol} event The event name.
5904 * @param {Function} fn Only remove the listeners that match this function.
5905 * @param {Mixed} context Only remove the listeners that have this context.
5906 * @param {Boolean} once Only remove one-time listeners.
5907 * @returns {EventEmitter} `this`.
5908 * @api public
5909 */
5910EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
5911 var evt = prefix ? prefix + event : event;
5912
5913 if (!this._events[evt]) return this;
5914 if (!fn) {
5915 if (--this._eventsCount === 0) this._events = new Events();
5916 else delete this._events[evt];
5917 return this;
5918 }
5919
5920 var listeners = this._events[evt];
5921
5922 if (listeners.fn) {
5923 if (
5924 listeners.fn === fn
5925 && (!once || listeners.once)
5926 && (!context || listeners.context === context)
5927 ) {
5928 if (--this._eventsCount === 0) this._events = new Events();
5929 else delete this._events[evt];
5930 }
5931 } else {
5932 for (var i = 0, events = [], length = listeners.length; i < length; i++) {
5933 if (
5934 listeners[i].fn !== fn
5935 || (once && !listeners[i].once)
5936 || (context && listeners[i].context !== context)
5937 ) {
5938 events.push(listeners[i]);
5939 }
5940 }
5941
5942 //
5943 // Reset the array, or remove it completely if we have no more listeners.
5944 //
5945 if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
5946 else if (--this._eventsCount === 0) this._events = new Events();
5947 else delete this._events[evt];
5948 }
5949
5950 return this;
5951};
5952
5953/**
5954 * Remove all listeners, or those of the specified event.
5955 *
5956 * @param {String|Symbol} [event] The event name.
5957 * @returns {EventEmitter} `this`.
5958 * @api public
5959 */
5960EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
5961 var evt;
5962
5963 if (event) {
5964 evt = prefix ? prefix + event : event;
5965 if (this._events[evt]) {
5966 if (--this._eventsCount === 0) this._events = new Events();
5967 else delete this._events[evt];
5968 }
5969 } else {
5970 this._events = new Events();
5971 this._eventsCount = 0;
5972 }
5973
5974 return this;
5975};
5976
5977//
5978// Alias methods names because people roll like that.
5979//
5980EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
5981EventEmitter.prototype.addListener = EventEmitter.prototype.on;
5982
5983//
5984// This function doesn't apply anymore.
5985//
5986EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
5987 return this;
5988};
5989
5990//
5991// Expose the prefix.
5992//
5993EventEmitter.prefixed = prefix;
5994
5995//
5996// Allow `EventEmitter` to be imported as module namespace.
5997//
5998EventEmitter.EventEmitter = EventEmitter;
5999
6000//
6001// Expose the module.
6002//
6003if (true) {
6004 module.exports = EventEmitter;
6005}
6006
6007
6008/***/ }),
6009/* 181 */
6010/***/ (function(module, exports, __webpack_require__) {
6011
6012"use strict";
6013
6014
6015var _promise = __webpack_require__(3);
6016
6017var _promise2 = _interopRequireDefault(_promise);
6018
6019function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
6020
6021var _require = __webpack_require__(43),
6022 getAdapter = _require.getAdapter;
6023
6024var syncApiNames = ['getItem', 'setItem', 'removeItem', 'clear'];
6025
6026var localStorage = {
6027 get async() {
6028 return getAdapter('storage').async;
6029 }
6030};
6031
6032// wrap sync apis with async ones.
6033syncApiNames.forEach(function (apiName) {
6034 localStorage[apiName + 'Async'] = function () {
6035 var storage = getAdapter('storage');
6036 return _promise2.default.resolve(storage[apiName].apply(storage, arguments));
6037 };
6038
6039 localStorage[apiName] = function () {
6040 var storage = getAdapter('storage');
6041 if (!storage.async) {
6042 return storage[apiName].apply(storage, arguments);
6043 }
6044 var error = new Error('Synchronous API [' + apiName + '] is not available in this runtime.');
6045 error.code = 'SYNC_API_NOT_AVAILABLE';
6046 throw error;
6047 };
6048});
6049
6050module.exports = localStorage;
6051
6052/***/ }),
6053/* 182 */
6054/***/ (function(module, exports, __webpack_require__) {
6055
6056"use strict";
6057
6058
6059var _stringify = __webpack_require__(21);
6060
6061var _stringify2 = _interopRequireDefault(_stringify);
6062
6063function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
6064
6065var storage = __webpack_require__(181);
6066var AV = __webpack_require__(42);
6067
6068var removeAsync = exports.removeAsync = storage.removeItemAsync.bind(storage);
6069
6070var getCacheData = function getCacheData(cacheData, key) {
6071 try {
6072 cacheData = JSON.parse(cacheData);
6073 } catch (e) {
6074 return null;
6075 }
6076 if (cacheData) {
6077 var expired = cacheData.expiredAt && cacheData.expiredAt < Date.now();
6078 if (!expired) {
6079 return cacheData.value;
6080 }
6081 return removeAsync(key).then(function () {
6082 return null;
6083 });
6084 }
6085 return null;
6086};
6087
6088exports.getAsync = function (key) {
6089 key = 'AV/' + AV.applicationId + '/' + key;
6090 return storage.getItemAsync(key).then(function (cache) {
6091 return getCacheData(cache, key);
6092 });
6093};
6094
6095exports.setAsync = function (key, value, ttl) {
6096 var cache = { value: value };
6097 if (typeof ttl === 'number') {
6098 cache.expiredAt = Date.now() + ttl;
6099 }
6100 return storage.setItemAsync('AV/' + AV.applicationId + '/' + key, (0, _stringify2.default)(cache));
6101};
6102
6103/***/ }),
6104/* 183 */
6105/***/ (function(module, exports, __webpack_require__) {
6106
6107"use strict";
6108
6109// ECMAScript 6 symbols shim
6110var global = __webpack_require__(5);
6111var has = __webpack_require__(25);
6112var DESCRIPTORS = __webpack_require__(16);
6113var $export = __webpack_require__(4);
6114var redefine = __webpack_require__(85);
6115var META = __webpack_require__(45).KEY;
6116var $fails = __webpack_require__(28);
6117var shared = __webpack_require__(88);
6118var setToStringTag = __webpack_require__(51);
6119var uid = __webpack_require__(62);
6120var wks = __webpack_require__(8);
6121var wksExt = __webpack_require__(108);
6122var wksDefine = __webpack_require__(109);
6123var enumKeys = __webpack_require__(316);
6124var isArray = __webpack_require__(184);
6125var anObject = __webpack_require__(15);
6126var isObject = __webpack_require__(9);
6127var toObject = __webpack_require__(29);
6128var toIObject = __webpack_require__(26);
6129var toPrimitive = __webpack_require__(84);
6130var createDesc = __webpack_require__(48);
6131var _create = __webpack_require__(60);
6132var gOPNExt = __webpack_require__(317);
6133var $GOPD = __webpack_require__(76);
6134var $GOPS = __webpack_require__(74);
6135var $DP = __webpack_require__(20);
6136var $keys = __webpack_require__(49);
6137var gOPD = $GOPD.f;
6138var dP = $DP.f;
6139var gOPN = gOPNExt.f;
6140var $Symbol = global.Symbol;
6141var $JSON = global.JSON;
6142var _stringify = $JSON && $JSON.stringify;
6143var PROTOTYPE = 'prototype';
6144var HIDDEN = wks('_hidden');
6145var TO_PRIMITIVE = wks('toPrimitive');
6146var isEnum = {}.propertyIsEnumerable;
6147var SymbolRegistry = shared('symbol-registry');
6148var AllSymbols = shared('symbols');
6149var OPSymbols = shared('op-symbols');
6150var ObjectProto = Object[PROTOTYPE];
6151var USE_NATIVE = typeof $Symbol == 'function' && !!$GOPS.f;
6152var QObject = global.QObject;
6153// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
6154var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
6155
6156// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
6157var setSymbolDesc = DESCRIPTORS && $fails(function () {
6158 return _create(dP({}, 'a', {
6159 get: function () { return dP(this, 'a', { value: 7 }).a; }
6160 })).a != 7;
6161}) ? function (it, key, D) {
6162 var protoDesc = gOPD(ObjectProto, key);
6163 if (protoDesc) delete ObjectProto[key];
6164 dP(it, key, D);
6165 if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);
6166} : dP;
6167
6168var wrap = function (tag) {
6169 var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
6170 sym._k = tag;
6171 return sym;
6172};
6173
6174var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {
6175 return typeof it == 'symbol';
6176} : function (it) {
6177 return it instanceof $Symbol;
6178};
6179
6180var $defineProperty = function defineProperty(it, key, D) {
6181 if (it === ObjectProto) $defineProperty(OPSymbols, key, D);
6182 anObject(it);
6183 key = toPrimitive(key, true);
6184 anObject(D);
6185 if (has(AllSymbols, key)) {
6186 if (!D.enumerable) {
6187 if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));
6188 it[HIDDEN][key] = true;
6189 } else {
6190 if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
6191 D = _create(D, { enumerable: createDesc(0, false) });
6192 } return setSymbolDesc(it, key, D);
6193 } return dP(it, key, D);
6194};
6195var $defineProperties = function defineProperties(it, P) {
6196 anObject(it);
6197 var keys = enumKeys(P = toIObject(P));
6198 var i = 0;
6199 var l = keys.length;
6200 var key;
6201 while (l > i) $defineProperty(it, key = keys[i++], P[key]);
6202 return it;
6203};
6204var $create = function create(it, P) {
6205 return P === undefined ? _create(it) : $defineProperties(_create(it), P);
6206};
6207var $propertyIsEnumerable = function propertyIsEnumerable(key) {
6208 var E = isEnum.call(this, key = toPrimitive(key, true));
6209 if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;
6210 return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
6211};
6212var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
6213 it = toIObject(it);
6214 key = toPrimitive(key, true);
6215 if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;
6216 var D = gOPD(it, key);
6217 if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
6218 return D;
6219};
6220var $getOwnPropertyNames = function getOwnPropertyNames(it) {
6221 var names = gOPN(toIObject(it));
6222 var result = [];
6223 var i = 0;
6224 var key;
6225 while (names.length > i) {
6226 if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
6227 } return result;
6228};
6229var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
6230 var IS_OP = it === ObjectProto;
6231 var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
6232 var result = [];
6233 var i = 0;
6234 var key;
6235 while (names.length > i) {
6236 if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);
6237 } return result;
6238};
6239
6240// 19.4.1.1 Symbol([description])
6241if (!USE_NATIVE) {
6242 $Symbol = function Symbol() {
6243 if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
6244 var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
6245 var $set = function (value) {
6246 if (this === ObjectProto) $set.call(OPSymbols, value);
6247 if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
6248 setSymbolDesc(this, tag, createDesc(1, value));
6249 };
6250 if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set });
6251 return wrap(tag);
6252 };
6253 redefine($Symbol[PROTOTYPE], 'toString', function toString() {
6254 return this._k;
6255 });
6256
6257 $GOPD.f = $getOwnPropertyDescriptor;
6258 $DP.f = $defineProperty;
6259 __webpack_require__(110).f = gOPNExt.f = $getOwnPropertyNames;
6260 __webpack_require__(75).f = $propertyIsEnumerable;
6261 $GOPS.f = $getOwnPropertySymbols;
6262
6263 if (DESCRIPTORS && !__webpack_require__(46)) {
6264 redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
6265 }
6266
6267 wksExt.f = function (name) {
6268 return wrap(wks(name));
6269 };
6270}
6271
6272$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol });
6273
6274for (var es6Symbols = (
6275 // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
6276 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
6277).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);
6278
6279for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);
6280
6281$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
6282 // 19.4.2.1 Symbol.for(key)
6283 'for': function (key) {
6284 return has(SymbolRegistry, key += '')
6285 ? SymbolRegistry[key]
6286 : SymbolRegistry[key] = $Symbol(key);
6287 },
6288 // 19.4.2.5 Symbol.keyFor(sym)
6289 keyFor: function keyFor(sym) {
6290 if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
6291 for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
6292 },
6293 useSetter: function () { setter = true; },
6294 useSimple: function () { setter = false; }
6295});
6296
6297$export($export.S + $export.F * !USE_NATIVE, 'Object', {
6298 // 19.1.2.2 Object.create(O [, Properties])
6299 create: $create,
6300 // 19.1.2.4 Object.defineProperty(O, P, Attributes)
6301 defineProperty: $defineProperty,
6302 // 19.1.2.3 Object.defineProperties(O, Properties)
6303 defineProperties: $defineProperties,
6304 // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
6305 getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
6306 // 19.1.2.7 Object.getOwnPropertyNames(O)
6307 getOwnPropertyNames: $getOwnPropertyNames,
6308 // 19.1.2.8 Object.getOwnPropertySymbols(O)
6309 getOwnPropertySymbols: $getOwnPropertySymbols
6310});
6311
6312// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
6313// https://bugs.chromium.org/p/v8/issues/detail?id=3443
6314var FAILS_ON_PRIMITIVES = $fails(function () { $GOPS.f(1); });
6315
6316$export($export.S + $export.F * FAILS_ON_PRIMITIVES, 'Object', {
6317 getOwnPropertySymbols: function getOwnPropertySymbols(it) {
6318 return $GOPS.f(toObject(it));
6319 }
6320});
6321
6322// 24.3.2 JSON.stringify(value [, replacer [, space]])
6323$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {
6324 var S = $Symbol();
6325 // MS Edge converts symbol values to JSON as {}
6326 // WebKit converts symbol values to JSON as null
6327 // V8 throws on boxed symbols
6328 return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';
6329})), 'JSON', {
6330 stringify: function stringify(it) {
6331 var args = [it];
6332 var i = 1;
6333 var replacer, $replacer;
6334 while (arguments.length > i) args.push(arguments[i++]);
6335 $replacer = replacer = args[1];
6336 if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
6337 if (!isArray(replacer)) replacer = function (key, value) {
6338 if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
6339 if (!isSymbol(value)) return value;
6340 };
6341 args[1] = replacer;
6342 return _stringify.apply($JSON, args);
6343 }
6344});
6345
6346// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
6347$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(24)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
6348// 19.4.3.5 Symbol.prototype[@@toStringTag]
6349setToStringTag($Symbol, 'Symbol');
6350// 20.2.1.9 Math[@@toStringTag]
6351setToStringTag(Math, 'Math', true);
6352// 24.3.3 JSON[@@toStringTag]
6353setToStringTag(global.JSON, 'JSON', true);
6354
6355
6356/***/ }),
6357/* 184 */
6358/***/ (function(module, exports, __webpack_require__) {
6359
6360// 7.2.2 IsArray(argument)
6361var cof = __webpack_require__(50);
6362module.exports = Array.isArray || function isArray(arg) {
6363 return cof(arg) == 'Array';
6364};
6365
6366
6367/***/ }),
6368/* 185 */
6369/***/ (function(module, exports, __webpack_require__) {
6370
6371"use strict";
6372// Copyright (c) 2015-2017 David M. Lee, II
6373
6374
6375/**
6376 * Local reference to TimeoutError
6377 * @private
6378 */
6379var TimeoutError;
6380
6381/**
6382 * Rejects a promise with a {@link TimeoutError} if it does not settle within
6383 * the specified timeout.
6384 *
6385 * @param {Promise} promise The promise.
6386 * @param {number} timeoutMillis Number of milliseconds to wait on settling.
6387 * @returns {Promise} Either resolves/rejects with `promise`, or rejects with
6388 * `TimeoutError`, whichever settles first.
6389 */
6390var timeout = module.exports.timeout = function(promise, timeoutMillis) {
6391 var error = new TimeoutError(),
6392 timeout;
6393
6394 return Promise.race([
6395 promise,
6396 new Promise(function(resolve, reject) {
6397 timeout = setTimeout(function() {
6398 reject(error);
6399 }, timeoutMillis);
6400 }),
6401 ]).then(function(v) {
6402 clearTimeout(timeout);
6403 return v;
6404 }, function(err) {
6405 clearTimeout(timeout);
6406 throw err;
6407 });
6408};
6409
6410/**
6411 * Exception indicating that the timeout expired.
6412 */
6413TimeoutError = module.exports.TimeoutError = function() {
6414 Error.call(this)
6415 this.stack = Error().stack
6416 this.message = 'Timeout';
6417};
6418
6419TimeoutError.prototype = Object.create(Error.prototype);
6420TimeoutError.prototype.name = "TimeoutError";
6421
6422
6423/***/ }),
6424/* 186 */
6425/***/ (function(module, exports, __webpack_require__) {
6426
6427module.exports = { "default": __webpack_require__(338), __esModule: true };
6428
6429/***/ }),
6430/* 187 */
6431/***/ (function(module, exports) {
6432
6433var charenc = {
6434 // UTF-8 encoding
6435 utf8: {
6436 // Convert a string to a byte array
6437 stringToBytes: function(str) {
6438 return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));
6439 },
6440
6441 // Convert a byte array to a string
6442 bytesToString: function(bytes) {
6443 return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));
6444 }
6445 },
6446
6447 // Binary encoding
6448 bin: {
6449 // Convert a string to a byte array
6450 stringToBytes: function(str) {
6451 for (var bytes = [], i = 0; i < str.length; i++)
6452 bytes.push(str.charCodeAt(i) & 0xFF);
6453 return bytes;
6454 },
6455
6456 // Convert a byte array to a string
6457 bytesToString: function(bytes) {
6458 for (var str = [], i = 0; i < bytes.length; i++)
6459 str.push(String.fromCharCode(bytes[i]));
6460 return str.join('');
6461 }
6462 }
6463};
6464
6465module.exports = charenc;
6466
6467
6468/***/ }),
6469/* 188 */
6470/***/ (function(module, exports, __webpack_require__) {
6471
6472module.exports = { "default": __webpack_require__(347), __esModule: true };
6473
6474/***/ }),
6475/* 189 */
6476/***/ (function(module, exports, __webpack_require__) {
6477
6478"use strict";
6479
6480
6481var adapters = __webpack_require__(366);
6482
6483module.exports = function (AV) {
6484 AV.setAdapters(adapters);
6485 return AV;
6486};
6487
6488/***/ }),
6489/* 190 */
6490/***/ (function(module, exports, __webpack_require__) {
6491
6492"use strict";
6493
6494
6495var _iterator = __webpack_require__(73);
6496
6497var _iterator2 = _interopRequireDefault(_iterator);
6498
6499var _typeof3 = __webpack_require__(23);
6500
6501var _typeof4 = _interopRequireDefault(_typeof3);
6502
6503var _symbol = __webpack_require__(44);
6504
6505var _symbol2 = _interopRequireDefault(_symbol);
6506
6507function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
6508
6509function _typeof(obj) {
6510 "@babel/helpers - typeof";
6511 if (typeof _symbol2.default === "function" && (0, _typeof4.default)(_iterator2.default) === "symbol") {
6512 _typeof = function _typeof(obj) {
6513 return typeof obj === "undefined" ? "undefined" : (0, _typeof4.default)(obj);
6514 };
6515 } else {
6516 _typeof = function _typeof(obj) {
6517 return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : (0, _typeof4.default)(obj);
6518 };
6519 }return _typeof(obj);
6520}
6521
6522/**
6523 * Check if `obj` is an object.
6524 *
6525 * @param {Object} obj
6526 * @return {Boolean}
6527 * @api private
6528 */
6529function isObject(obj) {
6530 return obj !== null && _typeof(obj) === 'object';
6531}
6532
6533module.exports = isObject;
6534
6535/***/ }),
6536/* 191 */
6537/***/ (function(module, exports, __webpack_require__) {
6538
6539module.exports = { "default": __webpack_require__(376), __esModule: true };
6540
6541/***/ }),
6542/* 192 */
6543/***/ (function(module, exports, __webpack_require__) {
6544
6545"use strict";
6546
6547var $defineProperty = __webpack_require__(20);
6548var createDesc = __webpack_require__(48);
6549
6550module.exports = function (object, index, value) {
6551 if (index in object) $defineProperty.f(object, index, createDesc(0, value));
6552 else object[index] = value;
6553};
6554
6555
6556/***/ }),
6557/* 193 */
6558/***/ (function(module, exports, __webpack_require__) {
6559
6560module.exports = { "default": __webpack_require__(380), __esModule: true };
6561
6562/***/ }),
6563/* 194 */
6564/***/ (function(module, exports, __webpack_require__) {
6565
6566"use strict";
6567
6568var global = __webpack_require__(5);
6569var $export = __webpack_require__(4);
6570var meta = __webpack_require__(45);
6571var fails = __webpack_require__(28);
6572var hide = __webpack_require__(24);
6573var redefineAll = __webpack_require__(65);
6574var forOf = __webpack_require__(38);
6575var anInstance = __webpack_require__(64);
6576var isObject = __webpack_require__(9);
6577var setToStringTag = __webpack_require__(51);
6578var dP = __webpack_require__(20).f;
6579var each = __webpack_require__(114)(0);
6580var DESCRIPTORS = __webpack_require__(16);
6581
6582module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) {
6583 var Base = global[NAME];
6584 var C = Base;
6585 var ADDER = IS_MAP ? 'set' : 'add';
6586 var proto = C && C.prototype;
6587 var O = {};
6588 if (!DESCRIPTORS || typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () {
6589 new C().entries().next();
6590 }))) {
6591 // create collection constructor
6592 C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
6593 redefineAll(C.prototype, methods);
6594 meta.NEED = true;
6595 } else {
6596 C = wrapper(function (target, iterable) {
6597 anInstance(target, C, NAME, '_c');
6598 target._c = new Base();
6599 if (iterable != undefined) forOf(iterable, IS_MAP, target[ADDER], target);
6600 });
6601 each('add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON'.split(','), function (KEY) {
6602 var IS_ADDER = KEY == 'add' || KEY == 'set';
6603 if (KEY in proto && !(IS_WEAK && KEY == 'clear')) hide(C.prototype, KEY, function (a, b) {
6604 anInstance(this, C, KEY);
6605 if (!IS_ADDER && IS_WEAK && !isObject(a)) return KEY == 'get' ? undefined : false;
6606 var result = this._c[KEY](a === 0 ? 0 : a, b);
6607 return IS_ADDER ? this : result;
6608 });
6609 });
6610 IS_WEAK || dP(C.prototype, 'size', {
6611 get: function () {
6612 return this._c.size;
6613 }
6614 });
6615 }
6616
6617 setToStringTag(C, NAME);
6618
6619 O[NAME] = C;
6620 $export($export.G + $export.W + $export.F, O);
6621
6622 if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP);
6623
6624 return C;
6625};
6626
6627
6628/***/ }),
6629/* 195 */
6630/***/ (function(module, exports, __webpack_require__) {
6631
6632"use strict";
6633
6634// https://tc39.github.io/proposal-setmap-offrom/
6635var $export = __webpack_require__(4);
6636
6637module.exports = function (COLLECTION) {
6638 $export($export.S, COLLECTION, { of: function of() {
6639 var length = arguments.length;
6640 var A = new Array(length);
6641 while (length--) A[length] = arguments[length];
6642 return new this(A);
6643 } });
6644};
6645
6646
6647/***/ }),
6648/* 196 */
6649/***/ (function(module, exports, __webpack_require__) {
6650
6651"use strict";
6652
6653// https://tc39.github.io/proposal-setmap-offrom/
6654var $export = __webpack_require__(4);
6655var aFunction = __webpack_require__(47);
6656var ctx = __webpack_require__(22);
6657var forOf = __webpack_require__(38);
6658
6659module.exports = function (COLLECTION) {
6660 $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) {
6661 var mapFn = arguments[1];
6662 var mapping, A, n, cb;
6663 aFunction(this);
6664 mapping = mapFn !== undefined;
6665 if (mapping) aFunction(mapFn);
6666 if (source == undefined) return new this();
6667 A = [];
6668 if (mapping) {
6669 n = 0;
6670 cb = ctx(mapFn, arguments[2], 2);
6671 forOf(source, false, function (nextItem) {
6672 A.push(cb(nextItem, n++));
6673 });
6674 } else {
6675 forOf(source, false, A.push, A);
6676 }
6677 return new this(A);
6678 } });
6679};
6680
6681
6682/***/ }),
6683/* 197 */
6684/***/ (function(module, exports, __webpack_require__) {
6685
6686"use strict";
6687
6688// 19.1.2.1 Object.assign(target, source, ...)
6689var DESCRIPTORS = __webpack_require__(16);
6690var getKeys = __webpack_require__(49);
6691var gOPS = __webpack_require__(74);
6692var pIE = __webpack_require__(75);
6693var toObject = __webpack_require__(29);
6694var IObject = __webpack_require__(86);
6695var $assign = Object.assign;
6696
6697// should work with symbols and should have deterministic property order (V8 bug)
6698module.exports = !$assign || __webpack_require__(28)(function () {
6699 var A = {};
6700 var B = {};
6701 // eslint-disable-next-line no-undef
6702 var S = Symbol();
6703 var K = 'abcdefghijklmnopqrst';
6704 A[S] = 7;
6705 K.split('').forEach(function (k) { B[k] = k; });
6706 return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
6707}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
6708 var T = toObject(target);
6709 var aLen = arguments.length;
6710 var index = 1;
6711 var getSymbols = gOPS.f;
6712 var isEnum = pIE.f;
6713 while (aLen > index) {
6714 var S = IObject(arguments[index++]);
6715 var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
6716 var length = keys.length;
6717 var j = 0;
6718 var key;
6719 while (length > j) {
6720 key = keys[j++];
6721 if (!DESCRIPTORS || isEnum.call(S, key)) T[key] = S[key];
6722 }
6723 } return T;
6724} : $assign;
6725
6726
6727/***/ }),
6728/* 198 */
6729/***/ (function(module, exports, __webpack_require__) {
6730
6731module.exports = { "default": __webpack_require__(403), __esModule: true };
6732
6733/***/ }),
6734/* 199 */
6735/***/ (function(module, exports, __webpack_require__) {
6736
6737module.exports = { "default": __webpack_require__(404), __esModule: true };
6738
6739/***/ }),
6740/* 200 */
6741/***/ (function(module, exports) {
6742
6743function _arrayLikeToArray(arr, len) {
6744 if (len == null || len > arr.length) len = arr.length;
6745
6746 for (var i = 0, arr2 = new Array(len); i < len; i++) {
6747 arr2[i] = arr[i];
6748 }
6749
6750 return arr2;
6751}
6752
6753module.exports = _arrayLikeToArray;
6754
6755/***/ }),
6756/* 201 */
6757/***/ (function(module, exports) {
6758
6759function _iterableToArray(iter) {
6760 if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
6761}
6762
6763module.exports = _iterableToArray;
6764
6765/***/ }),
6766/* 202 */
6767/***/ (function(module, exports, __webpack_require__) {
6768
6769var arrayLikeToArray = __webpack_require__(200);
6770
6771function _unsupportedIterableToArray(o, minLen) {
6772 if (!o) return;
6773 if (typeof o === "string") return arrayLikeToArray(o, minLen);
6774 var n = Object.prototype.toString.call(o).slice(8, -1);
6775 if (n === "Object" && o.constructor) n = o.constructor.name;
6776 if (n === "Map" || n === "Set") return Array.from(o);
6777 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
6778}
6779
6780module.exports = _unsupportedIterableToArray;
6781
6782/***/ }),
6783/* 203 */
6784/***/ (function(module, exports, __webpack_require__) {
6785
6786var baseRandom = __webpack_require__(428);
6787
6788/**
6789 * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
6790 *
6791 * @private
6792 * @param {Array} array The array to shuffle.
6793 * @param {number} [size=array.length] The size of `array`.
6794 * @returns {Array} Returns `array`.
6795 */
6796function shuffleSelf(array, size) {
6797 var index = -1,
6798 length = array.length,
6799 lastIndex = length - 1;
6800
6801 size = size === undefined ? length : size;
6802 while (++index < size) {
6803 var rand = baseRandom(index, lastIndex),
6804 value = array[rand];
6805
6806 array[rand] = array[index];
6807 array[index] = value;
6808 }
6809 array.length = size;
6810 return array;
6811}
6812
6813module.exports = shuffleSelf;
6814
6815
6816/***/ }),
6817/* 204 */
6818/***/ (function(module, exports, __webpack_require__) {
6819
6820var baseValues = __webpack_require__(430),
6821 keys = __webpack_require__(432);
6822
6823/**
6824 * Creates an array of the own enumerable string keyed property values of `object`.
6825 *
6826 * **Note:** Non-object values are coerced to objects.
6827 *
6828 * @static
6829 * @since 0.1.0
6830 * @memberOf _
6831 * @category Object
6832 * @param {Object} object The object to query.
6833 * @returns {Array} Returns the array of property values.
6834 * @example
6835 *
6836 * function Foo() {
6837 * this.a = 1;
6838 * this.b = 2;
6839 * }
6840 *
6841 * Foo.prototype.c = 3;
6842 *
6843 * _.values(new Foo);
6844 * // => [1, 2] (iteration order is not guaranteed)
6845 *
6846 * _.values('hi');
6847 * // => ['h', 'i']
6848 */
6849function values(object) {
6850 return object == null ? [] : baseValues(object, keys(object));
6851}
6852
6853module.exports = values;
6854
6855
6856/***/ }),
6857/* 205 */
6858/***/ (function(module, exports, __webpack_require__) {
6859
6860var root = __webpack_require__(206);
6861
6862/** Built-in value references. */
6863var Symbol = root.Symbol;
6864
6865module.exports = Symbol;
6866
6867
6868/***/ }),
6869/* 206 */
6870/***/ (function(module, exports, __webpack_require__) {
6871
6872var freeGlobal = __webpack_require__(207);
6873
6874/** Detect free variable `self`. */
6875var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
6876
6877/** Used as a reference to the global object. */
6878var root = freeGlobal || freeSelf || Function('return this')();
6879
6880module.exports = root;
6881
6882
6883/***/ }),
6884/* 207 */
6885/***/ (function(module, exports, __webpack_require__) {
6886
6887/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */
6888var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
6889
6890module.exports = freeGlobal;
6891
6892/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(66)))
6893
6894/***/ }),
6895/* 208 */
6896/***/ (function(module, exports) {
6897
6898/**
6899 * Checks if `value` is classified as an `Array` object.
6900 *
6901 * @static
6902 * @memberOf _
6903 * @since 0.1.0
6904 * @category Lang
6905 * @param {*} value The value to check.
6906 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
6907 * @example
6908 *
6909 * _.isArray([1, 2, 3]);
6910 * // => true
6911 *
6912 * _.isArray(document.body.children);
6913 * // => false
6914 *
6915 * _.isArray('abc');
6916 * // => false
6917 *
6918 * _.isArray(_.noop);
6919 * // => false
6920 */
6921var isArray = Array.isArray;
6922
6923module.exports = isArray;
6924
6925
6926/***/ }),
6927/* 209 */
6928/***/ (function(module, exports) {
6929
6930module.exports = function(module) {
6931 if(!module.webpackPolyfill) {
6932 module.deprecate = function() {};
6933 module.paths = [];
6934 // module.parent = undefined by default
6935 if(!module.children) module.children = [];
6936 Object.defineProperty(module, "loaded", {
6937 enumerable: true,
6938 get: function() {
6939 return module.l;
6940 }
6941 });
6942 Object.defineProperty(module, "id", {
6943 enumerable: true,
6944 get: function() {
6945 return module.i;
6946 }
6947 });
6948 module.webpackPolyfill = 1;
6949 }
6950 return module;
6951};
6952
6953
6954/***/ }),
6955/* 210 */
6956/***/ (function(module, exports) {
6957
6958/** Used as references for various `Number` constants. */
6959var MAX_SAFE_INTEGER = 9007199254740991;
6960
6961/**
6962 * Checks if `value` is a valid array-like length.
6963 *
6964 * **Note:** This method is loosely based on
6965 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
6966 *
6967 * @static
6968 * @memberOf _
6969 * @since 4.0.0
6970 * @category Lang
6971 * @param {*} value The value to check.
6972 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
6973 * @example
6974 *
6975 * _.isLength(3);
6976 * // => true
6977 *
6978 * _.isLength(Number.MIN_VALUE);
6979 * // => false
6980 *
6981 * _.isLength(Infinity);
6982 * // => false
6983 *
6984 * _.isLength('3');
6985 * // => false
6986 */
6987function isLength(value) {
6988 return typeof value == 'number' &&
6989 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
6990}
6991
6992module.exports = isLength;
6993
6994
6995/***/ }),
6996/* 211 */
6997/***/ (function(module, exports) {
6998
6999/**
7000 * Creates a unary function that invokes `func` with its argument transformed.
7001 *
7002 * @private
7003 * @param {Function} func The function to wrap.
7004 * @param {Function} transform The argument transform.
7005 * @returns {Function} Returns the new function.
7006 */
7007function overArg(func, transform) {
7008 return function(arg) {
7009 return func(transform(arg));
7010 };
7011}
7012
7013module.exports = overArg;
7014
7015
7016/***/ }),
7017/* 212 */
7018/***/ (function(module, exports, __webpack_require__) {
7019
7020"use strict";
7021
7022
7023var AV = __webpack_require__(213);
7024var useLiveQuery = __webpack_require__(378);
7025var useAdatpers = __webpack_require__(189);
7026
7027module.exports = useAdatpers(useLiveQuery(AV));
7028
7029/***/ }),
7030/* 213 */
7031/***/ (function(module, exports, __webpack_require__) {
7032
7033"use strict";
7034
7035
7036var AV = __webpack_require__(214);
7037var useAdatpers = __webpack_require__(189);
7038
7039module.exports = useAdatpers(AV);
7040
7041/***/ }),
7042/* 214 */
7043/***/ (function(module, exports, __webpack_require__) {
7044
7045"use strict";
7046
7047
7048module.exports = __webpack_require__(215);
7049
7050/***/ }),
7051/* 215 */
7052/***/ (function(module, exports, __webpack_require__) {
7053
7054"use strict";
7055
7056
7057var _promise = __webpack_require__(3);
7058
7059var _promise2 = _interopRequireDefault(_promise);
7060
7061function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
7062
7063/*!
7064 * LeanCloud JavaScript SDK
7065 * https://leancloud.cn
7066 *
7067 * Copyright 2016 LeanCloud.cn, Inc.
7068 * The LeanCloud JavaScript SDK is freely distributable under the MIT license.
7069 */
7070var _ = __webpack_require__(0);
7071
7072var AV = __webpack_require__(42);
7073
7074AV._ = _;
7075AV.version = __webpack_require__(179);
7076AV.Promise = _promise2.default;
7077AV.localStorage = __webpack_require__(181);
7078AV.Cache = __webpack_require__(182);
7079AV.Error = __webpack_require__(34);
7080
7081__webpack_require__(310);
7082__webpack_require__(320)(AV);
7083__webpack_require__(321)(AV);
7084__webpack_require__(322)(AV);
7085__webpack_require__(323)(AV);
7086__webpack_require__(324)(AV);
7087__webpack_require__(325)(AV);
7088__webpack_require__(346)(AV);
7089__webpack_require__(352)(AV);
7090__webpack_require__(353)(AV);
7091__webpack_require__(355)(AV);
7092__webpack_require__(356)(AV);
7093__webpack_require__(357)(AV);
7094__webpack_require__(358)(AV);
7095__webpack_require__(359)(AV);
7096__webpack_require__(360)(AV);
7097__webpack_require__(361)(AV);
7098__webpack_require__(362)(AV);
7099__webpack_require__(363)(AV);
7100
7101AV.Conversation = __webpack_require__(364);
7102__webpack_require__(365);
7103module.exports = AV;
7104
7105/**
7106 * Options to controll the authentication for an operation
7107 * @typedef {Object} AuthOptions
7108 * @property {String} [sessionToken] Specify a user to excute the operation as.
7109 * @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.
7110 * @property {Boolean} [useMasterKey] Indicates whether masterKey is used for this operation. Only valid when masterKey is set.
7111 */
7112
7113/**
7114 * Options to controll the authentication for an SMS operation
7115 * @typedef {Object} SMSAuthOptions
7116 * @property {String} [sessionToken] Specify a user to excute the operation as.
7117 * @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.
7118 * @property {Boolean} [useMasterKey] Indicates whether masterKey is used for this operation. Only valid when masterKey is set.
7119 * @property {String} [validateToken] a validate token returned by {@link AV.Cloud.verifyCaptcha}
7120 */
7121
7122/***/ }),
7123/* 216 */
7124/***/ (function(module, exports, __webpack_require__) {
7125
7126__webpack_require__(59);
7127__webpack_require__(35);
7128__webpack_require__(37);
7129__webpack_require__(223);
7130__webpack_require__(227);
7131__webpack_require__(228);
7132module.exports = __webpack_require__(1).Promise;
7133
7134
7135/***/ }),
7136/* 217 */
7137/***/ (function(module, exports, __webpack_require__) {
7138
7139var toInteger = __webpack_require__(80);
7140var defined = __webpack_require__(81);
7141// true -> String#at
7142// false -> String#codePointAt
7143module.exports = function (TO_STRING) {
7144 return function (that, pos) {
7145 var s = String(defined(that));
7146 var i = toInteger(pos);
7147 var l = s.length;
7148 var a, b;
7149 if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
7150 a = s.charCodeAt(i);
7151 return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
7152 ? TO_STRING ? s.charAt(i) : a
7153 : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
7154 };
7155};
7156
7157
7158/***/ }),
7159/* 218 */
7160/***/ (function(module, exports, __webpack_require__) {
7161
7162"use strict";
7163
7164var create = __webpack_require__(60);
7165var descriptor = __webpack_require__(48);
7166var setToStringTag = __webpack_require__(51);
7167var IteratorPrototype = {};
7168
7169// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
7170__webpack_require__(24)(IteratorPrototype, __webpack_require__(8)('iterator'), function () { return this; });
7171
7172module.exports = function (Constructor, NAME, next) {
7173 Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });
7174 setToStringTag(Constructor, NAME + ' Iterator');
7175};
7176
7177
7178/***/ }),
7179/* 219 */
7180/***/ (function(module, exports, __webpack_require__) {
7181
7182// false -> Array#indexOf
7183// true -> Array#includes
7184var toIObject = __webpack_require__(26);
7185var toLength = __webpack_require__(61);
7186var toAbsoluteIndex = __webpack_require__(220);
7187module.exports = function (IS_INCLUDES) {
7188 return function ($this, el, fromIndex) {
7189 var O = toIObject($this);
7190 var length = toLength(O.length);
7191 var index = toAbsoluteIndex(fromIndex, length);
7192 var value;
7193 // Array#includes uses SameValueZero equality algorithm
7194 // eslint-disable-next-line no-self-compare
7195 if (IS_INCLUDES && el != el) while (length > index) {
7196 value = O[index++];
7197 // eslint-disable-next-line no-self-compare
7198 if (value != value) return true;
7199 // Array#indexOf ignores holes, Array#includes - not
7200 } else for (;length > index; index++) if (IS_INCLUDES || index in O) {
7201 if (O[index] === el) return IS_INCLUDES || index || 0;
7202 } return !IS_INCLUDES && -1;
7203 };
7204};
7205
7206
7207/***/ }),
7208/* 220 */
7209/***/ (function(module, exports, __webpack_require__) {
7210
7211var toInteger = __webpack_require__(80);
7212var max = Math.max;
7213var min = Math.min;
7214module.exports = function (index, length) {
7215 index = toInteger(index);
7216 return index < 0 ? max(index + length, 0) : min(index, length);
7217};
7218
7219
7220/***/ }),
7221/* 221 */
7222/***/ (function(module, exports, __webpack_require__) {
7223
7224"use strict";
7225
7226var addToUnscopables = __webpack_require__(222);
7227var step = __webpack_require__(120);
7228var Iterators = __webpack_require__(36);
7229var toIObject = __webpack_require__(26);
7230
7231// 22.1.3.4 Array.prototype.entries()
7232// 22.1.3.13 Array.prototype.keys()
7233// 22.1.3.29 Array.prototype.values()
7234// 22.1.3.30 Array.prototype[@@iterator]()
7235module.exports = __webpack_require__(82)(Array, 'Array', function (iterated, kind) {
7236 this._t = toIObject(iterated); // target
7237 this._i = 0; // next index
7238 this._k = kind; // kind
7239// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
7240}, function () {
7241 var O = this._t;
7242 var kind = this._k;
7243 var index = this._i++;
7244 if (!O || index >= O.length) {
7245 this._t = undefined;
7246 return step(1);
7247 }
7248 if (kind == 'keys') return step(0, index);
7249 if (kind == 'values') return step(0, O[index]);
7250 return step(0, [index, O[index]]);
7251}, 'values');
7252
7253// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
7254Iterators.Arguments = Iterators.Array;
7255
7256addToUnscopables('keys');
7257addToUnscopables('values');
7258addToUnscopables('entries');
7259
7260
7261/***/ }),
7262/* 222 */
7263/***/ (function(module, exports) {
7264
7265module.exports = function () { /* empty */ };
7266
7267
7268/***/ }),
7269/* 223 */
7270/***/ (function(module, exports, __webpack_require__) {
7271
7272"use strict";
7273
7274var LIBRARY = __webpack_require__(46);
7275var global = __webpack_require__(5);
7276var ctx = __webpack_require__(22);
7277var classof = __webpack_require__(63);
7278var $export = __webpack_require__(4);
7279var isObject = __webpack_require__(9);
7280var aFunction = __webpack_require__(47);
7281var anInstance = __webpack_require__(64);
7282var forOf = __webpack_require__(38);
7283var speciesConstructor = __webpack_require__(123);
7284var task = __webpack_require__(124).set;
7285var microtask = __webpack_require__(225)();
7286var newPromiseCapabilityModule = __webpack_require__(91);
7287var perform = __webpack_require__(125);
7288var userAgent = __webpack_require__(226);
7289var promiseResolve = __webpack_require__(126);
7290var PROMISE = 'Promise';
7291var TypeError = global.TypeError;
7292var process = global.process;
7293var versions = process && process.versions;
7294var v8 = versions && versions.v8 || '';
7295var $Promise = global[PROMISE];
7296var isNode = classof(process) == 'process';
7297var empty = function () { /* empty */ };
7298var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
7299var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;
7300
7301var USE_NATIVE = !!function () {
7302 try {
7303 // correct subclassing with @@species support
7304 var promise = $Promise.resolve(1);
7305 var FakePromise = (promise.constructor = {})[__webpack_require__(8)('species')] = function (exec) {
7306 exec(empty, empty);
7307 };
7308 // unhandled rejections tracking support, NodeJS Promise without it fails @@species test
7309 return (isNode || typeof PromiseRejectionEvent == 'function')
7310 && promise.then(empty) instanceof FakePromise
7311 // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
7312 // https://bugs.chromium.org/p/chromium/issues/detail?id=830565
7313 // we can't detect it synchronously, so just check versions
7314 && v8.indexOf('6.6') !== 0
7315 && userAgent.indexOf('Chrome/66') === -1;
7316 } catch (e) { /* empty */ }
7317}();
7318
7319// helpers
7320var isThenable = function (it) {
7321 var then;
7322 return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
7323};
7324var notify = function (promise, isReject) {
7325 if (promise._n) return;
7326 promise._n = true;
7327 var chain = promise._c;
7328 microtask(function () {
7329 var value = promise._v;
7330 var ok = promise._s == 1;
7331 var i = 0;
7332 var run = function (reaction) {
7333 var handler = ok ? reaction.ok : reaction.fail;
7334 var resolve = reaction.resolve;
7335 var reject = reaction.reject;
7336 var domain = reaction.domain;
7337 var result, then, exited;
7338 try {
7339 if (handler) {
7340 if (!ok) {
7341 if (promise._h == 2) onHandleUnhandled(promise);
7342 promise._h = 1;
7343 }
7344 if (handler === true) result = value;
7345 else {
7346 if (domain) domain.enter();
7347 result = handler(value); // may throw
7348 if (domain) {
7349 domain.exit();
7350 exited = true;
7351 }
7352 }
7353 if (result === reaction.promise) {
7354 reject(TypeError('Promise-chain cycle'));
7355 } else if (then = isThenable(result)) {
7356 then.call(result, resolve, reject);
7357 } else resolve(result);
7358 } else reject(value);
7359 } catch (e) {
7360 if (domain && !exited) domain.exit();
7361 reject(e);
7362 }
7363 };
7364 while (chain.length > i) run(chain[i++]); // variable length - can't use forEach
7365 promise._c = [];
7366 promise._n = false;
7367 if (isReject && !promise._h) onUnhandled(promise);
7368 });
7369};
7370var onUnhandled = function (promise) {
7371 task.call(global, function () {
7372 var value = promise._v;
7373 var unhandled = isUnhandled(promise);
7374 var result, handler, console;
7375 if (unhandled) {
7376 result = perform(function () {
7377 if (isNode) {
7378 process.emit('unhandledRejection', value, promise);
7379 } else if (handler = global.onunhandledrejection) {
7380 handler({ promise: promise, reason: value });
7381 } else if ((console = global.console) && console.error) {
7382 console.error('Unhandled promise rejection', value);
7383 }
7384 });
7385 // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
7386 promise._h = isNode || isUnhandled(promise) ? 2 : 1;
7387 } promise._a = undefined;
7388 if (unhandled && result.e) throw result.v;
7389 });
7390};
7391var isUnhandled = function (promise) {
7392 return promise._h !== 1 && (promise._a || promise._c).length === 0;
7393};
7394var onHandleUnhandled = function (promise) {
7395 task.call(global, function () {
7396 var handler;
7397 if (isNode) {
7398 process.emit('rejectionHandled', promise);
7399 } else if (handler = global.onrejectionhandled) {
7400 handler({ promise: promise, reason: promise._v });
7401 }
7402 });
7403};
7404var $reject = function (value) {
7405 var promise = this;
7406 if (promise._d) return;
7407 promise._d = true;
7408 promise = promise._w || promise; // unwrap
7409 promise._v = value;
7410 promise._s = 2;
7411 if (!promise._a) promise._a = promise._c.slice();
7412 notify(promise, true);
7413};
7414var $resolve = function (value) {
7415 var promise = this;
7416 var then;
7417 if (promise._d) return;
7418 promise._d = true;
7419 promise = promise._w || promise; // unwrap
7420 try {
7421 if (promise === value) throw TypeError("Promise can't be resolved itself");
7422 if (then = isThenable(value)) {
7423 microtask(function () {
7424 var wrapper = { _w: promise, _d: false }; // wrap
7425 try {
7426 then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
7427 } catch (e) {
7428 $reject.call(wrapper, e);
7429 }
7430 });
7431 } else {
7432 promise._v = value;
7433 promise._s = 1;
7434 notify(promise, false);
7435 }
7436 } catch (e) {
7437 $reject.call({ _w: promise, _d: false }, e); // wrap
7438 }
7439};
7440
7441// constructor polyfill
7442if (!USE_NATIVE) {
7443 // 25.4.3.1 Promise(executor)
7444 $Promise = function Promise(executor) {
7445 anInstance(this, $Promise, PROMISE, '_h');
7446 aFunction(executor);
7447 Internal.call(this);
7448 try {
7449 executor(ctx($resolve, this, 1), ctx($reject, this, 1));
7450 } catch (err) {
7451 $reject.call(this, err);
7452 }
7453 };
7454 // eslint-disable-next-line no-unused-vars
7455 Internal = function Promise(executor) {
7456 this._c = []; // <- awaiting reactions
7457 this._a = undefined; // <- checked in isUnhandled reactions
7458 this._s = 0; // <- state
7459 this._d = false; // <- done
7460 this._v = undefined; // <- value
7461 this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
7462 this._n = false; // <- notify
7463 };
7464 Internal.prototype = __webpack_require__(65)($Promise.prototype, {
7465 // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
7466 then: function then(onFulfilled, onRejected) {
7467 var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
7468 reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
7469 reaction.fail = typeof onRejected == 'function' && onRejected;
7470 reaction.domain = isNode ? process.domain : undefined;
7471 this._c.push(reaction);
7472 if (this._a) this._a.push(reaction);
7473 if (this._s) notify(this, false);
7474 return reaction.promise;
7475 },
7476 // 25.4.5.1 Promise.prototype.catch(onRejected)
7477 'catch': function (onRejected) {
7478 return this.then(undefined, onRejected);
7479 }
7480 });
7481 OwnPromiseCapability = function () {
7482 var promise = new Internal();
7483 this.promise = promise;
7484 this.resolve = ctx($resolve, promise, 1);
7485 this.reject = ctx($reject, promise, 1);
7486 };
7487 newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
7488 return C === $Promise || C === Wrapper
7489 ? new OwnPromiseCapability(C)
7490 : newGenericPromiseCapability(C);
7491 };
7492}
7493
7494$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise });
7495__webpack_require__(51)($Promise, PROMISE);
7496__webpack_require__(127)(PROMISE);
7497Wrapper = __webpack_require__(1)[PROMISE];
7498
7499// statics
7500$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
7501 // 25.4.4.5 Promise.reject(r)
7502 reject: function reject(r) {
7503 var capability = newPromiseCapability(this);
7504 var $$reject = capability.reject;
7505 $$reject(r);
7506 return capability.promise;
7507 }
7508});
7509$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
7510 // 25.4.4.6 Promise.resolve(x)
7511 resolve: function resolve(x) {
7512 return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);
7513 }
7514});
7515$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(128)(function (iter) {
7516 $Promise.all(iter)['catch'](empty);
7517})), PROMISE, {
7518 // 25.4.4.1 Promise.all(iterable)
7519 all: function all(iterable) {
7520 var C = this;
7521 var capability = newPromiseCapability(C);
7522 var resolve = capability.resolve;
7523 var reject = capability.reject;
7524 var result = perform(function () {
7525 var values = [];
7526 var index = 0;
7527 var remaining = 1;
7528 forOf(iterable, false, function (promise) {
7529 var $index = index++;
7530 var alreadyCalled = false;
7531 values.push(undefined);
7532 remaining++;
7533 C.resolve(promise).then(function (value) {
7534 if (alreadyCalled) return;
7535 alreadyCalled = true;
7536 values[$index] = value;
7537 --remaining || resolve(values);
7538 }, reject);
7539 });
7540 --remaining || resolve(values);
7541 });
7542 if (result.e) reject(result.v);
7543 return capability.promise;
7544 },
7545 // 25.4.4.4 Promise.race(iterable)
7546 race: function race(iterable) {
7547 var C = this;
7548 var capability = newPromiseCapability(C);
7549 var reject = capability.reject;
7550 var result = perform(function () {
7551 forOf(iterable, false, function (promise) {
7552 C.resolve(promise).then(capability.resolve, reject);
7553 });
7554 });
7555 if (result.e) reject(result.v);
7556 return capability.promise;
7557 }
7558});
7559
7560
7561/***/ }),
7562/* 224 */
7563/***/ (function(module, exports) {
7564
7565// fast apply, http://jsperf.lnkit.com/fast-apply/5
7566module.exports = function (fn, args, that) {
7567 var un = that === undefined;
7568 switch (args.length) {
7569 case 0: return un ? fn()
7570 : fn.call(that);
7571 case 1: return un ? fn(args[0])
7572 : fn.call(that, args[0]);
7573 case 2: return un ? fn(args[0], args[1])
7574 : fn.call(that, args[0], args[1]);
7575 case 3: return un ? fn(args[0], args[1], args[2])
7576 : fn.call(that, args[0], args[1], args[2]);
7577 case 4: return un ? fn(args[0], args[1], args[2], args[3])
7578 : fn.call(that, args[0], args[1], args[2], args[3]);
7579 } return fn.apply(that, args);
7580};
7581
7582
7583/***/ }),
7584/* 225 */
7585/***/ (function(module, exports, __webpack_require__) {
7586
7587var global = __webpack_require__(5);
7588var macrotask = __webpack_require__(124).set;
7589var Observer = global.MutationObserver || global.WebKitMutationObserver;
7590var process = global.process;
7591var Promise = global.Promise;
7592var isNode = __webpack_require__(50)(process) == 'process';
7593
7594module.exports = function () {
7595 var head, last, notify;
7596
7597 var flush = function () {
7598 var parent, fn;
7599 if (isNode && (parent = process.domain)) parent.exit();
7600 while (head) {
7601 fn = head.fn;
7602 head = head.next;
7603 try {
7604 fn();
7605 } catch (e) {
7606 if (head) notify();
7607 else last = undefined;
7608 throw e;
7609 }
7610 } last = undefined;
7611 if (parent) parent.enter();
7612 };
7613
7614 // Node.js
7615 if (isNode) {
7616 notify = function () {
7617 process.nextTick(flush);
7618 };
7619 // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339
7620 } else if (Observer && !(global.navigator && global.navigator.standalone)) {
7621 var toggle = true;
7622 var node = document.createTextNode('');
7623 new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new
7624 notify = function () {
7625 node.data = toggle = !toggle;
7626 };
7627 // environments with maybe non-completely correct, but existent Promise
7628 } else if (Promise && Promise.resolve) {
7629 // Promise.resolve without an argument throws an error in LG WebOS 2
7630 var promise = Promise.resolve(undefined);
7631 notify = function () {
7632 promise.then(flush);
7633 };
7634 // for other environments - macrotask based on:
7635 // - setImmediate
7636 // - MessageChannel
7637 // - window.postMessag
7638 // - onreadystatechange
7639 // - setTimeout
7640 } else {
7641 notify = function () {
7642 // strange IE + webpack dev server bug - use .call(global)
7643 macrotask.call(global, flush);
7644 };
7645 }
7646
7647 return function (fn) {
7648 var task = { fn: fn, next: undefined };
7649 if (last) last.next = task;
7650 if (!head) {
7651 head = task;
7652 notify();
7653 } last = task;
7654 };
7655};
7656
7657
7658/***/ }),
7659/* 226 */
7660/***/ (function(module, exports, __webpack_require__) {
7661
7662var global = __webpack_require__(5);
7663var navigator = global.navigator;
7664
7665module.exports = navigator && navigator.userAgent || '';
7666
7667
7668/***/ }),
7669/* 227 */
7670/***/ (function(module, exports, __webpack_require__) {
7671
7672"use strict";
7673// https://github.com/tc39/proposal-promise-finally
7674
7675var $export = __webpack_require__(4);
7676var core = __webpack_require__(1);
7677var global = __webpack_require__(5);
7678var speciesConstructor = __webpack_require__(123);
7679var promiseResolve = __webpack_require__(126);
7680
7681$export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) {
7682 var C = speciesConstructor(this, core.Promise || global.Promise);
7683 var isFunction = typeof onFinally == 'function';
7684 return this.then(
7685 isFunction ? function (x) {
7686 return promiseResolve(C, onFinally()).then(function () { return x; });
7687 } : onFinally,
7688 isFunction ? function (e) {
7689 return promiseResolve(C, onFinally()).then(function () { throw e; });
7690 } : onFinally
7691 );
7692} });
7693
7694
7695/***/ }),
7696/* 228 */
7697/***/ (function(module, exports, __webpack_require__) {
7698
7699"use strict";
7700
7701// https://github.com/tc39/proposal-promise-try
7702var $export = __webpack_require__(4);
7703var newPromiseCapability = __webpack_require__(91);
7704var perform = __webpack_require__(125);
7705
7706$export($export.S, 'Promise', { 'try': function (callbackfn) {
7707 var promiseCapability = newPromiseCapability.f(this);
7708 var result = perform(callbackfn);
7709 (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v);
7710 return promiseCapability.promise;
7711} });
7712
7713
7714/***/ }),
7715/* 229 */
7716/***/ (function(module, __webpack_exports__, __webpack_require__) {
7717
7718"use strict";
7719/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__index_js__ = __webpack_require__(92);
7720// Default Export
7721// ==============
7722// In this module, we mix our bundled exports into the `_` object and export
7723// the result. This is analogous to setting `module.exports = _` in CommonJS.
7724// Hence, this module is also the entry point of our UMD bundle and the package
7725// entry point for CommonJS and AMD users. In other words, this is (the source
7726// of) the module you are interfacing with when you do any of the following:
7727//
7728// ```js
7729// // CommonJS
7730// var _ = require('underscore');
7731//
7732// // AMD
7733// define(['underscore'], function(_) {...});
7734//
7735// // UMD in the browser
7736// // _ is available as a global variable
7737// ```
7738
7739
7740
7741// Add all of the Underscore functions to the wrapper object.
7742var _ = Object(__WEBPACK_IMPORTED_MODULE_0__index_js__["mixin"])(__WEBPACK_IMPORTED_MODULE_0__index_js__);
7743// Legacy Node.js API.
7744_._ = _;
7745// Export the Underscore API.
7746/* harmony default export */ __webpack_exports__["a"] = (_);
7747
7748
7749/***/ }),
7750/* 230 */
7751/***/ (function(module, __webpack_exports__, __webpack_require__) {
7752
7753"use strict";
7754/* harmony export (immutable) */ __webpack_exports__["a"] = isNull;
7755// Is a given value equal to null?
7756function isNull(obj) {
7757 return obj === null;
7758}
7759
7760
7761/***/ }),
7762/* 231 */
7763/***/ (function(module, __webpack_exports__, __webpack_require__) {
7764
7765"use strict";
7766/* harmony export (immutable) */ __webpack_exports__["a"] = isElement;
7767// Is a given value a DOM element?
7768function isElement(obj) {
7769 return !!(obj && obj.nodeType === 1);
7770}
7771
7772
7773/***/ }),
7774/* 232 */
7775/***/ (function(module, __webpack_exports__, __webpack_require__) {
7776
7777"use strict";
7778/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
7779
7780
7781/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Date'));
7782
7783
7784/***/ }),
7785/* 233 */
7786/***/ (function(module, __webpack_exports__, __webpack_require__) {
7787
7788"use strict";
7789/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
7790
7791
7792/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('RegExp'));
7793
7794
7795/***/ }),
7796/* 234 */
7797/***/ (function(module, __webpack_exports__, __webpack_require__) {
7798
7799"use strict";
7800/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
7801
7802
7803/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Error'));
7804
7805
7806/***/ }),
7807/* 235 */
7808/***/ (function(module, __webpack_exports__, __webpack_require__) {
7809
7810"use strict";
7811/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
7812
7813
7814/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Object'));
7815
7816
7817/***/ }),
7818/* 236 */
7819/***/ (function(module, __webpack_exports__, __webpack_require__) {
7820
7821"use strict";
7822/* harmony export (immutable) */ __webpack_exports__["a"] = isFinite;
7823/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
7824/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isSymbol_js__ = __webpack_require__(132);
7825
7826
7827
7828// Is a given object a finite number?
7829function isFinite(obj) {
7830 return !Object(__WEBPACK_IMPORTED_MODULE_1__isSymbol_js__["a" /* default */])(obj) && Object(__WEBPACK_IMPORTED_MODULE_0__setup_js__["f" /* _isFinite */])(obj) && !isNaN(parseFloat(obj));
7831}
7832
7833
7834/***/ }),
7835/* 237 */
7836/***/ (function(module, __webpack_exports__, __webpack_require__) {
7837
7838"use strict";
7839/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createSizePropertyCheck_js__ = __webpack_require__(137);
7840/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__getByteLength_js__ = __webpack_require__(96);
7841
7842
7843
7844// Internal helper to determine whether we should spend extensive checks against
7845// `ArrayBuffer` et al.
7846/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createSizePropertyCheck_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__getByteLength_js__["a" /* default */]));
7847
7848
7849/***/ }),
7850/* 238 */
7851/***/ (function(module, __webpack_exports__, __webpack_require__) {
7852
7853"use strict";
7854/* harmony export (immutable) */ __webpack_exports__["a"] = isEmpty;
7855/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__getLength_js__ = __webpack_require__(18);
7856/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArray_js__ = __webpack_require__(31);
7857/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isString_js__ = __webpack_require__(93);
7858/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isArguments_js__ = __webpack_require__(95);
7859/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__keys_js__ = __webpack_require__(6);
7860
7861
7862
7863
7864
7865
7866// Is a given array, string, or object empty?
7867// An "empty" object has no enumerable own-properties.
7868function isEmpty(obj) {
7869 if (obj == null) return true;
7870 // Skip the more expensive `toString`-based type checks if `obj` has no
7871 // `.length`.
7872 var length = Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(obj);
7873 if (typeof length == 'number' && (
7874 Object(__WEBPACK_IMPORTED_MODULE_1__isArray_js__["a" /* default */])(obj) || Object(__WEBPACK_IMPORTED_MODULE_2__isString_js__["a" /* default */])(obj) || Object(__WEBPACK_IMPORTED_MODULE_3__isArguments_js__["a" /* default */])(obj)
7875 )) return length === 0;
7876 return Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(Object(__WEBPACK_IMPORTED_MODULE_4__keys_js__["a" /* default */])(obj)) === 0;
7877}
7878
7879
7880/***/ }),
7881/* 239 */
7882/***/ (function(module, __webpack_exports__, __webpack_require__) {
7883
7884"use strict";
7885/* harmony export (immutable) */ __webpack_exports__["a"] = isEqual;
7886/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(12);
7887/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__setup_js__ = __webpack_require__(2);
7888/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__getByteLength_js__ = __webpack_require__(96);
7889/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isTypedArray_js__ = __webpack_require__(135);
7890/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__isFunction_js__ = __webpack_require__(17);
7891/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__stringTagBug_js__ = __webpack_require__(52);
7892/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__isDataView_js__ = __webpack_require__(94);
7893/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__keys_js__ = __webpack_require__(6);
7894/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__has_js__ = __webpack_require__(27);
7895/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__toBufferView_js__ = __webpack_require__(240);
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907// We use this string twice, so give it a name for minification.
7908var tagDataView = '[object DataView]';
7909
7910// Internal recursive comparison function for `_.isEqual`.
7911function eq(a, b, aStack, bStack) {
7912 // Identical objects are equal. `0 === -0`, but they aren't identical.
7913 // See the [Harmony `egal` proposal](https://wiki.ecmascript.org/doku.php?id=harmony:egal).
7914 if (a === b) return a !== 0 || 1 / a === 1 / b;
7915 // `null` or `undefined` only equal to itself (strict comparison).
7916 if (a == null || b == null) return false;
7917 // `NaN`s are equivalent, but non-reflexive.
7918 if (a !== a) return b !== b;
7919 // Exhaust primitive checks
7920 var type = typeof a;
7921 if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
7922 return deepEq(a, b, aStack, bStack);
7923}
7924
7925// Internal recursive comparison function for `_.isEqual`.
7926function deepEq(a, b, aStack, bStack) {
7927 // Unwrap any wrapped objects.
7928 if (a instanceof __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */]) a = a._wrapped;
7929 if (b instanceof __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */]) b = b._wrapped;
7930 // Compare `[[Class]]` names.
7931 var className = __WEBPACK_IMPORTED_MODULE_1__setup_js__["t" /* toString */].call(a);
7932 if (className !== __WEBPACK_IMPORTED_MODULE_1__setup_js__["t" /* toString */].call(b)) return false;
7933 // Work around a bug in IE 10 - Edge 13.
7934 if (__WEBPACK_IMPORTED_MODULE_5__stringTagBug_js__["a" /* hasStringTagBug */] && className == '[object Object]' && Object(__WEBPACK_IMPORTED_MODULE_6__isDataView_js__["a" /* default */])(a)) {
7935 if (!Object(__WEBPACK_IMPORTED_MODULE_6__isDataView_js__["a" /* default */])(b)) return false;
7936 className = tagDataView;
7937 }
7938 switch (className) {
7939 // These types are compared by value.
7940 case '[object RegExp]':
7941 // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
7942 case '[object String]':
7943 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
7944 // equivalent to `new String("5")`.
7945 return '' + a === '' + b;
7946 case '[object Number]':
7947 // `NaN`s are equivalent, but non-reflexive.
7948 // Object(NaN) is equivalent to NaN.
7949 if (+a !== +a) return +b !== +b;
7950 // An `egal` comparison is performed for other numeric values.
7951 return +a === 0 ? 1 / +a === 1 / b : +a === +b;
7952 case '[object Date]':
7953 case '[object Boolean]':
7954 // Coerce dates and booleans to numeric primitive values. Dates are compared by their
7955 // millisecond representations. Note that invalid dates with millisecond representations
7956 // of `NaN` are not equivalent.
7957 return +a === +b;
7958 case '[object Symbol]':
7959 return __WEBPACK_IMPORTED_MODULE_1__setup_js__["d" /* SymbolProto */].valueOf.call(a) === __WEBPACK_IMPORTED_MODULE_1__setup_js__["d" /* SymbolProto */].valueOf.call(b);
7960 case '[object ArrayBuffer]':
7961 case tagDataView:
7962 // Coerce to typed array so we can fall through.
7963 return deepEq(Object(__WEBPACK_IMPORTED_MODULE_9__toBufferView_js__["a" /* default */])(a), Object(__WEBPACK_IMPORTED_MODULE_9__toBufferView_js__["a" /* default */])(b), aStack, bStack);
7964 }
7965
7966 var areArrays = className === '[object Array]';
7967 if (!areArrays && Object(__WEBPACK_IMPORTED_MODULE_3__isTypedArray_js__["a" /* default */])(a)) {
7968 var byteLength = Object(__WEBPACK_IMPORTED_MODULE_2__getByteLength_js__["a" /* default */])(a);
7969 if (byteLength !== Object(__WEBPACK_IMPORTED_MODULE_2__getByteLength_js__["a" /* default */])(b)) return false;
7970 if (a.buffer === b.buffer && a.byteOffset === b.byteOffset) return true;
7971 areArrays = true;
7972 }
7973 if (!areArrays) {
7974 if (typeof a != 'object' || typeof b != 'object') return false;
7975
7976 // Objects with different constructors are not equivalent, but `Object`s or `Array`s
7977 // from different frames are.
7978 var aCtor = a.constructor, bCtor = b.constructor;
7979 if (aCtor !== bCtor && !(Object(__WEBPACK_IMPORTED_MODULE_4__isFunction_js__["a" /* default */])(aCtor) && aCtor instanceof aCtor &&
7980 Object(__WEBPACK_IMPORTED_MODULE_4__isFunction_js__["a" /* default */])(bCtor) && bCtor instanceof bCtor)
7981 && ('constructor' in a && 'constructor' in b)) {
7982 return false;
7983 }
7984 }
7985 // Assume equality for cyclic structures. The algorithm for detecting cyclic
7986 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
7987
7988 // Initializing stack of traversed objects.
7989 // It's done here since we only need them for objects and arrays comparison.
7990 aStack = aStack || [];
7991 bStack = bStack || [];
7992 var length = aStack.length;
7993 while (length--) {
7994 // Linear search. Performance is inversely proportional to the number of
7995 // unique nested structures.
7996 if (aStack[length] === a) return bStack[length] === b;
7997 }
7998
7999 // Add the first object to the stack of traversed objects.
8000 aStack.push(a);
8001 bStack.push(b);
8002
8003 // Recursively compare objects and arrays.
8004 if (areArrays) {
8005 // Compare array lengths to determine if a deep comparison is necessary.
8006 length = a.length;
8007 if (length !== b.length) return false;
8008 // Deep compare the contents, ignoring non-numeric properties.
8009 while (length--) {
8010 if (!eq(a[length], b[length], aStack, bStack)) return false;
8011 }
8012 } else {
8013 // Deep compare objects.
8014 var _keys = Object(__WEBPACK_IMPORTED_MODULE_7__keys_js__["a" /* default */])(a), key;
8015 length = _keys.length;
8016 // Ensure that both objects contain the same number of properties before comparing deep equality.
8017 if (Object(__WEBPACK_IMPORTED_MODULE_7__keys_js__["a" /* default */])(b).length !== length) return false;
8018 while (length--) {
8019 // Deep compare each member
8020 key = _keys[length];
8021 if (!(Object(__WEBPACK_IMPORTED_MODULE_8__has_js__["a" /* default */])(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
8022 }
8023 }
8024 // Remove the first object from the stack of traversed objects.
8025 aStack.pop();
8026 bStack.pop();
8027 return true;
8028}
8029
8030// Perform a deep comparison to check if two objects are equal.
8031function isEqual(a, b) {
8032 return eq(a, b);
8033}
8034
8035
8036/***/ }),
8037/* 240 */
8038/***/ (function(module, __webpack_exports__, __webpack_require__) {
8039
8040"use strict";
8041/* harmony export (immutable) */ __webpack_exports__["a"] = toBufferView;
8042/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__getByteLength_js__ = __webpack_require__(96);
8043
8044
8045// Internal function to wrap or shallow-copy an ArrayBuffer,
8046// typed array or DataView to a new view, reusing the buffer.
8047function toBufferView(bufferSource) {
8048 return new Uint8Array(
8049 bufferSource.buffer || bufferSource,
8050 bufferSource.byteOffset || 0,
8051 Object(__WEBPACK_IMPORTED_MODULE_0__getByteLength_js__["a" /* default */])(bufferSource)
8052 );
8053}
8054
8055
8056/***/ }),
8057/* 241 */
8058/***/ (function(module, __webpack_exports__, __webpack_require__) {
8059
8060"use strict";
8061/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
8062/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__stringTagBug_js__ = __webpack_require__(52);
8063/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__ = __webpack_require__(97);
8064
8065
8066
8067
8068/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_1__stringTagBug_js__["b" /* isIE11 */] ? Object(__WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__["a" /* ie11fingerprint */])(__WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__["b" /* mapMethods */]) : Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Map'));
8069
8070
8071/***/ }),
8072/* 242 */
8073/***/ (function(module, __webpack_exports__, __webpack_require__) {
8074
8075"use strict";
8076/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
8077/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__stringTagBug_js__ = __webpack_require__(52);
8078/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__ = __webpack_require__(97);
8079
8080
8081
8082
8083/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_1__stringTagBug_js__["b" /* isIE11 */] ? Object(__WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__["a" /* ie11fingerprint */])(__WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__["d" /* weakMapMethods */]) : Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('WeakMap'));
8084
8085
8086/***/ }),
8087/* 243 */
8088/***/ (function(module, __webpack_exports__, __webpack_require__) {
8089
8090"use strict";
8091/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
8092/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__stringTagBug_js__ = __webpack_require__(52);
8093/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__ = __webpack_require__(97);
8094
8095
8096
8097
8098/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_1__stringTagBug_js__["b" /* isIE11 */] ? Object(__WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__["a" /* ie11fingerprint */])(__WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__["c" /* setMethods */]) : Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Set'));
8099
8100
8101/***/ }),
8102/* 244 */
8103/***/ (function(module, __webpack_exports__, __webpack_require__) {
8104
8105"use strict";
8106/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(7);
8107
8108
8109/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('WeakSet'));
8110
8111
8112/***/ }),
8113/* 245 */
8114/***/ (function(module, __webpack_exports__, __webpack_require__) {
8115
8116"use strict";
8117/* harmony export (immutable) */ __webpack_exports__["a"] = pairs;
8118/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__keys_js__ = __webpack_require__(6);
8119
8120
8121// Convert an object into a list of `[key, value]` pairs.
8122// The opposite of `_.object` with one argument.
8123function pairs(obj) {
8124 var _keys = Object(__WEBPACK_IMPORTED_MODULE_0__keys_js__["a" /* default */])(obj);
8125 var length = _keys.length;
8126 var pairs = Array(length);
8127 for (var i = 0; i < length; i++) {
8128 pairs[i] = [_keys[i], obj[_keys[i]]];
8129 }
8130 return pairs;
8131}
8132
8133
8134/***/ }),
8135/* 246 */
8136/***/ (function(module, __webpack_exports__, __webpack_require__) {
8137
8138"use strict";
8139/* harmony export (immutable) */ __webpack_exports__["a"] = create;
8140/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__baseCreate_js__ = __webpack_require__(145);
8141/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__extendOwn_js__ = __webpack_require__(99);
8142
8143
8144
8145// Creates an object that inherits from the given prototype object.
8146// If additional properties are provided then they will be added to the
8147// created object.
8148function create(prototype, props) {
8149 var result = Object(__WEBPACK_IMPORTED_MODULE_0__baseCreate_js__["a" /* default */])(prototype);
8150 if (props) Object(__WEBPACK_IMPORTED_MODULE_1__extendOwn_js__["a" /* default */])(result, props);
8151 return result;
8152}
8153
8154
8155/***/ }),
8156/* 247 */
8157/***/ (function(module, __webpack_exports__, __webpack_require__) {
8158
8159"use strict";
8160/* harmony export (immutable) */ __webpack_exports__["a"] = tap;
8161// Invokes `interceptor` with the `obj` and then returns `obj`.
8162// The primary purpose of this method is to "tap into" a method chain, in
8163// order to perform operations on intermediate results within the chain.
8164function tap(obj, interceptor) {
8165 interceptor(obj);
8166 return obj;
8167}
8168
8169
8170/***/ }),
8171/* 248 */
8172/***/ (function(module, __webpack_exports__, __webpack_require__) {
8173
8174"use strict";
8175/* harmony export (immutable) */ __webpack_exports__["a"] = has;
8176/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__has_js__ = __webpack_require__(27);
8177/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__toPath_js__ = __webpack_require__(54);
8178
8179
8180
8181// Shortcut function for checking if an object has a given property directly on
8182// itself (in other words, not on a prototype). Unlike the internal `has`
8183// function, this public version can also traverse nested properties.
8184function has(obj, path) {
8185 path = Object(__WEBPACK_IMPORTED_MODULE_1__toPath_js__["a" /* default */])(path);
8186 var length = path.length;
8187 for (var i = 0; i < length; i++) {
8188 var key = path[i];
8189 if (!Object(__WEBPACK_IMPORTED_MODULE_0__has_js__["a" /* default */])(obj, key)) return false;
8190 obj = obj[key];
8191 }
8192 return !!length;
8193}
8194
8195
8196/***/ }),
8197/* 249 */
8198/***/ (function(module, __webpack_exports__, __webpack_require__) {
8199
8200"use strict";
8201/* harmony export (immutable) */ __webpack_exports__["a"] = mapObject;
8202/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(10);
8203/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__keys_js__ = __webpack_require__(6);
8204
8205
8206
8207// Returns the results of applying the `iteratee` to each element of `obj`.
8208// In contrast to `_.map` it returns an object.
8209function mapObject(obj, iteratee, context) {
8210 iteratee = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(iteratee, context);
8211 var _keys = Object(__WEBPACK_IMPORTED_MODULE_1__keys_js__["a" /* default */])(obj),
8212 length = _keys.length,
8213 results = {};
8214 for (var index = 0; index < length; index++) {
8215 var currentKey = _keys[index];
8216 results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
8217 }
8218 return results;
8219}
8220
8221
8222/***/ }),
8223/* 250 */
8224/***/ (function(module, __webpack_exports__, __webpack_require__) {
8225
8226"use strict";
8227/* harmony export (immutable) */ __webpack_exports__["a"] = propertyOf;
8228/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__noop_js__ = __webpack_require__(151);
8229/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__get_js__ = __webpack_require__(147);
8230
8231
8232
8233// Generates a function for a given object that returns a given property.
8234function propertyOf(obj) {
8235 if (obj == null) return __WEBPACK_IMPORTED_MODULE_0__noop_js__["a" /* default */];
8236 return function(path) {
8237 return Object(__WEBPACK_IMPORTED_MODULE_1__get_js__["a" /* default */])(obj, path);
8238 };
8239}
8240
8241
8242/***/ }),
8243/* 251 */
8244/***/ (function(module, __webpack_exports__, __webpack_require__) {
8245
8246"use strict";
8247/* harmony export (immutable) */ __webpack_exports__["a"] = times;
8248/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__optimizeCb_js__ = __webpack_require__(55);
8249
8250
8251// Run a function **n** times.
8252function times(n, iteratee, context) {
8253 var accum = Array(Math.max(0, n));
8254 iteratee = Object(__WEBPACK_IMPORTED_MODULE_0__optimizeCb_js__["a" /* default */])(iteratee, context, 1);
8255 for (var i = 0; i < n; i++) accum[i] = iteratee(i);
8256 return accum;
8257}
8258
8259
8260/***/ }),
8261/* 252 */
8262/***/ (function(module, __webpack_exports__, __webpack_require__) {
8263
8264"use strict";
8265/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createEscaper_js__ = __webpack_require__(153);
8266/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__escapeMap_js__ = __webpack_require__(154);
8267
8268
8269
8270// Function for escaping strings to HTML interpolation.
8271/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createEscaper_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__escapeMap_js__["a" /* default */]));
8272
8273
8274/***/ }),
8275/* 253 */
8276/***/ (function(module, __webpack_exports__, __webpack_require__) {
8277
8278"use strict";
8279/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createEscaper_js__ = __webpack_require__(153);
8280/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__unescapeMap_js__ = __webpack_require__(254);
8281
8282
8283
8284// Function for unescaping strings from HTML interpolation.
8285/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createEscaper_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__unescapeMap_js__["a" /* default */]));
8286
8287
8288/***/ }),
8289/* 254 */
8290/***/ (function(module, __webpack_exports__, __webpack_require__) {
8291
8292"use strict";
8293/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__invert_js__ = __webpack_require__(141);
8294/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__escapeMap_js__ = __webpack_require__(154);
8295
8296
8297
8298// Internal list of HTML entities for unescaping.
8299/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__invert_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__escapeMap_js__["a" /* default */]));
8300
8301
8302/***/ }),
8303/* 255 */
8304/***/ (function(module, __webpack_exports__, __webpack_require__) {
8305
8306"use strict";
8307/* harmony export (immutable) */ __webpack_exports__["a"] = template;
8308/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__defaults_js__ = __webpack_require__(144);
8309/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__underscore_js__ = __webpack_require__(12);
8310/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__templateSettings_js__ = __webpack_require__(155);
8311
8312
8313
8314
8315// When customizing `_.templateSettings`, if you don't want to define an
8316// interpolation, evaluation or escaping regex, we need one that is
8317// guaranteed not to match.
8318var noMatch = /(.)^/;
8319
8320// Certain characters need to be escaped so that they can be put into a
8321// string literal.
8322var escapes = {
8323 "'": "'",
8324 '\\': '\\',
8325 '\r': 'r',
8326 '\n': 'n',
8327 '\u2028': 'u2028',
8328 '\u2029': 'u2029'
8329};
8330
8331var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
8332
8333function escapeChar(match) {
8334 return '\\' + escapes[match];
8335}
8336
8337var bareIdentifier = /^\s*(\w|\$)+\s*$/;
8338
8339// JavaScript micro-templating, similar to John Resig's implementation.
8340// Underscore templating handles arbitrary delimiters, preserves whitespace,
8341// and correctly escapes quotes within interpolated code.
8342// NB: `oldSettings` only exists for backwards compatibility.
8343function template(text, settings, oldSettings) {
8344 if (!settings && oldSettings) settings = oldSettings;
8345 settings = Object(__WEBPACK_IMPORTED_MODULE_0__defaults_js__["a" /* default */])({}, settings, __WEBPACK_IMPORTED_MODULE_1__underscore_js__["a" /* default */].templateSettings);
8346
8347 // Combine delimiters into one regular expression via alternation.
8348 var matcher = RegExp([
8349 (settings.escape || noMatch).source,
8350 (settings.interpolate || noMatch).source,
8351 (settings.evaluate || noMatch).source
8352 ].join('|') + '|$', 'g');
8353
8354 // Compile the template source, escaping string literals appropriately.
8355 var index = 0;
8356 var source = "__p+='";
8357 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
8358 source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
8359 index = offset + match.length;
8360
8361 if (escape) {
8362 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
8363 } else if (interpolate) {
8364 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
8365 } else if (evaluate) {
8366 source += "';\n" + evaluate + "\n__p+='";
8367 }
8368
8369 // Adobe VMs need the match returned to produce the correct offset.
8370 return match;
8371 });
8372 source += "';\n";
8373
8374 var argument = settings.variable;
8375 if (argument) {
8376 if (!bareIdentifier.test(argument)) throw new Error(argument);
8377 } else {
8378 // If a variable is not specified, place data values in local scope.
8379 source = 'with(obj||{}){\n' + source + '}\n';
8380 argument = 'obj';
8381 }
8382
8383 source = "var __t,__p='',__j=Array.prototype.join," +
8384 "print=function(){__p+=__j.call(arguments,'');};\n" +
8385 source + 'return __p;\n';
8386
8387 var render;
8388 try {
8389 render = new Function(argument, '_', source);
8390 } catch (e) {
8391 e.source = source;
8392 throw e;
8393 }
8394
8395 var template = function(data) {
8396 return render.call(this, data, __WEBPACK_IMPORTED_MODULE_1__underscore_js__["a" /* default */]);
8397 };
8398
8399 // Provide the compiled source as a convenience for precompilation.
8400 template.source = 'function(' + argument + '){\n' + source + '}';
8401
8402 return template;
8403}
8404
8405
8406/***/ }),
8407/* 256 */
8408/***/ (function(module, __webpack_exports__, __webpack_require__) {
8409
8410"use strict";
8411/* harmony export (immutable) */ __webpack_exports__["a"] = result;
8412/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isFunction_js__ = __webpack_require__(17);
8413/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__toPath_js__ = __webpack_require__(54);
8414
8415
8416
8417// Traverses the children of `obj` along `path`. If a child is a function, it
8418// is invoked with its parent as context. Returns the value of the final
8419// child, or `fallback` if any child is undefined.
8420function result(obj, path, fallback) {
8421 path = Object(__WEBPACK_IMPORTED_MODULE_1__toPath_js__["a" /* default */])(path);
8422 var length = path.length;
8423 if (!length) {
8424 return Object(__WEBPACK_IMPORTED_MODULE_0__isFunction_js__["a" /* default */])(fallback) ? fallback.call(obj) : fallback;
8425 }
8426 for (var i = 0; i < length; i++) {
8427 var prop = obj == null ? void 0 : obj[path[i]];
8428 if (prop === void 0) {
8429 prop = fallback;
8430 i = length; // Ensure we don't continue iterating.
8431 }
8432 obj = Object(__WEBPACK_IMPORTED_MODULE_0__isFunction_js__["a" /* default */])(prop) ? prop.call(obj) : prop;
8433 }
8434 return obj;
8435}
8436
8437
8438/***/ }),
8439/* 257 */
8440/***/ (function(module, __webpack_exports__, __webpack_require__) {
8441
8442"use strict";
8443/* harmony export (immutable) */ __webpack_exports__["a"] = uniqueId;
8444// Generate a unique integer id (unique within the entire client session).
8445// Useful for temporary DOM ids.
8446var idCounter = 0;
8447function uniqueId(prefix) {
8448 var id = ++idCounter + '';
8449 return prefix ? prefix + id : id;
8450}
8451
8452
8453/***/ }),
8454/* 258 */
8455/***/ (function(module, __webpack_exports__, __webpack_require__) {
8456
8457"use strict";
8458/* harmony export (immutable) */ __webpack_exports__["a"] = chain;
8459/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(12);
8460
8461
8462// Start chaining a wrapped Underscore object.
8463function chain(obj) {
8464 var instance = Object(__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */])(obj);
8465 instance._chain = true;
8466 return instance;
8467}
8468
8469
8470/***/ }),
8471/* 259 */
8472/***/ (function(module, __webpack_exports__, __webpack_require__) {
8473
8474"use strict";
8475/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(11);
8476/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__flatten_js__ = __webpack_require__(40);
8477/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__bind_js__ = __webpack_require__(157);
8478
8479
8480
8481
8482// Bind a number of an object's methods to that object. Remaining arguments
8483// are the method names to be bound. Useful for ensuring that all callbacks
8484// defined on an object belong to it.
8485/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(obj, keys) {
8486 keys = Object(__WEBPACK_IMPORTED_MODULE_1__flatten_js__["a" /* default */])(keys, false, false);
8487 var index = keys.length;
8488 if (index < 1) throw new Error('bindAll must be passed function names');
8489 while (index--) {
8490 var key = keys[index];
8491 obj[key] = Object(__WEBPACK_IMPORTED_MODULE_2__bind_js__["a" /* default */])(obj[key], obj);
8492 }
8493 return obj;
8494}));
8495
8496
8497/***/ }),
8498/* 260 */
8499/***/ (function(module, __webpack_exports__, __webpack_require__) {
8500
8501"use strict";
8502/* harmony export (immutable) */ __webpack_exports__["a"] = memoize;
8503/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__has_js__ = __webpack_require__(27);
8504
8505
8506// Memoize an expensive function by storing its results.
8507function memoize(func, hasher) {
8508 var memoize = function(key) {
8509 var cache = memoize.cache;
8510 var address = '' + (hasher ? hasher.apply(this, arguments) : key);
8511 if (!Object(__WEBPACK_IMPORTED_MODULE_0__has_js__["a" /* default */])(cache, address)) cache[address] = func.apply(this, arguments);
8512 return cache[address];
8513 };
8514 memoize.cache = {};
8515 return memoize;
8516}
8517
8518
8519/***/ }),
8520/* 261 */
8521/***/ (function(module, __webpack_exports__, __webpack_require__) {
8522
8523"use strict";
8524/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__partial_js__ = __webpack_require__(68);
8525/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__delay_js__ = __webpack_require__(158);
8526/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__underscore_js__ = __webpack_require__(12);
8527
8528
8529
8530
8531// Defers a function, scheduling it to run after the current call stack has
8532// cleared.
8533/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__partial_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__delay_js__["a" /* default */], __WEBPACK_IMPORTED_MODULE_2__underscore_js__["a" /* default */], 1));
8534
8535
8536/***/ }),
8537/* 262 */
8538/***/ (function(module, __webpack_exports__, __webpack_require__) {
8539
8540"use strict";
8541/* harmony export (immutable) */ __webpack_exports__["a"] = throttle;
8542/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__now_js__ = __webpack_require__(103);
8543
8544
8545// Returns a function, that, when invoked, will only be triggered at most once
8546// during a given window of time. Normally, the throttled function will run
8547// as much as it can, without ever going more than once per `wait` duration;
8548// but if you'd like to disable the execution on the leading edge, pass
8549// `{leading: false}`. To disable execution on the trailing edge, ditto.
8550function throttle(func, wait, options) {
8551 var timeout, context, args, result;
8552 var previous = 0;
8553 if (!options) options = {};
8554
8555 var later = function() {
8556 previous = options.leading === false ? 0 : Object(__WEBPACK_IMPORTED_MODULE_0__now_js__["a" /* default */])();
8557 timeout = null;
8558 result = func.apply(context, args);
8559 if (!timeout) context = args = null;
8560 };
8561
8562 var throttled = function() {
8563 var _now = Object(__WEBPACK_IMPORTED_MODULE_0__now_js__["a" /* default */])();
8564 if (!previous && options.leading === false) previous = _now;
8565 var remaining = wait - (_now - previous);
8566 context = this;
8567 args = arguments;
8568 if (remaining <= 0 || remaining > wait) {
8569 if (timeout) {
8570 clearTimeout(timeout);
8571 timeout = null;
8572 }
8573 previous = _now;
8574 result = func.apply(context, args);
8575 if (!timeout) context = args = null;
8576 } else if (!timeout && options.trailing !== false) {
8577 timeout = setTimeout(later, remaining);
8578 }
8579 return result;
8580 };
8581
8582 throttled.cancel = function() {
8583 clearTimeout(timeout);
8584 previous = 0;
8585 timeout = context = args = null;
8586 };
8587
8588 return throttled;
8589}
8590
8591
8592/***/ }),
8593/* 263 */
8594/***/ (function(module, __webpack_exports__, __webpack_require__) {
8595
8596"use strict";
8597/* harmony export (immutable) */ __webpack_exports__["a"] = debounce;
8598/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(11);
8599/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__now_js__ = __webpack_require__(103);
8600
8601
8602
8603// When a sequence of calls of the returned function ends, the argument
8604// function is triggered. The end of a sequence is defined by the `wait`
8605// parameter. If `immediate` is passed, the argument function will be
8606// triggered at the beginning of the sequence instead of at the end.
8607function debounce(func, wait, immediate) {
8608 var timeout, previous, args, result, context;
8609
8610 var later = function() {
8611 var passed = Object(__WEBPACK_IMPORTED_MODULE_1__now_js__["a" /* default */])() - previous;
8612 if (wait > passed) {
8613 timeout = setTimeout(later, wait - passed);
8614 } else {
8615 timeout = null;
8616 if (!immediate) result = func.apply(context, args);
8617 // This check is needed because `func` can recursively invoke `debounced`.
8618 if (!timeout) args = context = null;
8619 }
8620 };
8621
8622 var debounced = Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(_args) {
8623 context = this;
8624 args = _args;
8625 previous = Object(__WEBPACK_IMPORTED_MODULE_1__now_js__["a" /* default */])();
8626 if (!timeout) {
8627 timeout = setTimeout(later, wait);
8628 if (immediate) result = func.apply(context, args);
8629 }
8630 return result;
8631 });
8632
8633 debounced.cancel = function() {
8634 clearTimeout(timeout);
8635 timeout = args = context = null;
8636 };
8637
8638 return debounced;
8639}
8640
8641
8642/***/ }),
8643/* 264 */
8644/***/ (function(module, __webpack_exports__, __webpack_require__) {
8645
8646"use strict";
8647/* harmony export (immutable) */ __webpack_exports__["a"] = wrap;
8648/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__partial_js__ = __webpack_require__(68);
8649
8650
8651// Returns the first function passed as an argument to the second,
8652// allowing you to adjust arguments, run code before and after, and
8653// conditionally execute the original function.
8654function wrap(func, wrapper) {
8655 return Object(__WEBPACK_IMPORTED_MODULE_0__partial_js__["a" /* default */])(wrapper, func);
8656}
8657
8658
8659/***/ }),
8660/* 265 */
8661/***/ (function(module, __webpack_exports__, __webpack_require__) {
8662
8663"use strict";
8664/* harmony export (immutable) */ __webpack_exports__["a"] = compose;
8665// Returns a function that is the composition of a list of functions, each
8666// consuming the return value of the function that follows.
8667function compose() {
8668 var args = arguments;
8669 var start = args.length - 1;
8670 return function() {
8671 var i = start;
8672 var result = args[start].apply(this, arguments);
8673 while (i--) result = args[i].call(this, result);
8674 return result;
8675 };
8676}
8677
8678
8679/***/ }),
8680/* 266 */
8681/***/ (function(module, __webpack_exports__, __webpack_require__) {
8682
8683"use strict";
8684/* harmony export (immutable) */ __webpack_exports__["a"] = after;
8685// Returns a function that will only be executed on and after the Nth call.
8686function after(times, func) {
8687 return function() {
8688 if (--times < 1) {
8689 return func.apply(this, arguments);
8690 }
8691 };
8692}
8693
8694
8695/***/ }),
8696/* 267 */
8697/***/ (function(module, __webpack_exports__, __webpack_require__) {
8698
8699"use strict";
8700/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__partial_js__ = __webpack_require__(68);
8701/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__before_js__ = __webpack_require__(159);
8702
8703
8704
8705// Returns a function that will be executed at most one time, no matter how
8706// often you call it. Useful for lazy initialization.
8707/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__partial_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__before_js__["a" /* default */], 2));
8708
8709
8710/***/ }),
8711/* 268 */
8712/***/ (function(module, __webpack_exports__, __webpack_require__) {
8713
8714"use strict";
8715/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__findLastIndex_js__ = __webpack_require__(162);
8716/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__createIndexFinder_js__ = __webpack_require__(165);
8717
8718
8719
8720// Return the position of the last occurrence of an item in an array,
8721// or -1 if the item is not included in the array.
8722/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_1__createIndexFinder_js__["a" /* default */])(-1, __WEBPACK_IMPORTED_MODULE_0__findLastIndex_js__["a" /* default */]));
8723
8724
8725/***/ }),
8726/* 269 */
8727/***/ (function(module, __webpack_exports__, __webpack_require__) {
8728
8729"use strict";
8730/* harmony export (immutable) */ __webpack_exports__["a"] = findWhere;
8731/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__find_js__ = __webpack_require__(166);
8732/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__matcher_js__ = __webpack_require__(67);
8733
8734
8735
8736// Convenience version of a common use case of `_.find`: getting the first
8737// object containing specific `key:value` pairs.
8738function findWhere(obj, attrs) {
8739 return Object(__WEBPACK_IMPORTED_MODULE_0__find_js__["a" /* default */])(obj, Object(__WEBPACK_IMPORTED_MODULE_1__matcher_js__["a" /* default */])(attrs));
8740}
8741
8742
8743/***/ }),
8744/* 270 */
8745/***/ (function(module, __webpack_exports__, __webpack_require__) {
8746
8747"use strict";
8748/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createReduce_js__ = __webpack_require__(167);
8749
8750
8751// **Reduce** builds up a single result from a list of values, aka `inject`,
8752// or `foldl`.
8753/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createReduce_js__["a" /* default */])(1));
8754
8755
8756/***/ }),
8757/* 271 */
8758/***/ (function(module, __webpack_exports__, __webpack_require__) {
8759
8760"use strict";
8761/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createReduce_js__ = __webpack_require__(167);
8762
8763
8764// The right-associative version of reduce, also known as `foldr`.
8765/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createReduce_js__["a" /* default */])(-1));
8766
8767
8768/***/ }),
8769/* 272 */
8770/***/ (function(module, __webpack_exports__, __webpack_require__) {
8771
8772"use strict";
8773/* harmony export (immutable) */ __webpack_exports__["a"] = reject;
8774/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__filter_js__ = __webpack_require__(56);
8775/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__negate_js__ = __webpack_require__(104);
8776/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__cb_js__ = __webpack_require__(10);
8777
8778
8779
8780
8781// Return all the elements for which a truth test fails.
8782function reject(obj, predicate, context) {
8783 return Object(__WEBPACK_IMPORTED_MODULE_0__filter_js__["a" /* default */])(obj, Object(__WEBPACK_IMPORTED_MODULE_1__negate_js__["a" /* default */])(Object(__WEBPACK_IMPORTED_MODULE_2__cb_js__["a" /* default */])(predicate)), context);
8784}
8785
8786
8787/***/ }),
8788/* 273 */
8789/***/ (function(module, __webpack_exports__, __webpack_require__) {
8790
8791"use strict";
8792/* harmony export (immutable) */ __webpack_exports__["a"] = every;
8793/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(10);
8794/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__ = __webpack_require__(13);
8795/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__keys_js__ = __webpack_require__(6);
8796
8797
8798
8799
8800// Determine whether all of the elements pass a truth test.
8801function every(obj, predicate, context) {
8802 predicate = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(predicate, context);
8803 var _keys = !Object(__WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__["a" /* default */])(obj) && Object(__WEBPACK_IMPORTED_MODULE_2__keys_js__["a" /* default */])(obj),
8804 length = (_keys || obj).length;
8805 for (var index = 0; index < length; index++) {
8806 var currentKey = _keys ? _keys[index] : index;
8807 if (!predicate(obj[currentKey], currentKey, obj)) return false;
8808 }
8809 return true;
8810}
8811
8812
8813/***/ }),
8814/* 274 */
8815/***/ (function(module, __webpack_exports__, __webpack_require__) {
8816
8817"use strict";
8818/* harmony export (immutable) */ __webpack_exports__["a"] = some;
8819/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(10);
8820/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__ = __webpack_require__(13);
8821/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__keys_js__ = __webpack_require__(6);
8822
8823
8824
8825
8826// Determine if at least one element in the object passes a truth test.
8827function some(obj, predicate, context) {
8828 predicate = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(predicate, context);
8829 var _keys = !Object(__WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__["a" /* default */])(obj) && Object(__WEBPACK_IMPORTED_MODULE_2__keys_js__["a" /* default */])(obj),
8830 length = (_keys || obj).length;
8831 for (var index = 0; index < length; index++) {
8832 var currentKey = _keys ? _keys[index] : index;
8833 if (predicate(obj[currentKey], currentKey, obj)) return true;
8834 }
8835 return false;
8836}
8837
8838
8839/***/ }),
8840/* 275 */
8841/***/ (function(module, __webpack_exports__, __webpack_require__) {
8842
8843"use strict";
8844/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(11);
8845/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(17);
8846/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__map_js__ = __webpack_require__(41);
8847/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__deepGet_js__ = __webpack_require__(100);
8848/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__toPath_js__ = __webpack_require__(54);
8849
8850
8851
8852
8853
8854
8855// Invoke a method (with arguments) on every item in a collection.
8856/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(obj, path, args) {
8857 var contextPath, func;
8858 if (Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(path)) {
8859 func = path;
8860 } else {
8861 path = Object(__WEBPACK_IMPORTED_MODULE_4__toPath_js__["a" /* default */])(path);
8862 contextPath = path.slice(0, -1);
8863 path = path[path.length - 1];
8864 }
8865 return Object(__WEBPACK_IMPORTED_MODULE_2__map_js__["a" /* default */])(obj, function(context) {
8866 var method = func;
8867 if (!method) {
8868 if (contextPath && contextPath.length) {
8869 context = Object(__WEBPACK_IMPORTED_MODULE_3__deepGet_js__["a" /* default */])(context, contextPath);
8870 }
8871 if (context == null) return void 0;
8872 method = context[path];
8873 }
8874 return method == null ? method : method.apply(context, args);
8875 });
8876}));
8877
8878
8879/***/ }),
8880/* 276 */
8881/***/ (function(module, __webpack_exports__, __webpack_require__) {
8882
8883"use strict";
8884/* harmony export (immutable) */ __webpack_exports__["a"] = where;
8885/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__filter_js__ = __webpack_require__(56);
8886/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__matcher_js__ = __webpack_require__(67);
8887
8888
8889
8890// Convenience version of a common use case of `_.filter`: selecting only
8891// objects containing specific `key:value` pairs.
8892function where(obj, attrs) {
8893 return Object(__WEBPACK_IMPORTED_MODULE_0__filter_js__["a" /* default */])(obj, Object(__WEBPACK_IMPORTED_MODULE_1__matcher_js__["a" /* default */])(attrs));
8894}
8895
8896
8897/***/ }),
8898/* 277 */
8899/***/ (function(module, __webpack_exports__, __webpack_require__) {
8900
8901"use strict";
8902/* harmony export (immutable) */ __webpack_exports__["a"] = min;
8903/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__ = __webpack_require__(13);
8904/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__values_js__ = __webpack_require__(39);
8905/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__cb_js__ = __webpack_require__(10);
8906/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__each_js__ = __webpack_require__(32);
8907
8908
8909
8910
8911
8912// Return the minimum element (or element-based computation).
8913function min(obj, iteratee, context) {
8914 var result = Infinity, lastComputed = Infinity,
8915 value, computed;
8916 if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
8917 obj = Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj) ? obj : Object(__WEBPACK_IMPORTED_MODULE_1__values_js__["a" /* default */])(obj);
8918 for (var i = 0, length = obj.length; i < length; i++) {
8919 value = obj[i];
8920 if (value != null && value < result) {
8921 result = value;
8922 }
8923 }
8924 } else {
8925 iteratee = Object(__WEBPACK_IMPORTED_MODULE_2__cb_js__["a" /* default */])(iteratee, context);
8926 Object(__WEBPACK_IMPORTED_MODULE_3__each_js__["a" /* default */])(obj, function(v, index, list) {
8927 computed = iteratee(v, index, list);
8928 if (computed < lastComputed || computed === Infinity && result === Infinity) {
8929 result = v;
8930 lastComputed = computed;
8931 }
8932 });
8933 }
8934 return result;
8935}
8936
8937
8938/***/ }),
8939/* 278 */
8940/***/ (function(module, __webpack_exports__, __webpack_require__) {
8941
8942"use strict";
8943/* harmony export (immutable) */ __webpack_exports__["a"] = shuffle;
8944/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__sample_js__ = __webpack_require__(169);
8945
8946
8947// Shuffle a collection.
8948function shuffle(obj) {
8949 return Object(__WEBPACK_IMPORTED_MODULE_0__sample_js__["a" /* default */])(obj, Infinity);
8950}
8951
8952
8953/***/ }),
8954/* 279 */
8955/***/ (function(module, __webpack_exports__, __webpack_require__) {
8956
8957"use strict";
8958/* harmony export (immutable) */ __webpack_exports__["a"] = sortBy;
8959/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(10);
8960/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__pluck_js__ = __webpack_require__(106);
8961/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__map_js__ = __webpack_require__(41);
8962
8963
8964
8965
8966// Sort the object's values by a criterion produced by an iteratee.
8967function sortBy(obj, iteratee, context) {
8968 var index = 0;
8969 iteratee = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(iteratee, context);
8970 return Object(__WEBPACK_IMPORTED_MODULE_1__pluck_js__["a" /* default */])(Object(__WEBPACK_IMPORTED_MODULE_2__map_js__["a" /* default */])(obj, function(value, key, list) {
8971 return {
8972 value: value,
8973 index: index++,
8974 criteria: iteratee(value, key, list)
8975 };
8976 }).sort(function(left, right) {
8977 var a = left.criteria;
8978 var b = right.criteria;
8979 if (a !== b) {
8980 if (a > b || a === void 0) return 1;
8981 if (a < b || b === void 0) return -1;
8982 }
8983 return left.index - right.index;
8984 }), 'value');
8985}
8986
8987
8988/***/ }),
8989/* 280 */
8990/***/ (function(module, __webpack_exports__, __webpack_require__) {
8991
8992"use strict";
8993/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__group_js__ = __webpack_require__(69);
8994/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__has_js__ = __webpack_require__(27);
8995
8996
8997
8998// Groups the object's values by a criterion. Pass either a string attribute
8999// to group by, or a function that returns the criterion.
9000/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__group_js__["a" /* default */])(function(result, value, key) {
9001 if (Object(__WEBPACK_IMPORTED_MODULE_1__has_js__["a" /* default */])(result, key)) result[key].push(value); else result[key] = [value];
9002}));
9003
9004
9005/***/ }),
9006/* 281 */
9007/***/ (function(module, __webpack_exports__, __webpack_require__) {
9008
9009"use strict";
9010/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__group_js__ = __webpack_require__(69);
9011
9012
9013// Indexes the object's values by a criterion, similar to `_.groupBy`, but for
9014// when you know that your index values will be unique.
9015/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__group_js__["a" /* default */])(function(result, value, key) {
9016 result[key] = value;
9017}));
9018
9019
9020/***/ }),
9021/* 282 */
9022/***/ (function(module, __webpack_exports__, __webpack_require__) {
9023
9024"use strict";
9025/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__group_js__ = __webpack_require__(69);
9026/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__has_js__ = __webpack_require__(27);
9027
9028
9029
9030// Counts instances of an object that group by a certain criterion. Pass
9031// either a string attribute to count by, or a function that returns the
9032// criterion.
9033/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__group_js__["a" /* default */])(function(result, value, key) {
9034 if (Object(__WEBPACK_IMPORTED_MODULE_1__has_js__["a" /* default */])(result, key)) result[key]++; else result[key] = 1;
9035}));
9036
9037
9038/***/ }),
9039/* 283 */
9040/***/ (function(module, __webpack_exports__, __webpack_require__) {
9041
9042"use strict";
9043/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__group_js__ = __webpack_require__(69);
9044
9045
9046// Split a collection into two arrays: one whose elements all pass the given
9047// truth test, and one whose elements all do not pass the truth test.
9048/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__group_js__["a" /* default */])(function(result, value, pass) {
9049 result[pass ? 0 : 1].push(value);
9050}, true));
9051
9052
9053/***/ }),
9054/* 284 */
9055/***/ (function(module, __webpack_exports__, __webpack_require__) {
9056
9057"use strict";
9058/* harmony export (immutable) */ __webpack_exports__["a"] = toArray;
9059/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArray_js__ = __webpack_require__(31);
9060/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__setup_js__ = __webpack_require__(2);
9061/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isString_js__ = __webpack_require__(93);
9062/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isArrayLike_js__ = __webpack_require__(13);
9063/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__map_js__ = __webpack_require__(41);
9064/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__identity_js__ = __webpack_require__(101);
9065/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__values_js__ = __webpack_require__(39);
9066
9067
9068
9069
9070
9071
9072
9073
9074// Safely create a real, live array from anything iterable.
9075var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
9076function toArray(obj) {
9077 if (!obj) return [];
9078 if (Object(__WEBPACK_IMPORTED_MODULE_0__isArray_js__["a" /* default */])(obj)) return __WEBPACK_IMPORTED_MODULE_1__setup_js__["q" /* slice */].call(obj);
9079 if (Object(__WEBPACK_IMPORTED_MODULE_2__isString_js__["a" /* default */])(obj)) {
9080 // Keep surrogate pair characters together.
9081 return obj.match(reStrSymbol);
9082 }
9083 if (Object(__WEBPACK_IMPORTED_MODULE_3__isArrayLike_js__["a" /* default */])(obj)) return Object(__WEBPACK_IMPORTED_MODULE_4__map_js__["a" /* default */])(obj, __WEBPACK_IMPORTED_MODULE_5__identity_js__["a" /* default */]);
9084 return Object(__WEBPACK_IMPORTED_MODULE_6__values_js__["a" /* default */])(obj);
9085}
9086
9087
9088/***/ }),
9089/* 285 */
9090/***/ (function(module, __webpack_exports__, __webpack_require__) {
9091
9092"use strict";
9093/* harmony export (immutable) */ __webpack_exports__["a"] = size;
9094/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__ = __webpack_require__(13);
9095/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__keys_js__ = __webpack_require__(6);
9096
9097
9098
9099// Return the number of elements in a collection.
9100function size(obj) {
9101 if (obj == null) return 0;
9102 return Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj) ? obj.length : Object(__WEBPACK_IMPORTED_MODULE_1__keys_js__["a" /* default */])(obj).length;
9103}
9104
9105
9106/***/ }),
9107/* 286 */
9108/***/ (function(module, __webpack_exports__, __webpack_require__) {
9109
9110"use strict";
9111/* harmony export (immutable) */ __webpack_exports__["a"] = keyInObj;
9112// Internal `_.pick` helper function to determine whether `key` is an enumerable
9113// property name of `obj`.
9114function keyInObj(value, key, obj) {
9115 return key in obj;
9116}
9117
9118
9119/***/ }),
9120/* 287 */
9121/***/ (function(module, __webpack_exports__, __webpack_require__) {
9122
9123"use strict";
9124/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(11);
9125/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(17);
9126/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__negate_js__ = __webpack_require__(104);
9127/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__map_js__ = __webpack_require__(41);
9128/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__flatten_js__ = __webpack_require__(40);
9129/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__contains_js__ = __webpack_require__(57);
9130/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__pick_js__ = __webpack_require__(170);
9131
9132
9133
9134
9135
9136
9137
9138
9139// Return a copy of the object without the disallowed properties.
9140/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(obj, keys) {
9141 var iteratee = keys[0], context;
9142 if (Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(iteratee)) {
9143 iteratee = Object(__WEBPACK_IMPORTED_MODULE_2__negate_js__["a" /* default */])(iteratee);
9144 if (keys.length > 1) context = keys[1];
9145 } else {
9146 keys = Object(__WEBPACK_IMPORTED_MODULE_3__map_js__["a" /* default */])(Object(__WEBPACK_IMPORTED_MODULE_4__flatten_js__["a" /* default */])(keys, false, false), String);
9147 iteratee = function(value, key) {
9148 return !Object(__WEBPACK_IMPORTED_MODULE_5__contains_js__["a" /* default */])(keys, key);
9149 };
9150 }
9151 return Object(__WEBPACK_IMPORTED_MODULE_6__pick_js__["a" /* default */])(obj, iteratee, context);
9152}));
9153
9154
9155/***/ }),
9156/* 288 */
9157/***/ (function(module, __webpack_exports__, __webpack_require__) {
9158
9159"use strict";
9160/* harmony export (immutable) */ __webpack_exports__["a"] = first;
9161/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__initial_js__ = __webpack_require__(171);
9162
9163
9164// Get the first element of an array. Passing **n** will return the first N
9165// values in the array. The **guard** check allows it to work with `_.map`.
9166function first(array, n, guard) {
9167 if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
9168 if (n == null || guard) return array[0];
9169 return Object(__WEBPACK_IMPORTED_MODULE_0__initial_js__["a" /* default */])(array, array.length - n);
9170}
9171
9172
9173/***/ }),
9174/* 289 */
9175/***/ (function(module, __webpack_exports__, __webpack_require__) {
9176
9177"use strict";
9178/* harmony export (immutable) */ __webpack_exports__["a"] = last;
9179/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__rest_js__ = __webpack_require__(172);
9180
9181
9182// Get the last element of an array. Passing **n** will return the last N
9183// values in the array.
9184function last(array, n, guard) {
9185 if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
9186 if (n == null || guard) return array[array.length - 1];
9187 return Object(__WEBPACK_IMPORTED_MODULE_0__rest_js__["a" /* default */])(array, Math.max(0, array.length - n));
9188}
9189
9190
9191/***/ }),
9192/* 290 */
9193/***/ (function(module, __webpack_exports__, __webpack_require__) {
9194
9195"use strict";
9196/* harmony export (immutable) */ __webpack_exports__["a"] = compact;
9197/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__filter_js__ = __webpack_require__(56);
9198
9199
9200// Trim out all falsy values from an array.
9201function compact(array) {
9202 return Object(__WEBPACK_IMPORTED_MODULE_0__filter_js__["a" /* default */])(array, Boolean);
9203}
9204
9205
9206/***/ }),
9207/* 291 */
9208/***/ (function(module, __webpack_exports__, __webpack_require__) {
9209
9210"use strict";
9211/* harmony export (immutable) */ __webpack_exports__["a"] = flatten;
9212/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__flatten_js__ = __webpack_require__(40);
9213
9214
9215// Flatten out an array, either recursively (by default), or up to `depth`.
9216// Passing `true` or `false` as `depth` means `1` or `Infinity`, respectively.
9217function flatten(array, depth) {
9218 return Object(__WEBPACK_IMPORTED_MODULE_0__flatten_js__["a" /* default */])(array, depth, false);
9219}
9220
9221
9222/***/ }),
9223/* 292 */
9224/***/ (function(module, __webpack_exports__, __webpack_require__) {
9225
9226"use strict";
9227/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(11);
9228/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__difference_js__ = __webpack_require__(173);
9229
9230
9231
9232// Return a version of the array that does not contain the specified value(s).
9233/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(array, otherArrays) {
9234 return Object(__WEBPACK_IMPORTED_MODULE_1__difference_js__["a" /* default */])(array, otherArrays);
9235}));
9236
9237
9238/***/ }),
9239/* 293 */
9240/***/ (function(module, __webpack_exports__, __webpack_require__) {
9241
9242"use strict";
9243/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(11);
9244/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__uniq_js__ = __webpack_require__(174);
9245/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__flatten_js__ = __webpack_require__(40);
9246
9247
9248
9249
9250// Produce an array that contains the union: each distinct element from all of
9251// the passed-in arrays.
9252/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(arrays) {
9253 return Object(__WEBPACK_IMPORTED_MODULE_1__uniq_js__["a" /* default */])(Object(__WEBPACK_IMPORTED_MODULE_2__flatten_js__["a" /* default */])(arrays, true, true));
9254}));
9255
9256
9257/***/ }),
9258/* 294 */
9259/***/ (function(module, __webpack_exports__, __webpack_require__) {
9260
9261"use strict";
9262/* harmony export (immutable) */ __webpack_exports__["a"] = intersection;
9263/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__getLength_js__ = __webpack_require__(18);
9264/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__contains_js__ = __webpack_require__(57);
9265
9266
9267
9268// Produce an array that contains every item shared between all the
9269// passed-in arrays.
9270function intersection(array) {
9271 var result = [];
9272 var argsLength = arguments.length;
9273 for (var i = 0, length = Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(array); i < length; i++) {
9274 var item = array[i];
9275 if (Object(__WEBPACK_IMPORTED_MODULE_1__contains_js__["a" /* default */])(result, item)) continue;
9276 var j;
9277 for (j = 1; j < argsLength; j++) {
9278 if (!Object(__WEBPACK_IMPORTED_MODULE_1__contains_js__["a" /* default */])(arguments[j], item)) break;
9279 }
9280 if (j === argsLength) result.push(item);
9281 }
9282 return result;
9283}
9284
9285
9286/***/ }),
9287/* 295 */
9288/***/ (function(module, __webpack_exports__, __webpack_require__) {
9289
9290"use strict";
9291/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(11);
9292/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__unzip_js__ = __webpack_require__(175);
9293
9294
9295
9296// Zip together multiple lists into a single array -- elements that share
9297// an index go together.
9298/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__unzip_js__["a" /* default */]));
9299
9300
9301/***/ }),
9302/* 296 */
9303/***/ (function(module, __webpack_exports__, __webpack_require__) {
9304
9305"use strict";
9306/* harmony export (immutable) */ __webpack_exports__["a"] = object;
9307/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__getLength_js__ = __webpack_require__(18);
9308
9309
9310// Converts lists into objects. Pass either a single array of `[key, value]`
9311// pairs, or two parallel arrays of the same length -- one of keys, and one of
9312// the corresponding values. Passing by pairs is the reverse of `_.pairs`.
9313function object(list, values) {
9314 var result = {};
9315 for (var i = 0, length = Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(list); i < length; i++) {
9316 if (values) {
9317 result[list[i]] = values[i];
9318 } else {
9319 result[list[i][0]] = list[i][1];
9320 }
9321 }
9322 return result;
9323}
9324
9325
9326/***/ }),
9327/* 297 */
9328/***/ (function(module, __webpack_exports__, __webpack_require__) {
9329
9330"use strict";
9331/* harmony export (immutable) */ __webpack_exports__["a"] = range;
9332// Generate an integer Array containing an arithmetic progression. A port of
9333// the native Python `range()` function. See
9334// [the Python documentation](https://docs.python.org/library/functions.html#range).
9335function range(start, stop, step) {
9336 if (stop == null) {
9337 stop = start || 0;
9338 start = 0;
9339 }
9340 if (!step) {
9341 step = stop < start ? -1 : 1;
9342 }
9343
9344 var length = Math.max(Math.ceil((stop - start) / step), 0);
9345 var range = Array(length);
9346
9347 for (var idx = 0; idx < length; idx++, start += step) {
9348 range[idx] = start;
9349 }
9350
9351 return range;
9352}
9353
9354
9355/***/ }),
9356/* 298 */
9357/***/ (function(module, __webpack_exports__, __webpack_require__) {
9358
9359"use strict";
9360/* harmony export (immutable) */ __webpack_exports__["a"] = chunk;
9361/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(2);
9362
9363
9364// Chunk a single array into multiple arrays, each containing `count` or fewer
9365// items.
9366function chunk(array, count) {
9367 if (count == null || count < 1) return [];
9368 var result = [];
9369 var i = 0, length = array.length;
9370 while (i < length) {
9371 result.push(__WEBPACK_IMPORTED_MODULE_0__setup_js__["q" /* slice */].call(array, i, i += count));
9372 }
9373 return result;
9374}
9375
9376
9377/***/ }),
9378/* 299 */
9379/***/ (function(module, __webpack_exports__, __webpack_require__) {
9380
9381"use strict";
9382/* harmony export (immutable) */ __webpack_exports__["a"] = mixin;
9383/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(12);
9384/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__each_js__ = __webpack_require__(32);
9385/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__functions_js__ = __webpack_require__(142);
9386/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__setup_js__ = __webpack_require__(2);
9387/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__chainResult_js__ = __webpack_require__(176);
9388
9389
9390
9391
9392
9393
9394// Add your own custom functions to the Underscore object.
9395function mixin(obj) {
9396 Object(__WEBPACK_IMPORTED_MODULE_1__each_js__["a" /* default */])(Object(__WEBPACK_IMPORTED_MODULE_2__functions_js__["a" /* default */])(obj), function(name) {
9397 var func = __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */][name] = obj[name];
9398 __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].prototype[name] = function() {
9399 var args = [this._wrapped];
9400 __WEBPACK_IMPORTED_MODULE_3__setup_js__["o" /* push */].apply(args, arguments);
9401 return Object(__WEBPACK_IMPORTED_MODULE_4__chainResult_js__["a" /* default */])(this, func.apply(__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */], args));
9402 };
9403 });
9404 return __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */];
9405}
9406
9407
9408/***/ }),
9409/* 300 */
9410/***/ (function(module, __webpack_exports__, __webpack_require__) {
9411
9412"use strict";
9413/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(12);
9414/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__each_js__ = __webpack_require__(32);
9415/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__setup_js__ = __webpack_require__(2);
9416/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__chainResult_js__ = __webpack_require__(176);
9417
9418
9419
9420
9421
9422// Add all mutator `Array` functions to the wrapper.
9423Object(__WEBPACK_IMPORTED_MODULE_1__each_js__["a" /* default */])(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
9424 var method = __WEBPACK_IMPORTED_MODULE_2__setup_js__["a" /* ArrayProto */][name];
9425 __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].prototype[name] = function() {
9426 var obj = this._wrapped;
9427 if (obj != null) {
9428 method.apply(obj, arguments);
9429 if ((name === 'shift' || name === 'splice') && obj.length === 0) {
9430 delete obj[0];
9431 }
9432 }
9433 return Object(__WEBPACK_IMPORTED_MODULE_3__chainResult_js__["a" /* default */])(this, obj);
9434 };
9435});
9436
9437// Add all accessor `Array` functions to the wrapper.
9438Object(__WEBPACK_IMPORTED_MODULE_1__each_js__["a" /* default */])(['concat', 'join', 'slice'], function(name) {
9439 var method = __WEBPACK_IMPORTED_MODULE_2__setup_js__["a" /* ArrayProto */][name];
9440 __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].prototype[name] = function() {
9441 var obj = this._wrapped;
9442 if (obj != null) obj = method.apply(obj, arguments);
9443 return Object(__WEBPACK_IMPORTED_MODULE_3__chainResult_js__["a" /* default */])(this, obj);
9444 };
9445});
9446
9447/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */]);
9448
9449
9450/***/ }),
9451/* 301 */
9452/***/ (function(module, exports, __webpack_require__) {
9453
9454var core = __webpack_require__(1);
9455var $JSON = core.JSON || (core.JSON = { stringify: JSON.stringify });
9456module.exports = function stringify(it) { // eslint-disable-line no-unused-vars
9457 return $JSON.stringify.apply($JSON, arguments);
9458};
9459
9460
9461/***/ }),
9462/* 302 */
9463/***/ (function(module, exports, __webpack_require__) {
9464
9465__webpack_require__(303);
9466module.exports = __webpack_require__(1).Object.keys;
9467
9468
9469/***/ }),
9470/* 303 */
9471/***/ (function(module, exports, __webpack_require__) {
9472
9473// 19.1.2.14 Object.keys(O)
9474var toObject = __webpack_require__(29);
9475var $keys = __webpack_require__(49);
9476
9477__webpack_require__(70)('keys', function () {
9478 return function keys(it) {
9479 return $keys(toObject(it));
9480 };
9481});
9482
9483
9484/***/ }),
9485/* 304 */
9486/***/ (function(module, exports) {
9487
9488// Unique ID creation requires a high quality random # generator. In the
9489// browser this is a little complicated due to unknown quality of Math.random()
9490// and inconsistent support for the `crypto` API. We do the best we can via
9491// feature-detection
9492
9493// getRandomValues needs to be invoked in a context where "this" is a Crypto
9494// implementation. Also, find the complete implementation of crypto on IE11.
9495var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
9496 (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
9497
9498if (getRandomValues) {
9499 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
9500 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
9501
9502 module.exports = function whatwgRNG() {
9503 getRandomValues(rnds8);
9504 return rnds8;
9505 };
9506} else {
9507 // Math.random()-based (RNG)
9508 //
9509 // If all else fails, use Math.random(). It's fast, but is of unspecified
9510 // quality.
9511 var rnds = new Array(16);
9512
9513 module.exports = function mathRNG() {
9514 for (var i = 0, r; i < 16; i++) {
9515 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
9516 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
9517 }
9518
9519 return rnds;
9520 };
9521}
9522
9523
9524/***/ }),
9525/* 305 */
9526/***/ (function(module, exports) {
9527
9528/**
9529 * Convert array of 16 byte values to UUID string format of the form:
9530 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
9531 */
9532var byteToHex = [];
9533for (var i = 0; i < 256; ++i) {
9534 byteToHex[i] = (i + 0x100).toString(16).substr(1);
9535}
9536
9537function bytesToUuid(buf, offset) {
9538 var i = offset || 0;
9539 var bth = byteToHex;
9540 // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
9541 return ([bth[buf[i++]], bth[buf[i++]],
9542 bth[buf[i++]], bth[buf[i++]], '-',
9543 bth[buf[i++]], bth[buf[i++]], '-',
9544 bth[buf[i++]], bth[buf[i++]], '-',
9545 bth[buf[i++]], bth[buf[i++]], '-',
9546 bth[buf[i++]], bth[buf[i++]],
9547 bth[buf[i++]], bth[buf[i++]],
9548 bth[buf[i++]], bth[buf[i++]]]).join('');
9549}
9550
9551module.exports = bytesToUuid;
9552
9553
9554/***/ }),
9555/* 306 */
9556/***/ (function(module, exports, __webpack_require__) {
9557
9558"use strict";
9559
9560
9561/**
9562 * This is the common logic for both the Node.js and web browser
9563 * implementations of `debug()`.
9564 */
9565function setup(env) {
9566 createDebug.debug = createDebug;
9567 createDebug.default = createDebug;
9568 createDebug.coerce = coerce;
9569 createDebug.disable = disable;
9570 createDebug.enable = enable;
9571 createDebug.enabled = enabled;
9572 createDebug.humanize = __webpack_require__(307);
9573 Object.keys(env).forEach(function (key) {
9574 createDebug[key] = env[key];
9575 });
9576 /**
9577 * Active `debug` instances.
9578 */
9579
9580 createDebug.instances = [];
9581 /**
9582 * The currently active debug mode names, and names to skip.
9583 */
9584
9585 createDebug.names = [];
9586 createDebug.skips = [];
9587 /**
9588 * Map of special "%n" handling functions, for the debug "format" argument.
9589 *
9590 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
9591 */
9592
9593 createDebug.formatters = {};
9594 /**
9595 * Selects a color for a debug namespace
9596 * @param {String} namespace The namespace string for the for the debug instance to be colored
9597 * @return {Number|String} An ANSI color code for the given namespace
9598 * @api private
9599 */
9600
9601 function selectColor(namespace) {
9602 var hash = 0;
9603
9604 for (var i = 0; i < namespace.length; i++) {
9605 hash = (hash << 5) - hash + namespace.charCodeAt(i);
9606 hash |= 0; // Convert to 32bit integer
9607 }
9608
9609 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
9610 }
9611
9612 createDebug.selectColor = selectColor;
9613 /**
9614 * Create a debugger with the given `namespace`.
9615 *
9616 * @param {String} namespace
9617 * @return {Function}
9618 * @api public
9619 */
9620
9621 function createDebug(namespace) {
9622 var prevTime;
9623
9624 function debug() {
9625 // Disabled?
9626 if (!debug.enabled) {
9627 return;
9628 }
9629
9630 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
9631 args[_key] = arguments[_key];
9632 }
9633
9634 var self = debug; // Set `diff` timestamp
9635
9636 var curr = Number(new Date());
9637 var ms = curr - (prevTime || curr);
9638 self.diff = ms;
9639 self.prev = prevTime;
9640 self.curr = curr;
9641 prevTime = curr;
9642 args[0] = createDebug.coerce(args[0]);
9643
9644 if (typeof args[0] !== 'string') {
9645 // Anything else let's inspect with %O
9646 args.unshift('%O');
9647 } // Apply any `formatters` transformations
9648
9649
9650 var index = 0;
9651 args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
9652 // If we encounter an escaped % then don't increase the array index
9653 if (match === '%%') {
9654 return match;
9655 }
9656
9657 index++;
9658 var formatter = createDebug.formatters[format];
9659
9660 if (typeof formatter === 'function') {
9661 var val = args[index];
9662 match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
9663
9664 args.splice(index, 1);
9665 index--;
9666 }
9667
9668 return match;
9669 }); // Apply env-specific formatting (colors, etc.)
9670
9671 createDebug.formatArgs.call(self, args);
9672 var logFn = self.log || createDebug.log;
9673 logFn.apply(self, args);
9674 }
9675
9676 debug.namespace = namespace;
9677 debug.enabled = createDebug.enabled(namespace);
9678 debug.useColors = createDebug.useColors();
9679 debug.color = selectColor(namespace);
9680 debug.destroy = destroy;
9681 debug.extend = extend; // Debug.formatArgs = formatArgs;
9682 // debug.rawLog = rawLog;
9683 // env-specific initialization logic for debug instances
9684
9685 if (typeof createDebug.init === 'function') {
9686 createDebug.init(debug);
9687 }
9688
9689 createDebug.instances.push(debug);
9690 return debug;
9691 }
9692
9693 function destroy() {
9694 var index = createDebug.instances.indexOf(this);
9695
9696 if (index !== -1) {
9697 createDebug.instances.splice(index, 1);
9698 return true;
9699 }
9700
9701 return false;
9702 }
9703
9704 function extend(namespace, delimiter) {
9705 return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
9706 }
9707 /**
9708 * Enables a debug mode by namespaces. This can include modes
9709 * separated by a colon and wildcards.
9710 *
9711 * @param {String} namespaces
9712 * @api public
9713 */
9714
9715
9716 function enable(namespaces) {
9717 createDebug.save(namespaces);
9718 createDebug.names = [];
9719 createDebug.skips = [];
9720 var i;
9721 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
9722 var len = split.length;
9723
9724 for (i = 0; i < len; i++) {
9725 if (!split[i]) {
9726 // ignore empty strings
9727 continue;
9728 }
9729
9730 namespaces = split[i].replace(/\*/g, '.*?');
9731
9732 if (namespaces[0] === '-') {
9733 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
9734 } else {
9735 createDebug.names.push(new RegExp('^' + namespaces + '$'));
9736 }
9737 }
9738
9739 for (i = 0; i < createDebug.instances.length; i++) {
9740 var instance = createDebug.instances[i];
9741 instance.enabled = createDebug.enabled(instance.namespace);
9742 }
9743 }
9744 /**
9745 * Disable debug output.
9746 *
9747 * @api public
9748 */
9749
9750
9751 function disable() {
9752 createDebug.enable('');
9753 }
9754 /**
9755 * Returns true if the given mode name is enabled, false otherwise.
9756 *
9757 * @param {String} name
9758 * @return {Boolean}
9759 * @api public
9760 */
9761
9762
9763 function enabled(name) {
9764 if (name[name.length - 1] === '*') {
9765 return true;
9766 }
9767
9768 var i;
9769 var len;
9770
9771 for (i = 0, len = createDebug.skips.length; i < len; i++) {
9772 if (createDebug.skips[i].test(name)) {
9773 return false;
9774 }
9775 }
9776
9777 for (i = 0, len = createDebug.names.length; i < len; i++) {
9778 if (createDebug.names[i].test(name)) {
9779 return true;
9780 }
9781 }
9782
9783 return false;
9784 }
9785 /**
9786 * Coerce `val`.
9787 *
9788 * @param {Mixed} val
9789 * @return {Mixed}
9790 * @api private
9791 */
9792
9793
9794 function coerce(val) {
9795 if (val instanceof Error) {
9796 return val.stack || val.message;
9797 }
9798
9799 return val;
9800 }
9801
9802 createDebug.enable(createDebug.load());
9803 return createDebug;
9804}
9805
9806module.exports = setup;
9807
9808
9809
9810/***/ }),
9811/* 307 */
9812/***/ (function(module, exports) {
9813
9814/**
9815 * Helpers.
9816 */
9817
9818var s = 1000;
9819var m = s * 60;
9820var h = m * 60;
9821var d = h * 24;
9822var w = d * 7;
9823var y = d * 365.25;
9824
9825/**
9826 * Parse or format the given `val`.
9827 *
9828 * Options:
9829 *
9830 * - `long` verbose formatting [false]
9831 *
9832 * @param {String|Number} val
9833 * @param {Object} [options]
9834 * @throws {Error} throw an error if val is not a non-empty string or a number
9835 * @return {String|Number}
9836 * @api public
9837 */
9838
9839module.exports = function(val, options) {
9840 options = options || {};
9841 var type = typeof val;
9842 if (type === 'string' && val.length > 0) {
9843 return parse(val);
9844 } else if (type === 'number' && isFinite(val)) {
9845 return options.long ? fmtLong(val) : fmtShort(val);
9846 }
9847 throw new Error(
9848 'val is not a non-empty string or a valid number. val=' +
9849 JSON.stringify(val)
9850 );
9851};
9852
9853/**
9854 * Parse the given `str` and return milliseconds.
9855 *
9856 * @param {String} str
9857 * @return {Number}
9858 * @api private
9859 */
9860
9861function parse(str) {
9862 str = String(str);
9863 if (str.length > 100) {
9864 return;
9865 }
9866 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
9867 str
9868 );
9869 if (!match) {
9870 return;
9871 }
9872 var n = parseFloat(match[1]);
9873 var type = (match[2] || 'ms').toLowerCase();
9874 switch (type) {
9875 case 'years':
9876 case 'year':
9877 case 'yrs':
9878 case 'yr':
9879 case 'y':
9880 return n * y;
9881 case 'weeks':
9882 case 'week':
9883 case 'w':
9884 return n * w;
9885 case 'days':
9886 case 'day':
9887 case 'd':
9888 return n * d;
9889 case 'hours':
9890 case 'hour':
9891 case 'hrs':
9892 case 'hr':
9893 case 'h':
9894 return n * h;
9895 case 'minutes':
9896 case 'minute':
9897 case 'mins':
9898 case 'min':
9899 case 'm':
9900 return n * m;
9901 case 'seconds':
9902 case 'second':
9903 case 'secs':
9904 case 'sec':
9905 case 's':
9906 return n * s;
9907 case 'milliseconds':
9908 case 'millisecond':
9909 case 'msecs':
9910 case 'msec':
9911 case 'ms':
9912 return n;
9913 default:
9914 return undefined;
9915 }
9916}
9917
9918/**
9919 * Short format for `ms`.
9920 *
9921 * @param {Number} ms
9922 * @return {String}
9923 * @api private
9924 */
9925
9926function fmtShort(ms) {
9927 var msAbs = Math.abs(ms);
9928 if (msAbs >= d) {
9929 return Math.round(ms / d) + 'd';
9930 }
9931 if (msAbs >= h) {
9932 return Math.round(ms / h) + 'h';
9933 }
9934 if (msAbs >= m) {
9935 return Math.round(ms / m) + 'm';
9936 }
9937 if (msAbs >= s) {
9938 return Math.round(ms / s) + 's';
9939 }
9940 return ms + 'ms';
9941}
9942
9943/**
9944 * Long format for `ms`.
9945 *
9946 * @param {Number} ms
9947 * @return {String}
9948 * @api private
9949 */
9950
9951function fmtLong(ms) {
9952 var msAbs = Math.abs(ms);
9953 if (msAbs >= d) {
9954 return plural(ms, msAbs, d, 'day');
9955 }
9956 if (msAbs >= h) {
9957 return plural(ms, msAbs, h, 'hour');
9958 }
9959 if (msAbs >= m) {
9960 return plural(ms, msAbs, m, 'minute');
9961 }
9962 if (msAbs >= s) {
9963 return plural(ms, msAbs, s, 'second');
9964 }
9965 return ms + ' ms';
9966}
9967
9968/**
9969 * Pluralization helper.
9970 */
9971
9972function plural(ms, msAbs, n, name) {
9973 var isPlural = msAbs >= n * 1.5;
9974 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
9975}
9976
9977
9978/***/ }),
9979/* 308 */
9980/***/ (function(module, exports, __webpack_require__) {
9981
9982__webpack_require__(309);
9983module.exports = __webpack_require__(1).Object.getPrototypeOf;
9984
9985
9986/***/ }),
9987/* 309 */
9988/***/ (function(module, exports, __webpack_require__) {
9989
9990// 19.1.2.9 Object.getPrototypeOf(O)
9991var toObject = __webpack_require__(29);
9992var $getPrototypeOf = __webpack_require__(119);
9993
9994__webpack_require__(70)('getPrototypeOf', function () {
9995 return function getPrototypeOf(it) {
9996 return $getPrototypeOf(toObject(it));
9997 };
9998});
9999
10000
10001/***/ }),
10002/* 310 */
10003/***/ (function(module, exports, __webpack_require__) {
10004
10005"use strict";
10006
10007
10008var _defineProperty = __webpack_require__(71);
10009
10010var _defineProperty2 = _interopRequireDefault(_defineProperty);
10011
10012function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
10013
10014var AV = __webpack_require__(42);
10015var AppRouter = __webpack_require__(313);
10016
10017var _require = __webpack_require__(19),
10018 isNullOrUndefined = _require.isNullOrUndefined;
10019
10020var _require2 = __webpack_require__(0),
10021 extend = _require2.extend,
10022 isObject = _require2.isObject,
10023 isEmpty = _require2.isEmpty;
10024
10025var isCNApp = function isCNApp(appId) {
10026 return appId.slice(-9) !== '-MdYXbMMI';
10027};
10028
10029var fillServerURLs = function fillServerURLs(url) {
10030 return {
10031 push: url,
10032 stats: url,
10033 engine: url,
10034 api: url,
10035 rtm: url
10036 };
10037};
10038
10039function getDefaultServerURLs(appId) {
10040 if (isCNApp(appId)) {
10041 return {};
10042 }
10043 var id = appId.slice(0, 8).toLowerCase();
10044 var domain = 'lncldglobal.com';
10045 return {
10046 push: 'https://' + id + '.push.' + domain,
10047 stats: 'https://' + id + '.stats.' + domain,
10048 engine: 'https://' + id + '.engine.' + domain,
10049 api: 'https://' + id + '.api.' + domain,
10050 rtm: 'https://' + id + '.rtm.' + domain
10051 };
10052}
10053
10054var _disableAppRouter = false;
10055var _initialized = false;
10056
10057/**
10058 * URLs for services
10059 * @typedef {Object} ServerURLs
10060 * @property {String} [api] serverURL for API service
10061 * @property {String} [engine] serverURL for engine service
10062 * @property {String} [stats] serverURL for stats service
10063 * @property {String} [push] serverURL for push service
10064 * @property {String} [rtm] serverURL for LiveQuery service
10065 */
10066
10067/**
10068 * Call this method first to set up your authentication tokens for AV.
10069 * You can get your app keys from the LeanCloud dashboard on http://leancloud.cn .
10070 * @function AV.init
10071 * @param {Object} options
10072 * @param {String} options.appId application id
10073 * @param {String} options.appKey application key
10074 * @param {String} [options.masterKey] application master key
10075 * @param {Boolean} [options.production]
10076 * @param {String|ServerURLs} [options.serverURL] URLs for services. if a string was given, it will be applied for all services.
10077 * @param {Boolean} [options.disableCurrentUser]
10078 */
10079AV.init = function init(options) {
10080 if (!isObject(options)) {
10081 return AV.init({
10082 appId: options,
10083 appKey: arguments.length <= 1 ? undefined : arguments[1],
10084 masterKey: arguments.length <= 2 ? undefined : arguments[2]
10085 });
10086 }
10087 var appId = options.appId,
10088 appKey = options.appKey,
10089 masterKey = options.masterKey,
10090 hookKey = options.hookKey,
10091 serverURL = options.serverURL,
10092 _options$serverURLs = options.serverURLs,
10093 serverURLs = _options$serverURLs === undefined ? serverURL : _options$serverURLs,
10094 disableCurrentUser = options.disableCurrentUser,
10095 production = options.production,
10096 realtime = options.realtime;
10097
10098 if (_initialized) console.warn('Initializing LeanCloud Storage SDK which has already been initialized. Reinitializing the SDK might cause problems like unexpected cross-app data writing and invalid relations.');
10099 if (!appId) throw new TypeError('appId must be a string');
10100 if (!appKey) throw new TypeError('appKey must be a string');
10101 if ('Browser' !== 'NODE_JS' && masterKey) console.warn('MasterKey is not supposed to be used at client side.');
10102 if (isCNApp(appId)) {
10103 if (!serverURLs && isEmpty(AV._config.serverURLs)) {
10104 throw new TypeError('serverURL option is required for apps from CN region');
10105 }
10106 }
10107 if (appId !== AV._config.applicationId) {
10108 // overwrite all keys when reinitializing as a new app
10109 AV._config.masterKey = masterKey;
10110 AV._config.hookKey = hookKey;
10111 } else {
10112 if (masterKey) AV._config.masterKey = masterKey;
10113 if (hookKey) AV._config.hookKey = hookKey;
10114 }
10115 AV._config.applicationId = appId;
10116 AV._config.applicationKey = appKey;
10117 if (!isNullOrUndefined(production)) {
10118 AV.setProduction(production);
10119 }
10120 if (typeof disableCurrentUser !== 'undefined') AV._config.disableCurrentUser = disableCurrentUser;
10121 var disableAppRouter = _disableAppRouter || typeof serverURLs !== 'undefined';
10122 if (!disableAppRouter) {
10123 AV._appRouter = new AppRouter(AV);
10124 }
10125 AV._setServerURLs(extend({}, getDefaultServerURLs(appId), AV._config.serverURLs, typeof serverURLs === 'string' ? fillServerURLs(serverURLs) : serverURLs), disableAppRouter);
10126 if (realtime) {
10127 AV._config.realtime = realtime;
10128 } else if (AV._sharedConfig.liveQueryRealtime) {
10129 var _AV$_config$serverURL = AV._config.serverURLs,
10130 api = _AV$_config$serverURL.api,
10131 rtm = _AV$_config$serverURL.rtm;
10132
10133 AV._config.realtime = new AV._sharedConfig.liveQueryRealtime({
10134 appId: appId,
10135 appKey: appKey,
10136 server: {
10137 api: api,
10138 RTMRouter: rtm
10139 }
10140 });
10141 }
10142 _initialized = true;
10143};
10144
10145// If we're running in node.js, allow using the master key.
10146if (false) {
10147 AV.Cloud = AV.Cloud || {};
10148 /**
10149 * Switches the LeanCloud SDK to using the Master key. The Master key grants
10150 * priveleged access to the data in LeanCloud and can be used to bypass ACLs and
10151 * other restrictions that are applied to the client SDKs.
10152 * <p><strong><em>Available in Cloud Code and Node.js only.</em></strong>
10153 * </p>
10154 */
10155 AV.Cloud.useMasterKey = function () {
10156 AV._config.useMasterKey = true;
10157 };
10158}
10159
10160/**
10161 * Call this method to set production environment variable.
10162 * @function AV.setProduction
10163 * @param {Boolean} production True is production environment,and
10164 * it's true by default.
10165 */
10166AV.setProduction = function (production) {
10167 if (!isNullOrUndefined(production)) {
10168 AV._config.production = production ? 1 : 0;
10169 } else {
10170 // change to default value
10171 AV._config.production = null;
10172 }
10173};
10174
10175AV._setServerURLs = function (urls) {
10176 var disableAppRouter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
10177
10178 if (typeof urls !== 'string') {
10179 extend(AV._config.serverURLs, urls);
10180 } else {
10181 AV._config.serverURLs = fillServerURLs(urls);
10182 }
10183 if (disableAppRouter) {
10184 if (AV._appRouter) {
10185 AV._appRouter.disable();
10186 } else {
10187 _disableAppRouter = true;
10188 }
10189 }
10190};
10191/**
10192 * Set server URLs for services.
10193 * @function AV.setServerURL
10194 * @since 4.3.0
10195 * @param {String|ServerURLs} urls URLs for services. if a string was given, it will be applied for all services.
10196 * You can also set them when initializing SDK with `options.serverURL`
10197 */
10198AV.setServerURL = function (urls) {
10199 return AV._setServerURLs(urls);
10200};
10201AV.setServerURLs = AV.setServerURL;
10202
10203AV.keepErrorRawMessage = function (value) {
10204 AV._sharedConfig.keepErrorRawMessage = value;
10205};
10206
10207/**
10208 * Set a deadline for requests to complete.
10209 * Note that file upload requests are not affected.
10210 * @function AV.setRequestTimeout
10211 * @since 3.6.0
10212 * @param {number} ms
10213 */
10214AV.setRequestTimeout = function (ms) {
10215 AV._config.requestTimeout = ms;
10216};
10217
10218// backword compatible
10219AV.initialize = AV.init;
10220
10221var defineConfig = function defineConfig(property) {
10222 return (0, _defineProperty2.default)(AV, property, {
10223 get: function get() {
10224 return AV._config[property];
10225 },
10226 set: function set(value) {
10227 AV._config[property] = value;
10228 }
10229 });
10230};
10231
10232['applicationId', 'applicationKey', 'masterKey', 'hookKey'].forEach(defineConfig);
10233
10234/***/ }),
10235/* 311 */
10236/***/ (function(module, exports, __webpack_require__) {
10237
10238__webpack_require__(312);
10239var $Object = __webpack_require__(1).Object;
10240module.exports = function defineProperty(it, key, desc) {
10241 return $Object.defineProperty(it, key, desc);
10242};
10243
10244
10245/***/ }),
10246/* 312 */
10247/***/ (function(module, exports, __webpack_require__) {
10248
10249var $export = __webpack_require__(4);
10250// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
10251$export($export.S + $export.F * !__webpack_require__(16), 'Object', { defineProperty: __webpack_require__(20).f });
10252
10253
10254/***/ }),
10255/* 313 */
10256/***/ (function(module, exports, __webpack_require__) {
10257
10258"use strict";
10259
10260
10261var ajax = __webpack_require__(72);
10262var Cache = __webpack_require__(182);
10263
10264function AppRouter(AV) {
10265 var _this = this;
10266
10267 this.AV = AV;
10268 this.lockedUntil = 0;
10269 Cache.getAsync('serverURLs').then(function (data) {
10270 if (_this.disabled) return;
10271 if (!data) return _this.lock(0);
10272 var serverURLs = data.serverURLs,
10273 lockedUntil = data.lockedUntil;
10274
10275 _this.AV._setServerURLs(serverURLs, false);
10276 _this.lockedUntil = lockedUntil;
10277 }).catch(function () {
10278 return _this.lock(0);
10279 });
10280}
10281
10282AppRouter.prototype.disable = function disable() {
10283 this.disabled = true;
10284};
10285AppRouter.prototype.lock = function lock(ttl) {
10286 this.lockedUntil = Date.now() + ttl;
10287};
10288AppRouter.prototype.refresh = function refresh() {
10289 var _this2 = this;
10290
10291 if (this.disabled) return;
10292 if (Date.now() < this.lockedUntil) return;
10293 this.lock(10);
10294 var url = 'https://app-router.com/2/route';
10295 return ajax({
10296 method: 'get',
10297 url: url,
10298 query: {
10299 appId: this.AV.applicationId
10300 }
10301 }).then(function (servers) {
10302 if (_this2.disabled) return;
10303 var ttl = servers.ttl;
10304 if (!ttl) throw new Error('missing ttl');
10305 ttl = ttl * 1000;
10306 var protocal = 'https://';
10307 var serverURLs = {
10308 push: protocal + servers.push_server,
10309 stats: protocal + servers.stats_server,
10310 engine: protocal + servers.engine_server,
10311 api: protocal + servers.api_server
10312 };
10313 _this2.AV._setServerURLs(serverURLs, false);
10314 _this2.lock(ttl);
10315 return Cache.setAsync('serverURLs', {
10316 serverURLs: serverURLs,
10317 lockedUntil: _this2.lockedUntil
10318 }, ttl);
10319 }).catch(function (error) {
10320 // bypass all errors
10321 console.warn('refresh server URLs failed: ' + error.message);
10322 _this2.lock(600);
10323 });
10324};
10325
10326module.exports = AppRouter;
10327
10328/***/ }),
10329/* 314 */
10330/***/ (function(module, exports, __webpack_require__) {
10331
10332__webpack_require__(35);
10333__webpack_require__(37);
10334module.exports = __webpack_require__(108).f('iterator');
10335
10336
10337/***/ }),
10338/* 315 */
10339/***/ (function(module, exports, __webpack_require__) {
10340
10341__webpack_require__(183);
10342__webpack_require__(59);
10343__webpack_require__(318);
10344__webpack_require__(319);
10345module.exports = __webpack_require__(1).Symbol;
10346
10347
10348/***/ }),
10349/* 316 */
10350/***/ (function(module, exports, __webpack_require__) {
10351
10352// all enumerable object keys, includes symbols
10353var getKeys = __webpack_require__(49);
10354var gOPS = __webpack_require__(74);
10355var pIE = __webpack_require__(75);
10356module.exports = function (it) {
10357 var result = getKeys(it);
10358 var getSymbols = gOPS.f;
10359 if (getSymbols) {
10360 var symbols = getSymbols(it);
10361 var isEnum = pIE.f;
10362 var i = 0;
10363 var key;
10364 while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);
10365 } return result;
10366};
10367
10368
10369/***/ }),
10370/* 317 */
10371/***/ (function(module, exports, __webpack_require__) {
10372
10373// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
10374var toIObject = __webpack_require__(26);
10375var gOPN = __webpack_require__(110).f;
10376var toString = {}.toString;
10377
10378var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
10379 ? Object.getOwnPropertyNames(window) : [];
10380
10381var getWindowNames = function (it) {
10382 try {
10383 return gOPN(it);
10384 } catch (e) {
10385 return windowNames.slice();
10386 }
10387};
10388
10389module.exports.f = function getOwnPropertyNames(it) {
10390 return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
10391};
10392
10393
10394/***/ }),
10395/* 318 */
10396/***/ (function(module, exports, __webpack_require__) {
10397
10398__webpack_require__(109)('asyncIterator');
10399
10400
10401/***/ }),
10402/* 319 */
10403/***/ (function(module, exports, __webpack_require__) {
10404
10405__webpack_require__(109)('observable');
10406
10407
10408/***/ }),
10409/* 320 */
10410/***/ (function(module, exports, __webpack_require__) {
10411
10412"use strict";
10413
10414
10415var _ = __webpack_require__(0);
10416
10417module.exports = function (AV) {
10418 var eventSplitter = /\s+/;
10419 var slice = Array.prototype.slice;
10420
10421 /**
10422 * @class
10423 *
10424 * <p>AV.Events is a fork of Backbone's Events module, provided for your
10425 * convenience.</p>
10426 *
10427 * <p>A module that can be mixed in to any object in order to provide
10428 * it with custom events. You may bind callback functions to an event
10429 * with `on`, or remove these functions with `off`.
10430 * Triggering an event fires all callbacks in the order that `on` was
10431 * called.
10432 *
10433 * @private
10434 * @example
10435 * var object = {};
10436 * _.extend(object, AV.Events);
10437 * object.on('expand', function(){ alert('expanded'); });
10438 * object.trigger('expand');</pre></p>
10439 *
10440 */
10441 AV.Events = {
10442 /**
10443 * Bind one or more space separated events, `events`, to a `callback`
10444 * function. Passing `"all"` will bind the callback to all events fired.
10445 */
10446 on: function on(events, callback, context) {
10447 var calls, event, node, tail, list;
10448 if (!callback) {
10449 return this;
10450 }
10451 events = events.split(eventSplitter);
10452 calls = this._callbacks || (this._callbacks = {});
10453
10454 // Create an immutable callback list, allowing traversal during
10455 // modification. The tail is an empty object that will always be used
10456 // as the next node.
10457 event = events.shift();
10458 while (event) {
10459 list = calls[event];
10460 node = list ? list.tail : {};
10461 node.next = tail = {};
10462 node.context = context;
10463 node.callback = callback;
10464 calls[event] = { tail: tail, next: list ? list.next : node };
10465 event = events.shift();
10466 }
10467
10468 return this;
10469 },
10470
10471 /**
10472 * Remove one or many callbacks. If `context` is null, removes all callbacks
10473 * with that function. If `callback` is null, removes all callbacks for the
10474 * event. If `events` is null, removes all bound callbacks for all events.
10475 */
10476 off: function off(events, callback, context) {
10477 var event, calls, node, tail, cb, ctx;
10478
10479 // No events, or removing *all* events.
10480 if (!(calls = this._callbacks)) {
10481 return;
10482 }
10483 if (!(events || callback || context)) {
10484 delete this._callbacks;
10485 return this;
10486 }
10487
10488 // Loop through the listed events and contexts, splicing them out of the
10489 // linked list of callbacks if appropriate.
10490 events = events ? events.split(eventSplitter) : _.keys(calls);
10491 event = events.shift();
10492 while (event) {
10493 node = calls[event];
10494 delete calls[event];
10495 if (!node || !(callback || context)) {
10496 continue;
10497 }
10498 // Create a new list, omitting the indicated callbacks.
10499 tail = node.tail;
10500 node = node.next;
10501 while (node !== tail) {
10502 cb = node.callback;
10503 ctx = node.context;
10504 if (callback && cb !== callback || context && ctx !== context) {
10505 this.on(event, cb, ctx);
10506 }
10507 node = node.next;
10508 }
10509 event = events.shift();
10510 }
10511
10512 return this;
10513 },
10514
10515 /**
10516 * Trigger one or many events, firing all bound callbacks. Callbacks are
10517 * passed the same arguments as `trigger` is, apart from the event name
10518 * (unless you're listening on `"all"`, which will cause your callback to
10519 * receive the true name of the event as the first argument).
10520 */
10521 trigger: function trigger(events) {
10522 var event, node, calls, tail, args, all, rest;
10523 if (!(calls = this._callbacks)) {
10524 return this;
10525 }
10526 all = calls.all;
10527 events = events.split(eventSplitter);
10528 rest = slice.call(arguments, 1);
10529
10530 // For each event, walk through the linked list of callbacks twice,
10531 // first to trigger the event, then to trigger any `"all"` callbacks.
10532 event = events.shift();
10533 while (event) {
10534 node = calls[event];
10535 if (node) {
10536 tail = node.tail;
10537 while ((node = node.next) !== tail) {
10538 node.callback.apply(node.context || this, rest);
10539 }
10540 }
10541 node = all;
10542 if (node) {
10543 tail = node.tail;
10544 args = [event].concat(rest);
10545 while ((node = node.next) !== tail) {
10546 node.callback.apply(node.context || this, args);
10547 }
10548 }
10549 event = events.shift();
10550 }
10551
10552 return this;
10553 }
10554 };
10555
10556 /**
10557 * @function
10558 */
10559 AV.Events.bind = AV.Events.on;
10560
10561 /**
10562 * @function
10563 */
10564 AV.Events.unbind = AV.Events.off;
10565};
10566
10567/***/ }),
10568/* 321 */
10569/***/ (function(module, exports, __webpack_require__) {
10570
10571"use strict";
10572
10573
10574var _promise = __webpack_require__(3);
10575
10576var _promise2 = _interopRequireDefault(_promise);
10577
10578function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
10579
10580var _ = __webpack_require__(0);
10581
10582/*global navigator: false */
10583module.exports = function (AV) {
10584 /**
10585 * Creates a new GeoPoint with any of the following forms:<br>
10586 * @example
10587 * new GeoPoint(otherGeoPoint)
10588 * new GeoPoint(30, 30)
10589 * new GeoPoint([30, 30])
10590 * new GeoPoint({latitude: 30, longitude: 30})
10591 * new GeoPoint() // defaults to (0, 0)
10592 * @class
10593 *
10594 * <p>Represents a latitude / longitude point that may be associated
10595 * with a key in a AVObject or used as a reference point for geo queries.
10596 * This allows proximity-based queries on the key.</p>
10597 *
10598 * <p>Only one key in a class may contain a GeoPoint.</p>
10599 *
10600 * <p>Example:<pre>
10601 * var point = new AV.GeoPoint(30.0, -20.0);
10602 * var object = new AV.Object("PlaceObject");
10603 * object.set("location", point);
10604 * object.save();</pre></p>
10605 */
10606 AV.GeoPoint = function (arg1, arg2) {
10607 if (_.isArray(arg1)) {
10608 AV.GeoPoint._validate(arg1[0], arg1[1]);
10609 this.latitude = arg1[0];
10610 this.longitude = arg1[1];
10611 } else if (_.isObject(arg1)) {
10612 AV.GeoPoint._validate(arg1.latitude, arg1.longitude);
10613 this.latitude = arg1.latitude;
10614 this.longitude = arg1.longitude;
10615 } else if (_.isNumber(arg1) && _.isNumber(arg2)) {
10616 AV.GeoPoint._validate(arg1, arg2);
10617 this.latitude = arg1;
10618 this.longitude = arg2;
10619 } else {
10620 this.latitude = 0;
10621 this.longitude = 0;
10622 }
10623
10624 // Add properties so that anyone using Webkit or Mozilla will get an error
10625 // if they try to set values that are out of bounds.
10626 var self = this;
10627 if (this.__defineGetter__ && this.__defineSetter__) {
10628 // Use _latitude and _longitude to actually store the values, and add
10629 // getters and setters for latitude and longitude.
10630 this._latitude = this.latitude;
10631 this._longitude = this.longitude;
10632 this.__defineGetter__('latitude', function () {
10633 return self._latitude;
10634 });
10635 this.__defineGetter__('longitude', function () {
10636 return self._longitude;
10637 });
10638 this.__defineSetter__('latitude', function (val) {
10639 AV.GeoPoint._validate(val, self.longitude);
10640 self._latitude = val;
10641 });
10642 this.__defineSetter__('longitude', function (val) {
10643 AV.GeoPoint._validate(self.latitude, val);
10644 self._longitude = val;
10645 });
10646 }
10647 };
10648
10649 /**
10650 * @lends AV.GeoPoint.prototype
10651 * @property {float} latitude North-south portion of the coordinate, in range
10652 * [-90, 90]. Throws an exception if set out of range in a modern browser.
10653 * @property {float} longitude East-west portion of the coordinate, in range
10654 * [-180, 180]. Throws if set out of range in a modern browser.
10655 */
10656
10657 /**
10658 * Throws an exception if the given lat-long is out of bounds.
10659 * @private
10660 */
10661 AV.GeoPoint._validate = function (latitude, longitude) {
10662 if (latitude < -90.0) {
10663 throw new Error('AV.GeoPoint latitude ' + latitude + ' < -90.0.');
10664 }
10665 if (latitude > 90.0) {
10666 throw new Error('AV.GeoPoint latitude ' + latitude + ' > 90.0.');
10667 }
10668 if (longitude < -180.0) {
10669 throw new Error('AV.GeoPoint longitude ' + longitude + ' < -180.0.');
10670 }
10671 if (longitude > 180.0) {
10672 throw new Error('AV.GeoPoint longitude ' + longitude + ' > 180.0.');
10673 }
10674 };
10675
10676 /**
10677 * Creates a GeoPoint with the user's current location, if available.
10678 * @return {Promise.<AV.GeoPoint>}
10679 */
10680 AV.GeoPoint.current = function () {
10681 return new _promise2.default(function (resolve, reject) {
10682 navigator.geolocation.getCurrentPosition(function (location) {
10683 resolve(new AV.GeoPoint({
10684 latitude: location.coords.latitude,
10685 longitude: location.coords.longitude
10686 }));
10687 }, reject);
10688 });
10689 };
10690
10691 _.extend(AV.GeoPoint.prototype,
10692 /** @lends AV.GeoPoint.prototype */{
10693 /**
10694 * Returns a JSON representation of the GeoPoint, suitable for AV.
10695 * @return {Object}
10696 */
10697 toJSON: function toJSON() {
10698 AV.GeoPoint._validate(this.latitude, this.longitude);
10699 return {
10700 __type: 'GeoPoint',
10701 latitude: this.latitude,
10702 longitude: this.longitude
10703 };
10704 },
10705
10706 /**
10707 * Returns the distance from this GeoPoint to another in radians.
10708 * @param {AV.GeoPoint} point the other AV.GeoPoint.
10709 * @return {Number}
10710 */
10711 radiansTo: function radiansTo(point) {
10712 var d2r = Math.PI / 180.0;
10713 var lat1rad = this.latitude * d2r;
10714 var long1rad = this.longitude * d2r;
10715 var lat2rad = point.latitude * d2r;
10716 var long2rad = point.longitude * d2r;
10717 var deltaLat = lat1rad - lat2rad;
10718 var deltaLong = long1rad - long2rad;
10719 var sinDeltaLatDiv2 = Math.sin(deltaLat / 2);
10720 var sinDeltaLongDiv2 = Math.sin(deltaLong / 2);
10721 // Square of half the straight line chord distance between both points.
10722 var a = sinDeltaLatDiv2 * sinDeltaLatDiv2 + Math.cos(lat1rad) * Math.cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2;
10723 a = Math.min(1.0, a);
10724 return 2 * Math.asin(Math.sqrt(a));
10725 },
10726
10727 /**
10728 * Returns the distance from this GeoPoint to another in kilometers.
10729 * @param {AV.GeoPoint} point the other AV.GeoPoint.
10730 * @return {Number}
10731 */
10732 kilometersTo: function kilometersTo(point) {
10733 return this.radiansTo(point) * 6371.0;
10734 },
10735
10736 /**
10737 * Returns the distance from this GeoPoint to another in miles.
10738 * @param {AV.GeoPoint} point the other AV.GeoPoint.
10739 * @return {Number}
10740 */
10741 milesTo: function milesTo(point) {
10742 return this.radiansTo(point) * 3958.8;
10743 }
10744 });
10745};
10746
10747/***/ }),
10748/* 322 */
10749/***/ (function(module, exports, __webpack_require__) {
10750
10751"use strict";
10752
10753
10754var _ = __webpack_require__(0);
10755
10756module.exports = function (AV) {
10757 var PUBLIC_KEY = '*';
10758
10759 /**
10760 * Creates a new ACL.
10761 * If no argument is given, the ACL has no permissions for anyone.
10762 * If the argument is a AV.User, the ACL will have read and write
10763 * permission for only that user.
10764 * If the argument is any other JSON object, that object will be interpretted
10765 * as a serialized ACL created with toJSON().
10766 * @see AV.Object#setACL
10767 * @class
10768 *
10769 * <p>An ACL, or Access Control List can be added to any
10770 * <code>AV.Object</code> to restrict access to only a subset of users
10771 * of your application.</p>
10772 */
10773 AV.ACL = function (arg1) {
10774 var self = this;
10775 self.permissionsById = {};
10776 if (_.isObject(arg1)) {
10777 if (arg1 instanceof AV.User) {
10778 self.setReadAccess(arg1, true);
10779 self.setWriteAccess(arg1, true);
10780 } else {
10781 if (_.isFunction(arg1)) {
10782 throw new Error('AV.ACL() called with a function. Did you forget ()?');
10783 }
10784 AV._objectEach(arg1, function (accessList, userId) {
10785 if (!_.isString(userId)) {
10786 throw new Error('Tried to create an ACL with an invalid userId.');
10787 }
10788 self.permissionsById[userId] = {};
10789 AV._objectEach(accessList, function (allowed, permission) {
10790 if (permission !== 'read' && permission !== 'write') {
10791 throw new Error('Tried to create an ACL with an invalid permission type.');
10792 }
10793 if (!_.isBoolean(allowed)) {
10794 throw new Error('Tried to create an ACL with an invalid permission value.');
10795 }
10796 self.permissionsById[userId][permission] = allowed;
10797 });
10798 });
10799 }
10800 }
10801 };
10802
10803 /**
10804 * Returns a JSON-encoded version of the ACL.
10805 * @return {Object}
10806 */
10807 AV.ACL.prototype.toJSON = function () {
10808 return _.clone(this.permissionsById);
10809 };
10810
10811 AV.ACL.prototype._setAccess = function (accessType, userId, allowed) {
10812 if (userId instanceof AV.User) {
10813 userId = userId.id;
10814 } else if (userId instanceof AV.Role) {
10815 userId = 'role:' + userId.getName();
10816 }
10817 if (!_.isString(userId)) {
10818 throw new Error('userId must be a string.');
10819 }
10820 if (!_.isBoolean(allowed)) {
10821 throw new Error('allowed must be either true or false.');
10822 }
10823 var permissions = this.permissionsById[userId];
10824 if (!permissions) {
10825 if (!allowed) {
10826 // The user already doesn't have this permission, so no action needed.
10827 return;
10828 } else {
10829 permissions = {};
10830 this.permissionsById[userId] = permissions;
10831 }
10832 }
10833
10834 if (allowed) {
10835 this.permissionsById[userId][accessType] = true;
10836 } else {
10837 delete permissions[accessType];
10838 if (_.isEmpty(permissions)) {
10839 delete this.permissionsById[userId];
10840 }
10841 }
10842 };
10843
10844 AV.ACL.prototype._getAccess = function (accessType, userId) {
10845 if (userId instanceof AV.User) {
10846 userId = userId.id;
10847 } else if (userId instanceof AV.Role) {
10848 userId = 'role:' + userId.getName();
10849 }
10850 var permissions = this.permissionsById[userId];
10851 if (!permissions) {
10852 return false;
10853 }
10854 return permissions[accessType] ? true : false;
10855 };
10856
10857 /**
10858 * Set whether the given user is allowed to read this object.
10859 * @param userId An instance of AV.User or its objectId.
10860 * @param {Boolean} allowed Whether that user should have read access.
10861 */
10862 AV.ACL.prototype.setReadAccess = function (userId, allowed) {
10863 this._setAccess('read', userId, allowed);
10864 };
10865
10866 /**
10867 * Get whether the given user id is *explicitly* allowed to read this object.
10868 * Even if this returns false, the user may still be able to access it if
10869 * getPublicReadAccess returns true or a role that the user belongs to has
10870 * write access.
10871 * @param userId An instance of AV.User or its objectId, or a AV.Role.
10872 * @return {Boolean}
10873 */
10874 AV.ACL.prototype.getReadAccess = function (userId) {
10875 return this._getAccess('read', userId);
10876 };
10877
10878 /**
10879 * Set whether the given user id is allowed to write this object.
10880 * @param userId An instance of AV.User or its objectId, or a AV.Role..
10881 * @param {Boolean} allowed Whether that user should have write access.
10882 */
10883 AV.ACL.prototype.setWriteAccess = function (userId, allowed) {
10884 this._setAccess('write', userId, allowed);
10885 };
10886
10887 /**
10888 * Get whether the given user id is *explicitly* allowed to write this object.
10889 * Even if this returns false, the user may still be able to write it if
10890 * getPublicWriteAccess returns true or a role that the user belongs to has
10891 * write access.
10892 * @param userId An instance of AV.User or its objectId, or a AV.Role.
10893 * @return {Boolean}
10894 */
10895 AV.ACL.prototype.getWriteAccess = function (userId) {
10896 return this._getAccess('write', userId);
10897 };
10898
10899 /**
10900 * Set whether the public is allowed to read this object.
10901 * @param {Boolean} allowed
10902 */
10903 AV.ACL.prototype.setPublicReadAccess = function (allowed) {
10904 this.setReadAccess(PUBLIC_KEY, allowed);
10905 };
10906
10907 /**
10908 * Get whether the public is allowed to read this object.
10909 * @return {Boolean}
10910 */
10911 AV.ACL.prototype.getPublicReadAccess = function () {
10912 return this.getReadAccess(PUBLIC_KEY);
10913 };
10914
10915 /**
10916 * Set whether the public is allowed to write this object.
10917 * @param {Boolean} allowed
10918 */
10919 AV.ACL.prototype.setPublicWriteAccess = function (allowed) {
10920 this.setWriteAccess(PUBLIC_KEY, allowed);
10921 };
10922
10923 /**
10924 * Get whether the public is allowed to write this object.
10925 * @return {Boolean}
10926 */
10927 AV.ACL.prototype.getPublicWriteAccess = function () {
10928 return this.getWriteAccess(PUBLIC_KEY);
10929 };
10930
10931 /**
10932 * Get whether users belonging to the given role are allowed
10933 * to read this object. Even if this returns false, the role may
10934 * still be able to write it if a parent role has read access.
10935 *
10936 * @param role The name of the role, or a AV.Role object.
10937 * @return {Boolean} true if the role has read access. false otherwise.
10938 * @throws {String} If role is neither a AV.Role nor a String.
10939 */
10940 AV.ACL.prototype.getRoleReadAccess = function (role) {
10941 if (role instanceof AV.Role) {
10942 // Normalize to the String name
10943 role = role.getName();
10944 }
10945 if (_.isString(role)) {
10946 return this.getReadAccess('role:' + role);
10947 }
10948 throw new Error('role must be a AV.Role or a String');
10949 };
10950
10951 /**
10952 * Get whether users belonging to the given role are allowed
10953 * to write this object. Even if this returns false, the role may
10954 * still be able to write it if a parent role has write access.
10955 *
10956 * @param role The name of the role, or a AV.Role object.
10957 * @return {Boolean} true if the role has write access. false otherwise.
10958 * @throws {String} If role is neither a AV.Role nor a String.
10959 */
10960 AV.ACL.prototype.getRoleWriteAccess = function (role) {
10961 if (role instanceof AV.Role) {
10962 // Normalize to the String name
10963 role = role.getName();
10964 }
10965 if (_.isString(role)) {
10966 return this.getWriteAccess('role:' + role);
10967 }
10968 throw new Error('role must be a AV.Role or a String');
10969 };
10970
10971 /**
10972 * Set whether users belonging to the given role are allowed
10973 * to read this object.
10974 *
10975 * @param role The name of the role, or a AV.Role object.
10976 * @param {Boolean} allowed Whether the given role can read this object.
10977 * @throws {String} If role is neither a AV.Role nor a String.
10978 */
10979 AV.ACL.prototype.setRoleReadAccess = function (role, allowed) {
10980 if (role instanceof AV.Role) {
10981 // Normalize to the String name
10982 role = role.getName();
10983 }
10984 if (_.isString(role)) {
10985 this.setReadAccess('role:' + role, allowed);
10986 return;
10987 }
10988 throw new Error('role must be a AV.Role or a String');
10989 };
10990
10991 /**
10992 * Set whether users belonging to the given role are allowed
10993 * to write this object.
10994 *
10995 * @param role The name of the role, or a AV.Role object.
10996 * @param {Boolean} allowed Whether the given role can write this object.
10997 * @throws {String} If role is neither a AV.Role nor a String.
10998 */
10999 AV.ACL.prototype.setRoleWriteAccess = function (role, allowed) {
11000 if (role instanceof AV.Role) {
11001 // Normalize to the String name
11002 role = role.getName();
11003 }
11004 if (_.isString(role)) {
11005 this.setWriteAccess('role:' + role, allowed);
11006 return;
11007 }
11008 throw new Error('role must be a AV.Role or a String');
11009 };
11010};
11011
11012/***/ }),
11013/* 323 */
11014/***/ (function(module, exports, __webpack_require__) {
11015
11016"use strict";
11017
11018
11019var _ = __webpack_require__(0);
11020
11021module.exports = function (AV) {
11022 /**
11023 * @private
11024 * @class
11025 * A AV.Op is an atomic operation that can be applied to a field in a
11026 * AV.Object. For example, calling <code>object.set("foo", "bar")</code>
11027 * is an example of a AV.Op.Set. Calling <code>object.unset("foo")</code>
11028 * is a AV.Op.Unset. These operations are stored in a AV.Object and
11029 * sent to the server as part of <code>object.save()</code> operations.
11030 * Instances of AV.Op should be immutable.
11031 *
11032 * You should not create subclasses of AV.Op or instantiate AV.Op
11033 * directly.
11034 */
11035 AV.Op = function () {
11036 this._initialize.apply(this, arguments);
11037 };
11038
11039 _.extend(AV.Op.prototype,
11040 /** @lends AV.Op.prototype */{
11041 _initialize: function _initialize() {}
11042 });
11043
11044 _.extend(AV.Op, {
11045 /**
11046 * To create a new Op, call AV.Op._extend();
11047 * @private
11048 */
11049 _extend: AV._extend,
11050
11051 // A map of __op string to decoder function.
11052 _opDecoderMap: {},
11053
11054 /**
11055 * Registers a function to convert a json object with an __op field into an
11056 * instance of a subclass of AV.Op.
11057 * @private
11058 */
11059 _registerDecoder: function _registerDecoder(opName, decoder) {
11060 AV.Op._opDecoderMap[opName] = decoder;
11061 },
11062
11063 /**
11064 * Converts a json object into an instance of a subclass of AV.Op.
11065 * @private
11066 */
11067 _decode: function _decode(json) {
11068 var decoder = AV.Op._opDecoderMap[json.__op];
11069 if (decoder) {
11070 return decoder(json);
11071 } else {
11072 return undefined;
11073 }
11074 }
11075 });
11076
11077 /*
11078 * Add a handler for Batch ops.
11079 */
11080 AV.Op._registerDecoder('Batch', function (json) {
11081 var op = null;
11082 AV._arrayEach(json.ops, function (nextOp) {
11083 nextOp = AV.Op._decode(nextOp);
11084 op = nextOp._mergeWithPrevious(op);
11085 });
11086 return op;
11087 });
11088
11089 /**
11090 * @private
11091 * @class
11092 * A Set operation indicates that either the field was changed using
11093 * AV.Object.set, or it is a mutable container that was detected as being
11094 * changed.
11095 */
11096 AV.Op.Set = AV.Op._extend(
11097 /** @lends AV.Op.Set.prototype */{
11098 _initialize: function _initialize(value) {
11099 this._value = value;
11100 },
11101
11102 /**
11103 * Returns the new value of this field after the set.
11104 */
11105 value: function value() {
11106 return this._value;
11107 },
11108
11109 /**
11110 * Returns a JSON version of the operation suitable for sending to AV.
11111 * @return {Object}
11112 */
11113 toJSON: function toJSON() {
11114 return AV._encode(this.value());
11115 },
11116
11117 _mergeWithPrevious: function _mergeWithPrevious(previous) {
11118 return this;
11119 },
11120
11121 _estimate: function _estimate(oldValue) {
11122 return this.value();
11123 }
11124 });
11125
11126 /**
11127 * A sentinel value that is returned by AV.Op.Unset._estimate to
11128 * indicate the field should be deleted. Basically, if you find _UNSET as a
11129 * value in your object, you should remove that key.
11130 */
11131 AV.Op._UNSET = {};
11132
11133 /**
11134 * @private
11135 * @class
11136 * An Unset operation indicates that this field has been deleted from the
11137 * object.
11138 */
11139 AV.Op.Unset = AV.Op._extend(
11140 /** @lends AV.Op.Unset.prototype */{
11141 /**
11142 * Returns a JSON version of the operation suitable for sending to AV.
11143 * @return {Object}
11144 */
11145 toJSON: function toJSON() {
11146 return { __op: 'Delete' };
11147 },
11148
11149 _mergeWithPrevious: function _mergeWithPrevious(previous) {
11150 return this;
11151 },
11152
11153 _estimate: function _estimate(oldValue) {
11154 return AV.Op._UNSET;
11155 }
11156 });
11157
11158 AV.Op._registerDecoder('Delete', function (json) {
11159 return new AV.Op.Unset();
11160 });
11161
11162 /**
11163 * @private
11164 * @class
11165 * An Increment is an atomic operation where the numeric value for the field
11166 * will be increased by a given amount.
11167 */
11168 AV.Op.Increment = AV.Op._extend(
11169 /** @lends AV.Op.Increment.prototype */{
11170 _initialize: function _initialize(amount) {
11171 this._amount = amount;
11172 },
11173
11174 /**
11175 * Returns the amount to increment by.
11176 * @return {Number} the amount to increment by.
11177 */
11178 amount: function amount() {
11179 return this._amount;
11180 },
11181
11182 /**
11183 * Returns a JSON version of the operation suitable for sending to AV.
11184 * @return {Object}
11185 */
11186 toJSON: function toJSON() {
11187 return { __op: 'Increment', amount: this._amount };
11188 },
11189
11190 _mergeWithPrevious: function _mergeWithPrevious(previous) {
11191 if (!previous) {
11192 return this;
11193 } else if (previous instanceof AV.Op.Unset) {
11194 return new AV.Op.Set(this.amount());
11195 } else if (previous instanceof AV.Op.Set) {
11196 return new AV.Op.Set(previous.value() + this.amount());
11197 } else if (previous instanceof AV.Op.Increment) {
11198 return new AV.Op.Increment(this.amount() + previous.amount());
11199 } else {
11200 throw new Error('Op is invalid after previous op.');
11201 }
11202 },
11203
11204 _estimate: function _estimate(oldValue) {
11205 if (!oldValue) {
11206 return this.amount();
11207 }
11208 return oldValue + this.amount();
11209 }
11210 });
11211
11212 AV.Op._registerDecoder('Increment', function (json) {
11213 return new AV.Op.Increment(json.amount);
11214 });
11215
11216 /**
11217 * @private
11218 * @class
11219 * BitAnd is an atomic operation where the given value will be bit and to the
11220 * value than is stored in this field.
11221 */
11222 AV.Op.BitAnd = AV.Op._extend(
11223 /** @lends AV.Op.BitAnd.prototype */{
11224 _initialize: function _initialize(value) {
11225 this._value = value;
11226 },
11227 value: function value() {
11228 return this._value;
11229 },
11230
11231
11232 /**
11233 * Returns a JSON version of the operation suitable for sending to AV.
11234 * @return {Object}
11235 */
11236 toJSON: function toJSON() {
11237 return { __op: 'BitAnd', value: this.value() };
11238 },
11239 _mergeWithPrevious: function _mergeWithPrevious(previous) {
11240 if (!previous) {
11241 return this;
11242 } else if (previous instanceof AV.Op.Unset) {
11243 return new AV.Op.Set(0);
11244 } else if (previous instanceof AV.Op.Set) {
11245 return new AV.Op.Set(previous.value() & this.value());
11246 } else {
11247 throw new Error('Op is invalid after previous op.');
11248 }
11249 },
11250 _estimate: function _estimate(oldValue) {
11251 return oldValue & this.value();
11252 }
11253 });
11254
11255 AV.Op._registerDecoder('BitAnd', function (json) {
11256 return new AV.Op.BitAnd(json.value);
11257 });
11258
11259 /**
11260 * @private
11261 * @class
11262 * BitOr is an atomic operation where the given value will be bit and to the
11263 * value than is stored in this field.
11264 */
11265 AV.Op.BitOr = AV.Op._extend(
11266 /** @lends AV.Op.BitOr.prototype */{
11267 _initialize: function _initialize(value) {
11268 this._value = value;
11269 },
11270 value: function value() {
11271 return this._value;
11272 },
11273
11274
11275 /**
11276 * Returns a JSON version of the operation suitable for sending to AV.
11277 * @return {Object}
11278 */
11279 toJSON: function toJSON() {
11280 return { __op: 'BitOr', value: this.value() };
11281 },
11282 _mergeWithPrevious: function _mergeWithPrevious(previous) {
11283 if (!previous) {
11284 return this;
11285 } else if (previous instanceof AV.Op.Unset) {
11286 return new AV.Op.Set(this.value());
11287 } else if (previous instanceof AV.Op.Set) {
11288 return new AV.Op.Set(previous.value() | this.value());
11289 } else {
11290 throw new Error('Op is invalid after previous op.');
11291 }
11292 },
11293 _estimate: function _estimate(oldValue) {
11294 return oldValue | this.value();
11295 }
11296 });
11297
11298 AV.Op._registerDecoder('BitOr', function (json) {
11299 return new AV.Op.BitOr(json.value);
11300 });
11301
11302 /**
11303 * @private
11304 * @class
11305 * BitXor is an atomic operation where the given value will be bit and to the
11306 * value than is stored in this field.
11307 */
11308 AV.Op.BitXor = AV.Op._extend(
11309 /** @lends AV.Op.BitXor.prototype */{
11310 _initialize: function _initialize(value) {
11311 this._value = value;
11312 },
11313 value: function value() {
11314 return this._value;
11315 },
11316
11317
11318 /**
11319 * Returns a JSON version of the operation suitable for sending to AV.
11320 * @return {Object}
11321 */
11322 toJSON: function toJSON() {
11323 return { __op: 'BitXor', value: this.value() };
11324 },
11325 _mergeWithPrevious: function _mergeWithPrevious(previous) {
11326 if (!previous) {
11327 return this;
11328 } else if (previous instanceof AV.Op.Unset) {
11329 return new AV.Op.Set(this.value());
11330 } else if (previous instanceof AV.Op.Set) {
11331 return new AV.Op.Set(previous.value() ^ this.value());
11332 } else {
11333 throw new Error('Op is invalid after previous op.');
11334 }
11335 },
11336 _estimate: function _estimate(oldValue) {
11337 return oldValue ^ this.value();
11338 }
11339 });
11340
11341 AV.Op._registerDecoder('BitXor', function (json) {
11342 return new AV.Op.BitXor(json.value);
11343 });
11344
11345 /**
11346 * @private
11347 * @class
11348 * Add is an atomic operation where the given objects will be appended to the
11349 * array that is stored in this field.
11350 */
11351 AV.Op.Add = AV.Op._extend(
11352 /** @lends AV.Op.Add.prototype */{
11353 _initialize: function _initialize(objects) {
11354 this._objects = objects;
11355 },
11356
11357 /**
11358 * Returns the objects to be added to the array.
11359 * @return {Array} The objects to be added to the array.
11360 */
11361 objects: function objects() {
11362 return this._objects;
11363 },
11364
11365 /**
11366 * Returns a JSON version of the operation suitable for sending to AV.
11367 * @return {Object}
11368 */
11369 toJSON: function toJSON() {
11370 return { __op: 'Add', objects: AV._encode(this.objects()) };
11371 },
11372
11373 _mergeWithPrevious: function _mergeWithPrevious(previous) {
11374 if (!previous) {
11375 return this;
11376 } else if (previous instanceof AV.Op.Unset) {
11377 return new AV.Op.Set(this.objects());
11378 } else if (previous instanceof AV.Op.Set) {
11379 return new AV.Op.Set(this._estimate(previous.value()));
11380 } else if (previous instanceof AV.Op.Add) {
11381 return new AV.Op.Add(previous.objects().concat(this.objects()));
11382 } else {
11383 throw new Error('Op is invalid after previous op.');
11384 }
11385 },
11386
11387 _estimate: function _estimate(oldValue) {
11388 if (!oldValue) {
11389 return _.clone(this.objects());
11390 } else {
11391 return oldValue.concat(this.objects());
11392 }
11393 }
11394 });
11395
11396 AV.Op._registerDecoder('Add', function (json) {
11397 return new AV.Op.Add(AV._decode(json.objects));
11398 });
11399
11400 /**
11401 * @private
11402 * @class
11403 * AddUnique is an atomic operation where the given items will be appended to
11404 * the array that is stored in this field only if they were not already
11405 * present in the array.
11406 */
11407 AV.Op.AddUnique = AV.Op._extend(
11408 /** @lends AV.Op.AddUnique.prototype */{
11409 _initialize: function _initialize(objects) {
11410 this._objects = _.uniq(objects);
11411 },
11412
11413 /**
11414 * Returns the objects to be added to the array.
11415 * @return {Array} The objects to be added to the array.
11416 */
11417 objects: function objects() {
11418 return this._objects;
11419 },
11420
11421 /**
11422 * Returns a JSON version of the operation suitable for sending to AV.
11423 * @return {Object}
11424 */
11425 toJSON: function toJSON() {
11426 return { __op: 'AddUnique', objects: AV._encode(this.objects()) };
11427 },
11428
11429 _mergeWithPrevious: function _mergeWithPrevious(previous) {
11430 if (!previous) {
11431 return this;
11432 } else if (previous instanceof AV.Op.Unset) {
11433 return new AV.Op.Set(this.objects());
11434 } else if (previous instanceof AV.Op.Set) {
11435 return new AV.Op.Set(this._estimate(previous.value()));
11436 } else if (previous instanceof AV.Op.AddUnique) {
11437 return new AV.Op.AddUnique(this._estimate(previous.objects()));
11438 } else {
11439 throw new Error('Op is invalid after previous op.');
11440 }
11441 },
11442
11443 _estimate: function _estimate(oldValue) {
11444 if (!oldValue) {
11445 return _.clone(this.objects());
11446 } else {
11447 // We can't just take the _.uniq(_.union(...)) of oldValue and
11448 // this.objects, because the uniqueness may not apply to oldValue
11449 // (especially if the oldValue was set via .set())
11450 var newValue = _.clone(oldValue);
11451 AV._arrayEach(this.objects(), function (obj) {
11452 if (obj instanceof AV.Object && obj.id) {
11453 var matchingObj = _.find(newValue, function (anObj) {
11454 return anObj instanceof AV.Object && anObj.id === obj.id;
11455 });
11456 if (!matchingObj) {
11457 newValue.push(obj);
11458 } else {
11459 var index = _.indexOf(newValue, matchingObj);
11460 newValue[index] = obj;
11461 }
11462 } else if (!_.contains(newValue, obj)) {
11463 newValue.push(obj);
11464 }
11465 });
11466 return newValue;
11467 }
11468 }
11469 });
11470
11471 AV.Op._registerDecoder('AddUnique', function (json) {
11472 return new AV.Op.AddUnique(AV._decode(json.objects));
11473 });
11474
11475 /**
11476 * @private
11477 * @class
11478 * Remove is an atomic operation where the given objects will be removed from
11479 * the array that is stored in this field.
11480 */
11481 AV.Op.Remove = AV.Op._extend(
11482 /** @lends AV.Op.Remove.prototype */{
11483 _initialize: function _initialize(objects) {
11484 this._objects = _.uniq(objects);
11485 },
11486
11487 /**
11488 * Returns the objects to be removed from the array.
11489 * @return {Array} The objects to be removed from the array.
11490 */
11491 objects: function objects() {
11492 return this._objects;
11493 },
11494
11495 /**
11496 * Returns a JSON version of the operation suitable for sending to AV.
11497 * @return {Object}
11498 */
11499 toJSON: function toJSON() {
11500 return { __op: 'Remove', objects: AV._encode(this.objects()) };
11501 },
11502
11503 _mergeWithPrevious: function _mergeWithPrevious(previous) {
11504 if (!previous) {
11505 return this;
11506 } else if (previous instanceof AV.Op.Unset) {
11507 return previous;
11508 } else if (previous instanceof AV.Op.Set) {
11509 return new AV.Op.Set(this._estimate(previous.value()));
11510 } else if (previous instanceof AV.Op.Remove) {
11511 return new AV.Op.Remove(_.union(previous.objects(), this.objects()));
11512 } else {
11513 throw new Error('Op is invalid after previous op.');
11514 }
11515 },
11516
11517 _estimate: function _estimate(oldValue) {
11518 if (!oldValue) {
11519 return [];
11520 } else {
11521 var newValue = _.difference(oldValue, this.objects());
11522 // If there are saved AV Objects being removed, also remove them.
11523 AV._arrayEach(this.objects(), function (obj) {
11524 if (obj instanceof AV.Object && obj.id) {
11525 newValue = _.reject(newValue, function (other) {
11526 return other instanceof AV.Object && other.id === obj.id;
11527 });
11528 }
11529 });
11530 return newValue;
11531 }
11532 }
11533 });
11534
11535 AV.Op._registerDecoder('Remove', function (json) {
11536 return new AV.Op.Remove(AV._decode(json.objects));
11537 });
11538
11539 /**
11540 * @private
11541 * @class
11542 * A Relation operation indicates that the field is an instance of
11543 * AV.Relation, and objects are being added to, or removed from, that
11544 * relation.
11545 */
11546 AV.Op.Relation = AV.Op._extend(
11547 /** @lends AV.Op.Relation.prototype */{
11548 _initialize: function _initialize(adds, removes) {
11549 this._targetClassName = null;
11550
11551 var self = this;
11552
11553 var pointerToId = function pointerToId(object) {
11554 if (object instanceof AV.Object) {
11555 if (!object.id) {
11556 throw new Error("You can't add an unsaved AV.Object to a relation.");
11557 }
11558 if (!self._targetClassName) {
11559 self._targetClassName = object.className;
11560 }
11561 if (self._targetClassName !== object.className) {
11562 throw new Error('Tried to create a AV.Relation with 2 different types: ' + self._targetClassName + ' and ' + object.className + '.');
11563 }
11564 return object.id;
11565 }
11566 return object;
11567 };
11568
11569 this.relationsToAdd = _.uniq(_.map(adds, pointerToId));
11570 this.relationsToRemove = _.uniq(_.map(removes, pointerToId));
11571 },
11572
11573 /**
11574 * Returns an array of unfetched AV.Object that are being added to the
11575 * relation.
11576 * @return {Array}
11577 */
11578 added: function added() {
11579 var self = this;
11580 return _.map(this.relationsToAdd, function (objectId) {
11581 var object = AV.Object._create(self._targetClassName);
11582 object.id = objectId;
11583 return object;
11584 });
11585 },
11586
11587 /**
11588 * Returns an array of unfetched AV.Object that are being removed from
11589 * the relation.
11590 * @return {Array}
11591 */
11592 removed: function removed() {
11593 var self = this;
11594 return _.map(this.relationsToRemove, function (objectId) {
11595 var object = AV.Object._create(self._targetClassName);
11596 object.id = objectId;
11597 return object;
11598 });
11599 },
11600
11601 /**
11602 * Returns a JSON version of the operation suitable for sending to AV.
11603 * @return {Object}
11604 */
11605 toJSON: function toJSON() {
11606 var adds = null;
11607 var removes = null;
11608 var self = this;
11609 var idToPointer = function idToPointer(id) {
11610 return {
11611 __type: 'Pointer',
11612 className: self._targetClassName,
11613 objectId: id
11614 };
11615 };
11616 var pointers = null;
11617 if (this.relationsToAdd.length > 0) {
11618 pointers = _.map(this.relationsToAdd, idToPointer);
11619 adds = { __op: 'AddRelation', objects: pointers };
11620 }
11621
11622 if (this.relationsToRemove.length > 0) {
11623 pointers = _.map(this.relationsToRemove, idToPointer);
11624 removes = { __op: 'RemoveRelation', objects: pointers };
11625 }
11626
11627 if (adds && removes) {
11628 return { __op: 'Batch', ops: [adds, removes] };
11629 }
11630
11631 return adds || removes || {};
11632 },
11633
11634 _mergeWithPrevious: function _mergeWithPrevious(previous) {
11635 if (!previous) {
11636 return this;
11637 } else if (previous instanceof AV.Op.Unset) {
11638 throw new Error("You can't modify a relation after deleting it.");
11639 } else if (previous instanceof AV.Op.Relation) {
11640 if (previous._targetClassName && previous._targetClassName !== this._targetClassName) {
11641 throw new Error('Related object must be of class ' + previous._targetClassName + ', but ' + this._targetClassName + ' was passed in.');
11642 }
11643 var newAdd = _.union(_.difference(previous.relationsToAdd, this.relationsToRemove), this.relationsToAdd);
11644 var newRemove = _.union(_.difference(previous.relationsToRemove, this.relationsToAdd), this.relationsToRemove);
11645
11646 var newRelation = new AV.Op.Relation(newAdd, newRemove);
11647 newRelation._targetClassName = this._targetClassName;
11648 return newRelation;
11649 } else {
11650 throw new Error('Op is invalid after previous op.');
11651 }
11652 },
11653
11654 _estimate: function _estimate(oldValue, object, key) {
11655 if (!oldValue) {
11656 var relation = new AV.Relation(object, key);
11657 relation.targetClassName = this._targetClassName;
11658 } else if (oldValue instanceof AV.Relation) {
11659 if (this._targetClassName) {
11660 if (oldValue.targetClassName) {
11661 if (oldValue.targetClassName !== this._targetClassName) {
11662 throw new Error('Related object must be a ' + oldValue.targetClassName + ', but a ' + this._targetClassName + ' was passed in.');
11663 }
11664 } else {
11665 oldValue.targetClassName = this._targetClassName;
11666 }
11667 }
11668 return oldValue;
11669 } else {
11670 throw new Error('Op is invalid after previous op.');
11671 }
11672 }
11673 });
11674
11675 AV.Op._registerDecoder('AddRelation', function (json) {
11676 return new AV.Op.Relation(AV._decode(json.objects), []);
11677 });
11678 AV.Op._registerDecoder('RemoveRelation', function (json) {
11679 return new AV.Op.Relation([], AV._decode(json.objects));
11680 });
11681};
11682
11683/***/ }),
11684/* 324 */
11685/***/ (function(module, exports, __webpack_require__) {
11686
11687"use strict";
11688
11689
11690var _ = __webpack_require__(0);
11691
11692module.exports = function (AV) {
11693 /**
11694 * Creates a new Relation for the given parent object and key. This
11695 * constructor should rarely be used directly, but rather created by
11696 * {@link AV.Object#relation}.
11697 * @param {AV.Object} parent The parent of this relation.
11698 * @param {String} key The key for this relation on the parent.
11699 * @see AV.Object#relation
11700 * @class
11701 *
11702 * <p>
11703 * A class that is used to access all of the children of a many-to-many
11704 * relationship. Each instance of AV.Relation is associated with a
11705 * particular parent object and key.
11706 * </p>
11707 */
11708 AV.Relation = function (parent, key) {
11709 if (!_.isString(key)) {
11710 throw new TypeError('key must be a string');
11711 }
11712 this.parent = parent;
11713 this.key = key;
11714 this.targetClassName = null;
11715 };
11716
11717 /**
11718 * Creates a query that can be used to query the parent objects in this relation.
11719 * @param {String} parentClass The parent class or name.
11720 * @param {String} relationKey The relation field key in parent.
11721 * @param {AV.Object} child The child object.
11722 * @return {AV.Query}
11723 */
11724 AV.Relation.reverseQuery = function (parentClass, relationKey, child) {
11725 var query = new AV.Query(parentClass);
11726 query.equalTo(relationKey, child._toPointer());
11727 return query;
11728 };
11729
11730 _.extend(AV.Relation.prototype,
11731 /** @lends AV.Relation.prototype */{
11732 /**
11733 * Makes sure that this relation has the right parent and key.
11734 * @private
11735 */
11736 _ensureParentAndKey: function _ensureParentAndKey(parent, key) {
11737 this.parent = this.parent || parent;
11738 this.key = this.key || key;
11739 if (this.parent !== parent) {
11740 throw new Error('Internal Error. Relation retrieved from two different Objects.');
11741 }
11742 if (this.key !== key) {
11743 throw new Error('Internal Error. Relation retrieved from two different keys.');
11744 }
11745 },
11746
11747 /**
11748 * Adds a AV.Object or an array of AV.Objects to the relation.
11749 * @param {AV.Object|AV.Object[]} objects The item or items to add.
11750 */
11751 add: function add(objects) {
11752 if (!_.isArray(objects)) {
11753 objects = [objects];
11754 }
11755
11756 var change = new AV.Op.Relation(objects, []);
11757 this.parent.set(this.key, change);
11758 this.targetClassName = change._targetClassName;
11759 },
11760
11761 /**
11762 * Removes a AV.Object or an array of AV.Objects from this relation.
11763 * @param {AV.Object|AV.Object[]} objects The item or items to remove.
11764 */
11765 remove: function remove(objects) {
11766 if (!_.isArray(objects)) {
11767 objects = [objects];
11768 }
11769
11770 var change = new AV.Op.Relation([], objects);
11771 this.parent.set(this.key, change);
11772 this.targetClassName = change._targetClassName;
11773 },
11774
11775 /**
11776 * Returns a JSON version of the object suitable for saving to disk.
11777 * @return {Object}
11778 */
11779 toJSON: function toJSON() {
11780 return { __type: 'Relation', className: this.targetClassName };
11781 },
11782
11783 /**
11784 * Returns a AV.Query that is limited to objects in this
11785 * relation.
11786 * @return {AV.Query}
11787 */
11788 query: function query() {
11789 var targetClass;
11790 var query;
11791 if (!this.targetClassName) {
11792 targetClass = AV.Object._getSubclass(this.parent.className);
11793 query = new AV.Query(targetClass);
11794 query._defaultParams.redirectClassNameForKey = this.key;
11795 } else {
11796 targetClass = AV.Object._getSubclass(this.targetClassName);
11797 query = new AV.Query(targetClass);
11798 }
11799 query._addCondition('$relatedTo', 'object', this.parent._toPointer());
11800 query._addCondition('$relatedTo', 'key', this.key);
11801
11802 return query;
11803 }
11804 });
11805};
11806
11807/***/ }),
11808/* 325 */
11809/***/ (function(module, exports, __webpack_require__) {
11810
11811"use strict";
11812
11813
11814var _promise = __webpack_require__(3);
11815
11816var _promise2 = _interopRequireDefault(_promise);
11817
11818function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11819
11820var _ = __webpack_require__(0);
11821var cos = __webpack_require__(326);
11822var qiniu = __webpack_require__(327);
11823var s3 = __webpack_require__(341);
11824var AVError = __webpack_require__(34);
11825var AVRequest = __webpack_require__(14)._request;
11826
11827var _require = __webpack_require__(19),
11828 tap = _require.tap,
11829 transformFetchOptions = _require.transformFetchOptions;
11830
11831var debug = __webpack_require__(33)('leancloud:file');
11832var parseBase64 = __webpack_require__(345);
11833
11834module.exports = function (AV) {
11835 // port from browserify path module
11836 // since react-native packager won't shim node modules.
11837 var extname = function extname(path) {
11838 if (!_.isString(path)) return '';
11839 return path.match(/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/)[4];
11840 };
11841
11842 var b64Digit = function b64Digit(number) {
11843 if (number < 26) {
11844 return String.fromCharCode(65 + number);
11845 }
11846 if (number < 52) {
11847 return String.fromCharCode(97 + (number - 26));
11848 }
11849 if (number < 62) {
11850 return String.fromCharCode(48 + (number - 52));
11851 }
11852 if (number === 62) {
11853 return '+';
11854 }
11855 if (number === 63) {
11856 return '/';
11857 }
11858 throw new Error('Tried to encode large digit ' + number + ' in base64.');
11859 };
11860
11861 var encodeBase64 = function encodeBase64(array) {
11862 var chunks = [];
11863 chunks.length = Math.ceil(array.length / 3);
11864 _.times(chunks.length, function (i) {
11865 var b1 = array[i * 3];
11866 var b2 = array[i * 3 + 1] || 0;
11867 var b3 = array[i * 3 + 2] || 0;
11868
11869 var has2 = i * 3 + 1 < array.length;
11870 var has3 = i * 3 + 2 < array.length;
11871
11872 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('');
11873 });
11874 return chunks.join('');
11875 };
11876
11877 /**
11878 * An AV.File is a local representation of a file that is saved to the AV
11879 * cloud.
11880 * @param name {String} The file's name. This will change to a unique value
11881 * once the file has finished saving.
11882 * @param data {Array} The data for the file, as either:
11883 * 1. an Array of byte value Numbers, or
11884 * 2. an Object like { base64: "..." } with a base64-encoded String.
11885 * 3. a Blob(File) selected with a file upload control in a browser.
11886 * 4. an Object like { blob: {uri: "..."} } that mimics Blob
11887 * in some non-browser environments such as React Native.
11888 * 5. a Buffer in Node.js runtime.
11889 * 6. a Stream in Node.js runtime.
11890 *
11891 * For example:<pre>
11892 * var fileUploadControl = $("#profilePhotoFileUpload")[0];
11893 * if (fileUploadControl.files.length > 0) {
11894 * var file = fileUploadControl.files[0];
11895 * var name = "photo.jpg";
11896 * var file = new AV.File(name, file);
11897 * file.save().then(function() {
11898 * // The file has been saved to AV.
11899 * }, function(error) {
11900 * // The file either could not be read, or could not be saved to AV.
11901 * });
11902 * }</pre>
11903 *
11904 * @class
11905 * @param [mimeType] {String} Content-Type header to use for the file. If
11906 * this is omitted, the content type will be inferred from the name's
11907 * extension.
11908 */
11909 AV.File = function (name, data, mimeType) {
11910 this.attributes = {
11911 name: name,
11912 url: '',
11913 metaData: {},
11914 // 用来存储转换后要上传的 base64 String
11915 base64: ''
11916 };
11917
11918 if (_.isString(data)) {
11919 throw new TypeError('Creating an AV.File from a String is not yet supported.');
11920 }
11921 if (_.isArray(data)) {
11922 this.attributes.metaData.size = data.length;
11923 data = { base64: encodeBase64(data) };
11924 }
11925
11926 this._extName = '';
11927 this._data = data;
11928 this._uploadHeaders = {};
11929
11930 if (data && data.blob && typeof data.blob.uri === 'string') {
11931 this._extName = extname(data.blob.uri);
11932 }
11933
11934 if (typeof Blob !== 'undefined' && data instanceof Blob) {
11935 if (data.size) {
11936 this.attributes.metaData.size = data.size;
11937 }
11938 if (data.name) {
11939 this._extName = extname(data.name);
11940 }
11941 }
11942
11943 var owner = void 0;
11944 if (data && data.owner) {
11945 owner = data.owner;
11946 } else if (!AV._config.disableCurrentUser) {
11947 try {
11948 owner = AV.User.current();
11949 } catch (error) {
11950 if ('SYNC_API_NOT_AVAILABLE' !== error.code) {
11951 throw error;
11952 }
11953 }
11954 }
11955
11956 this.attributes.metaData.owner = owner ? owner.id : 'unknown';
11957
11958 this.set('mime_type', mimeType);
11959 };
11960
11961 /**
11962 * Creates a fresh AV.File object with exists url for saving to AVOS Cloud.
11963 * @param {String} name the file name
11964 * @param {String} url the file url.
11965 * @param {Object} [metaData] the file metadata object.
11966 * @param {String} [type] Content-Type header to use for the file. If
11967 * this is omitted, the content type will be inferred from the name's
11968 * extension.
11969 * @return {AV.File} the file object
11970 */
11971 AV.File.withURL = function (name, url, metaData, type) {
11972 if (!name || !url) {
11973 throw new Error('Please provide file name and url');
11974 }
11975 var file = new AV.File(name, null, type);
11976 //copy metaData properties to file.
11977 if (metaData) {
11978 for (var prop in metaData) {
11979 if (!file.attributes.metaData[prop]) file.attributes.metaData[prop] = metaData[prop];
11980 }
11981 }
11982 file.attributes.url = url;
11983 //Mark the file is from external source.
11984 file.attributes.metaData.__source = 'external';
11985 file.attributes.metaData.size = 0;
11986 return file;
11987 };
11988
11989 /**
11990 * Creates a file object with exists objectId.
11991 * @param {String} objectId The objectId string
11992 * @return {AV.File} the file object
11993 */
11994 AV.File.createWithoutData = function (objectId) {
11995 if (!objectId) {
11996 throw new TypeError('The objectId must be provided');
11997 }
11998 var file = new AV.File();
11999 file.id = objectId;
12000 return file;
12001 };
12002
12003 _.extend(AV.File.prototype,
12004 /** @lends AV.File.prototype */{
12005 className: '_File',
12006
12007 _toFullJSON: function _toFullJSON(seenObjects) {
12008 var _this = this;
12009
12010 var full = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
12011
12012 var json = _.clone(this.attributes);
12013 AV._objectEach(json, function (val, key) {
12014 json[key] = AV._encode(val, seenObjects, undefined, full);
12015 });
12016 AV._objectEach(this._operations, function (val, key) {
12017 json[key] = val;
12018 });
12019
12020 if (_.has(this, 'id')) {
12021 json.objectId = this.id;
12022 }
12023 ['createdAt', 'updatedAt'].forEach(function (key) {
12024 if (_.has(_this, key)) {
12025 var val = _this[key];
12026 json[key] = _.isDate(val) ? val.toJSON() : val;
12027 }
12028 });
12029 if (full) {
12030 json.__type = 'File';
12031 }
12032 return json;
12033 },
12034
12035
12036 /**
12037 * Returns a JSON version of the file with meta data.
12038 * Inverse to {@link AV.parseJSON}
12039 * @since 3.0.0
12040 * @return {Object}
12041 */
12042 toFullJSON: function toFullJSON() {
12043 var seenObjects = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
12044
12045 return this._toFullJSON(seenObjects);
12046 },
12047
12048
12049 /**
12050 * Returns a JSON version of the object.
12051 * @return {Object}
12052 */
12053 toJSON: function toJSON(key, holder) {
12054 var seenObjects = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [this];
12055
12056 return this._toFullJSON(seenObjects, false);
12057 },
12058
12059
12060 /**
12061 * Gets a Pointer referencing this file.
12062 * @private
12063 */
12064 _toPointer: function _toPointer() {
12065 return {
12066 __type: 'Pointer',
12067 className: this.className,
12068 objectId: this.id
12069 };
12070 },
12071
12072
12073 /**
12074 * Returns the ACL for this file.
12075 * @returns {AV.ACL} An instance of AV.ACL.
12076 */
12077 getACL: function getACL() {
12078 return this._acl;
12079 },
12080
12081
12082 /**
12083 * Sets the ACL to be used for this file.
12084 * @param {AV.ACL} acl An instance of AV.ACL.
12085 */
12086 setACL: function setACL(acl) {
12087 if (!(acl instanceof AV.ACL)) {
12088 return new AVError(AVError.OTHER_CAUSE, 'ACL must be a AV.ACL.');
12089 }
12090 this._acl = acl;
12091 return this;
12092 },
12093
12094
12095 /**
12096 * Gets the name of the file. Before save is called, this is the filename
12097 * given by the user. After save is called, that name gets prefixed with a
12098 * unique identifier.
12099 */
12100 name: function name() {
12101 return this.get('name');
12102 },
12103
12104
12105 /**
12106 * Gets the url of the file. It is only available after you save the file or
12107 * after you get the file from a AV.Object.
12108 * @return {String}
12109 */
12110 url: function url() {
12111 return this.get('url');
12112 },
12113
12114
12115 /**
12116 * Gets the attributs of the file object.
12117 * @param {String} The attribute name which want to get.
12118 * @returns {Any}
12119 */
12120 get: function get(attrName) {
12121 switch (attrName) {
12122 case 'objectId':
12123 return this.id;
12124 case 'url':
12125 case 'name':
12126 case 'mime_type':
12127 case 'metaData':
12128 case 'createdAt':
12129 case 'updatedAt':
12130 return this.attributes[attrName];
12131 default:
12132 return this.attributes.metaData[attrName];
12133 }
12134 },
12135
12136
12137 /**
12138 * Set the metaData of the file object.
12139 * @param {Object} Object is an key value Object for setting metaData.
12140 * @param {String} attr is an optional metadata key.
12141 * @param {Object} value is an optional metadata value.
12142 * @returns {String|Number|Array|Object}
12143 */
12144 set: function set() {
12145 var _this2 = this;
12146
12147 var set = function set(attrName, value) {
12148 switch (attrName) {
12149 case 'name':
12150 case 'url':
12151 case 'mime_type':
12152 case 'base64':
12153 case 'metaData':
12154 _this2.attributes[attrName] = value;
12155 break;
12156 default:
12157 // File 并非一个 AVObject,不能完全自定义其他属性,所以只能都放在 metaData 上面
12158 _this2.attributes.metaData[attrName] = value;
12159 break;
12160 }
12161 };
12162
12163 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
12164 args[_key] = arguments[_key];
12165 }
12166
12167 switch (args.length) {
12168 case 1:
12169 // 传入一个 Object
12170 for (var k in args[0]) {
12171 set(k, args[0][k]);
12172 }
12173 break;
12174 case 2:
12175 set(args[0], args[1]);
12176 break;
12177 }
12178 return this;
12179 },
12180
12181
12182 /**
12183 * Set a header for the upload request.
12184 * For more infomation, go to https://url.leanapp.cn/avfile-upload-headers
12185 *
12186 * @param {String} key header key
12187 * @param {String} value header value
12188 * @return {AV.File} this
12189 */
12190 setUploadHeader: function setUploadHeader(key, value) {
12191 this._uploadHeaders[key] = value;
12192 return this;
12193 },
12194
12195
12196 /**
12197 * <p>Returns the file's metadata JSON object if no arguments is given.Returns the
12198 * metadata value if a key is given.Set metadata value if key and value are both given.</p>
12199 * <p><pre>
12200 * var metadata = file.metaData(); //Get metadata JSON object.
12201 * var size = file.metaData('size'); // Get the size metadata value.
12202 * file.metaData('format', 'jpeg'); //set metadata attribute and value.
12203 *</pre></p>
12204 * @return {Object} The file's metadata JSON object.
12205 * @param {String} attr an optional metadata key.
12206 * @param {Object} value an optional metadata value.
12207 **/
12208 metaData: function metaData(attr, value) {
12209 if (attr && value) {
12210 this.attributes.metaData[attr] = value;
12211 return this;
12212 } else if (attr && !value) {
12213 return this.attributes.metaData[attr];
12214 } else {
12215 return this.attributes.metaData;
12216 }
12217 },
12218
12219
12220 /**
12221 * 如果文件是图片,获取图片的缩略图URL。可以传入宽度、高度、质量、格式等参数。
12222 * @return {String} 缩略图URL
12223 * @param {Number} width 宽度,单位:像素
12224 * @param {Number} heigth 高度,单位:像素
12225 * @param {Number} quality 质量,1-100的数字,默认100
12226 * @param {Number} scaleToFit 是否将图片自适应大小。默认为true。
12227 * @param {String} fmt 格式,默认为png,也可以为jpeg,gif等格式。
12228 */
12229
12230 thumbnailURL: function thumbnailURL(width, height) {
12231 var quality = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100;
12232 var scaleToFit = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
12233 var fmt = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'png';
12234
12235 var url = this.attributes.url;
12236 if (!url) {
12237 throw new Error('Invalid url.');
12238 }
12239 if (!width || !height || width <= 0 || height <= 0) {
12240 throw new Error('Invalid width or height value.');
12241 }
12242 if (quality <= 0 || quality > 100) {
12243 throw new Error('Invalid quality value.');
12244 }
12245 var mode = scaleToFit ? 2 : 1;
12246 return url + '?imageView/' + mode + '/w/' + width + '/h/' + height + '/q/' + quality + '/format/' + fmt;
12247 },
12248
12249
12250 /**
12251 * Returns the file's size.
12252 * @return {Number} The file's size in bytes.
12253 **/
12254 size: function size() {
12255 return this.metaData().size;
12256 },
12257
12258
12259 /**
12260 * Returns the file's owner.
12261 * @return {String} The file's owner id.
12262 */
12263 ownerId: function ownerId() {
12264 return this.metaData().owner;
12265 },
12266
12267
12268 /**
12269 * Destroy the file.
12270 * @param {AuthOptions} options
12271 * @return {Promise} A promise that is fulfilled when the destroy
12272 * completes.
12273 */
12274 destroy: function destroy(options) {
12275 if (!this.id) {
12276 return _promise2.default.reject(new Error('The file id does not eixst.'));
12277 }
12278 var request = AVRequest('files', null, this.id, 'DELETE', null, options);
12279 return request;
12280 },
12281
12282
12283 /**
12284 * Request Qiniu upload token
12285 * @param {string} type
12286 * @return {Promise} Resolved with the response
12287 * @private
12288 */
12289 _fileToken: function _fileToken(type, authOptions) {
12290 var name = this.attributes.name;
12291
12292 var extName = extname(name);
12293 if (!extName && this._extName) {
12294 name += this._extName;
12295 extName = this._extName;
12296 }
12297 var data = {
12298 name: name,
12299 keep_file_name: authOptions.keepFileName,
12300 key: authOptions.key,
12301 ACL: this._acl,
12302 mime_type: type,
12303 metaData: this.attributes.metaData
12304 };
12305 return AVRequest('fileTokens', null, null, 'POST', data, authOptions);
12306 },
12307
12308
12309 /**
12310 * @callback UploadProgressCallback
12311 * @param {XMLHttpRequestProgressEvent} event - The progress event with 'loaded' and 'total' attributes
12312 */
12313 /**
12314 * Saves the file to the AV cloud.
12315 * @param {AuthOptions} [options] AuthOptions plus:
12316 * @param {UploadProgressCallback} [options.onprogress] 文件上传进度,在 Node.js 中无效,回调参数说明详见 {@link UploadProgressCallback}。
12317 * @param {boolean} [options.keepFileName = false] 保留下载文件的文件名。
12318 * @param {string} [options.key] 指定文件的 key。设置该选项需要使用 masterKey
12319 * @return {Promise} Promise that is resolved when the save finishes.
12320 */
12321 save: function save() {
12322 var _this3 = this;
12323
12324 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
12325
12326 if (this.id) {
12327 throw new Error('File is already saved.');
12328 }
12329 if (!this._previousSave) {
12330 if (this._data) {
12331 var mimeType = this.get('mime_type');
12332 this._previousSave = this._fileToken(mimeType, options).then(function (uploadInfo) {
12333 if (uploadInfo.mime_type) {
12334 mimeType = uploadInfo.mime_type;
12335 _this3.set('mime_type', mimeType);
12336 }
12337 _this3._token = uploadInfo.token;
12338 return _promise2.default.resolve().then(function () {
12339 var data = _this3._data;
12340 if (data && data.base64) {
12341 return parseBase64(data.base64, mimeType);
12342 }
12343 if (data && data.blob) {
12344 if (!data.blob.type && mimeType) {
12345 data.blob.type = mimeType;
12346 }
12347 if (!data.blob.name) {
12348 data.blob.name = _this3.get('name');
12349 }
12350 return data.blob;
12351 }
12352 if (typeof Blob !== 'undefined' && data instanceof Blob) {
12353 return data;
12354 }
12355 throw new TypeError('malformed file data');
12356 }).then(function (data) {
12357 var _options = _.extend({}, options);
12358 // filter out download progress events
12359 if (options.onprogress) {
12360 _options.onprogress = function (event) {
12361 if (event.direction === 'download') return;
12362 return options.onprogress(event);
12363 };
12364 }
12365 switch (uploadInfo.provider) {
12366 case 's3':
12367 return s3(uploadInfo, data, _this3, _options);
12368 case 'qcloud':
12369 return cos(uploadInfo, data, _this3, _options);
12370 case 'qiniu':
12371 default:
12372 return qiniu(uploadInfo, data, _this3, _options);
12373 }
12374 }).then(tap(function () {
12375 return _this3._callback(true);
12376 }), function (error) {
12377 _this3._callback(false);
12378 throw error;
12379 });
12380 });
12381 } else if (this.attributes.url && this.attributes.metaData.__source === 'external') {
12382 // external link file.
12383 var data = {
12384 name: this.attributes.name,
12385 ACL: this._acl,
12386 metaData: this.attributes.metaData,
12387 mime_type: this.mimeType,
12388 url: this.attributes.url
12389 };
12390 this._previousSave = AVRequest('files', null, null, 'post', data, options).then(function (response) {
12391 _this3.id = response.objectId;
12392 return _this3;
12393 });
12394 }
12395 }
12396 return this._previousSave;
12397 },
12398 _callback: function _callback(success) {
12399 AVRequest('fileCallback', null, null, 'post', {
12400 token: this._token,
12401 result: success
12402 }).catch(debug);
12403 delete this._token;
12404 delete this._data;
12405 },
12406
12407
12408 /**
12409 * fetch the file from server. If the server's representation of the
12410 * model differs from its current attributes, they will be overriden,
12411 * @param {Object} fetchOptions Optional options to set 'keys',
12412 * 'include' and 'includeACL' option.
12413 * @param {AuthOptions} options
12414 * @return {Promise} A promise that is fulfilled when the fetch
12415 * completes.
12416 */
12417 fetch: function fetch(fetchOptions, options) {
12418 if (!this.id) {
12419 throw new Error('Cannot fetch unsaved file');
12420 }
12421 var request = AVRequest('files', null, this.id, 'GET', transformFetchOptions(fetchOptions), options);
12422 return request.then(this._finishFetch.bind(this));
12423 },
12424 _finishFetch: function _finishFetch(response) {
12425 var value = AV.Object.prototype.parse(response);
12426 value.attributes = {
12427 name: value.name,
12428 url: value.url,
12429 mime_type: value.mime_type,
12430 bucket: value.bucket
12431 };
12432 value.attributes.metaData = value.metaData || {};
12433 value.id = value.objectId;
12434 // clean
12435 delete value.objectId;
12436 delete value.metaData;
12437 delete value.url;
12438 delete value.name;
12439 delete value.mime_type;
12440 delete value.bucket;
12441 _.extend(this, value);
12442 return this;
12443 }
12444 });
12445};
12446
12447/***/ }),
12448/* 326 */
12449/***/ (function(module, exports, __webpack_require__) {
12450
12451"use strict";
12452
12453
12454var _require = __webpack_require__(43),
12455 getAdapter = _require.getAdapter;
12456
12457var debug = __webpack_require__(33)('cos');
12458
12459module.exports = function (uploadInfo, data, file) {
12460 var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
12461
12462 var url = uploadInfo.upload_url + '?sign=' + encodeURIComponent(uploadInfo.token);
12463 var fileFormData = {
12464 field: 'fileContent',
12465 data: data,
12466 name: file.attributes.name
12467 };
12468 var options = {
12469 headers: file._uploadHeaders,
12470 data: {
12471 op: 'upload'
12472 },
12473 onprogress: saveOptions.onprogress
12474 };
12475 debug('url: %s, file: %o, options: %o', url, fileFormData, options);
12476 var upload = getAdapter('upload');
12477 return upload(url, fileFormData, options).then(function (response) {
12478 debug(response.status, response.data);
12479 if (response.ok === false) {
12480 var error = new Error(response.status);
12481 error.response = response;
12482 throw error;
12483 }
12484 file.attributes.url = uploadInfo.url;
12485 file._bucket = uploadInfo.bucket;
12486 file.id = uploadInfo.objectId;
12487 return file;
12488 }, function (error) {
12489 var response = error.response;
12490
12491 if (response) {
12492 debug(response.status, response.data);
12493 error.statusCode = response.status;
12494 error.response = response.data;
12495 }
12496 throw error;
12497 });
12498};
12499
12500/***/ }),
12501/* 327 */
12502/***/ (function(module, exports, __webpack_require__) {
12503
12504"use strict";
12505
12506
12507var _getPrototypeOf = __webpack_require__(178);
12508
12509var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
12510
12511var _possibleConstructorReturn2 = __webpack_require__(328);
12512
12513var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
12514
12515var _inherits2 = __webpack_require__(329);
12516
12517var _inherits3 = _interopRequireDefault(_inherits2);
12518
12519var _promise = __webpack_require__(3);
12520
12521var _promise2 = _interopRequireDefault(_promise);
12522
12523var _classCallCheck2 = __webpack_require__(336);
12524
12525var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
12526
12527var _createClass2 = __webpack_require__(337);
12528
12529var _createClass3 = _interopRequireDefault(_createClass2);
12530
12531var _getIterator2 = __webpack_require__(186);
12532
12533var _getIterator3 = _interopRequireDefault(_getIterator2);
12534
12535var _stringify = __webpack_require__(21);
12536
12537var _stringify2 = _interopRequireDefault(_stringify);
12538
12539function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12540
12541var _require = __webpack_require__(43),
12542 getAdapter = _require.getAdapter;
12543
12544var debug = __webpack_require__(33)('leancloud:qiniu');
12545var ajax = __webpack_require__(72);
12546var btoa = __webpack_require__(340);
12547
12548var SHARD_THRESHOLD = 1024 * 1024 * 64;
12549
12550var CHUNK_SIZE = 1024 * 1024 * 16;
12551
12552function upload(uploadInfo, data, file) {
12553 var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
12554
12555 // Get the uptoken to upload files to qiniu.
12556 var uptoken = uploadInfo.token;
12557 var url = uploadInfo.upload_url || 'https://upload.qiniup.com';
12558 var fileFormData = {
12559 field: 'file',
12560 data: data,
12561 name: file.attributes.name
12562 };
12563 var options = {
12564 headers: file._uploadHeaders,
12565 data: {
12566 name: file.attributes.name,
12567 key: uploadInfo.key,
12568 token: uptoken
12569 },
12570 onprogress: saveOptions.onprogress
12571 };
12572 debug('url: %s, file: %o, options: %o', url, fileFormData, options);
12573 var upload = getAdapter('upload');
12574 return upload(url, fileFormData, options).then(function (response) {
12575 debug(response.status, response.data);
12576 if (response.ok === false) {
12577 var message = response.status;
12578 if (response.data) {
12579 if (response.data.error) {
12580 message = response.data.error;
12581 } else {
12582 message = (0, _stringify2.default)(response.data);
12583 }
12584 }
12585 var error = new Error(message);
12586 error.response = response;
12587 throw error;
12588 }
12589 file.attributes.url = uploadInfo.url;
12590 file._bucket = uploadInfo.bucket;
12591 file.id = uploadInfo.objectId;
12592 return file;
12593 }, function (error) {
12594 var response = error.response;
12595
12596 if (response) {
12597 debug(response.status, response.data);
12598 error.statusCode = response.status;
12599 error.response = response.data;
12600 }
12601 throw error;
12602 });
12603}
12604
12605function urlSafeBase64(string) {
12606 var base64 = btoa(unescape(encodeURIComponent(string)));
12607 var result = '';
12608 var _iteratorNormalCompletion = true;
12609 var _didIteratorError = false;
12610 var _iteratorError = undefined;
12611
12612 try {
12613 for (var _iterator = (0, _getIterator3.default)(base64), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
12614 var ch = _step.value;
12615
12616 switch (ch) {
12617 case '+':
12618 result += '-';
12619 break;
12620 case '/':
12621 result += '_';
12622 break;
12623 default:
12624 result += ch;
12625 }
12626 }
12627 } catch (err) {
12628 _didIteratorError = true;
12629 _iteratorError = err;
12630 } finally {
12631 try {
12632 if (!_iteratorNormalCompletion && _iterator.return) {
12633 _iterator.return();
12634 }
12635 } finally {
12636 if (_didIteratorError) {
12637 throw _iteratorError;
12638 }
12639 }
12640 }
12641
12642 return result;
12643}
12644
12645var ShardUploader = function () {
12646 function ShardUploader(uploadInfo, data, file, saveOptions) {
12647 var _this = this;
12648
12649 (0, _classCallCheck3.default)(this, ShardUploader);
12650
12651 this.uploadInfo = uploadInfo;
12652 this.data = data;
12653 this.file = file;
12654 this.size = undefined;
12655 this.offset = 0;
12656 this.uploadedChunks = 0;
12657
12658 var key = urlSafeBase64(uploadInfo.key);
12659 var uploadURL = uploadInfo.upload_url || 'https://upload.qiniup.com';
12660 this.baseURL = uploadURL + '/buckets/' + uploadInfo.bucket + '/objects/' + key + '/uploads';
12661 this.upToken = 'UpToken ' + uploadInfo.token;
12662
12663 this.uploaded = 0;
12664 if (saveOptions && saveOptions.onprogress) {
12665 this.onProgress = function (_ref) {
12666 var loaded = _ref.loaded;
12667
12668 loaded += _this.uploadedChunks * CHUNK_SIZE;
12669 if (loaded <= _this.uploaded) {
12670 return;
12671 }
12672 if (_this.size) {
12673 saveOptions.onprogress({
12674 loaded: loaded,
12675 total: _this.size,
12676 percent: loaded / _this.size * 100
12677 });
12678 } else {
12679 saveOptions.onprogress({ loaded: loaded });
12680 }
12681 _this.uploaded = loaded;
12682 };
12683 }
12684 }
12685
12686 /**
12687 * @returns {Promise<string>}
12688 */
12689
12690
12691 (0, _createClass3.default)(ShardUploader, [{
12692 key: 'getUploadId',
12693 value: function getUploadId() {
12694 return ajax({
12695 method: 'POST',
12696 url: this.baseURL,
12697 headers: {
12698 Authorization: this.upToken
12699 }
12700 }).then(function (res) {
12701 return res.uploadId;
12702 });
12703 }
12704 }, {
12705 key: 'getChunk',
12706 value: function getChunk() {
12707 throw new Error('Not implemented');
12708 }
12709
12710 /**
12711 * @param {string} uploadId
12712 * @param {number} partNumber
12713 * @param {any} data
12714 * @returns {Promise<{ partNumber: number, etag: string }>}
12715 */
12716
12717 }, {
12718 key: 'uploadPart',
12719 value: function uploadPart(uploadId, partNumber, data) {
12720 return ajax({
12721 method: 'PUT',
12722 url: this.baseURL + '/' + uploadId + '/' + partNumber,
12723 headers: {
12724 Authorization: this.upToken
12725 },
12726 data: data,
12727 onprogress: this.onProgress
12728 }).then(function (_ref2) {
12729 var etag = _ref2.etag;
12730 return { partNumber: partNumber, etag: etag };
12731 });
12732 }
12733 }, {
12734 key: 'stopUpload',
12735 value: function stopUpload(uploadId) {
12736 return ajax({
12737 method: 'DELETE',
12738 url: this.baseURL + '/' + uploadId,
12739 headers: {
12740 Authorization: this.upToken
12741 }
12742 });
12743 }
12744 }, {
12745 key: 'upload',
12746 value: function upload() {
12747 var _this2 = this;
12748
12749 var parts = [];
12750 return this.getUploadId().then(function (uploadId) {
12751 var uploadPart = function uploadPart() {
12752 return _promise2.default.resolve(_this2.getChunk()).then(function (chunk) {
12753 if (!chunk) {
12754 return;
12755 }
12756 var partNumber = parts.length + 1;
12757 return _this2.uploadPart(uploadId, partNumber, chunk).then(function (part) {
12758 parts.push(part);
12759 _this2.uploadedChunks++;
12760 return uploadPart();
12761 });
12762 }).catch(function (error) {
12763 return _this2.stopUpload(uploadId).then(function () {
12764 return _promise2.default.reject(error);
12765 });
12766 });
12767 };
12768
12769 return uploadPart().then(function () {
12770 return ajax({
12771 method: 'POST',
12772 url: _this2.baseURL + '/' + uploadId,
12773 headers: {
12774 Authorization: _this2.upToken
12775 },
12776 data: {
12777 parts: parts,
12778 fname: _this2.file.attributes.name,
12779 mimeType: _this2.file.attributes.mime_type
12780 }
12781 });
12782 });
12783 }).then(function () {
12784 _this2.file.attributes.url = _this2.uploadInfo.url;
12785 _this2.file._bucket = _this2.uploadInfo.bucket;
12786 _this2.file.id = _this2.uploadInfo.objectId;
12787 return _this2.file;
12788 });
12789 }
12790 }]);
12791 return ShardUploader;
12792}();
12793
12794var BlobUploader = function (_ShardUploader) {
12795 (0, _inherits3.default)(BlobUploader, _ShardUploader);
12796
12797 function BlobUploader(uploadInfo, data, file, saveOptions) {
12798 (0, _classCallCheck3.default)(this, BlobUploader);
12799
12800 var _this3 = (0, _possibleConstructorReturn3.default)(this, (BlobUploader.__proto__ || (0, _getPrototypeOf2.default)(BlobUploader)).call(this, uploadInfo, data, file, saveOptions));
12801
12802 _this3.size = data.size;
12803 return _this3;
12804 }
12805
12806 /**
12807 * @returns {Blob | null}
12808 */
12809
12810
12811 (0, _createClass3.default)(BlobUploader, [{
12812 key: 'getChunk',
12813 value: function getChunk() {
12814 if (this.offset >= this.size) {
12815 return null;
12816 }
12817 var chunk = this.data.slice(this.offset, this.offset + CHUNK_SIZE);
12818 this.offset += chunk.size;
12819 return chunk;
12820 }
12821 }]);
12822 return BlobUploader;
12823}(ShardUploader);
12824
12825function isBlob(data) {
12826 return typeof Blob !== 'undefined' && data instanceof Blob;
12827}
12828
12829module.exports = function (uploadInfo, data, file) {
12830 var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
12831
12832 if (isBlob(data) && data.size >= SHARD_THRESHOLD) {
12833 return new BlobUploader(uploadInfo, data, file, saveOptions).upload();
12834 }
12835 return upload(uploadInfo, data, file, saveOptions);
12836};
12837
12838/***/ }),
12839/* 328 */
12840/***/ (function(module, exports, __webpack_require__) {
12841
12842"use strict";
12843
12844
12845exports.__esModule = true;
12846
12847var _typeof2 = __webpack_require__(23);
12848
12849var _typeof3 = _interopRequireDefault(_typeof2);
12850
12851function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12852
12853exports.default = function (self, call) {
12854 if (!self) {
12855 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
12856 }
12857
12858 return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self;
12859};
12860
12861/***/ }),
12862/* 329 */
12863/***/ (function(module, exports, __webpack_require__) {
12864
12865"use strict";
12866
12867
12868exports.__esModule = true;
12869
12870var _setPrototypeOf = __webpack_require__(330);
12871
12872var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf);
12873
12874var _create = __webpack_require__(111);
12875
12876var _create2 = _interopRequireDefault(_create);
12877
12878var _typeof2 = __webpack_require__(23);
12879
12880var _typeof3 = _interopRequireDefault(_typeof2);
12881
12882function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12883
12884exports.default = function (subClass, superClass) {
12885 if (typeof superClass !== "function" && superClass !== null) {
12886 throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass)));
12887 }
12888
12889 subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, {
12890 constructor: {
12891 value: subClass,
12892 enumerable: false,
12893 writable: true,
12894 configurable: true
12895 }
12896 });
12897 if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass;
12898};
12899
12900/***/ }),
12901/* 330 */
12902/***/ (function(module, exports, __webpack_require__) {
12903
12904module.exports = { "default": __webpack_require__(331), __esModule: true };
12905
12906/***/ }),
12907/* 331 */
12908/***/ (function(module, exports, __webpack_require__) {
12909
12910__webpack_require__(332);
12911module.exports = __webpack_require__(1).Object.setPrototypeOf;
12912
12913
12914/***/ }),
12915/* 332 */
12916/***/ (function(module, exports, __webpack_require__) {
12917
12918// 19.1.3.19 Object.setPrototypeOf(O, proto)
12919var $export = __webpack_require__(4);
12920$export($export.S, 'Object', { setPrototypeOf: __webpack_require__(333).set });
12921
12922
12923/***/ }),
12924/* 333 */
12925/***/ (function(module, exports, __webpack_require__) {
12926
12927// Works with __proto__ only. Old v8 can't work with null proto objects.
12928/* eslint-disable no-proto */
12929var isObject = __webpack_require__(9);
12930var anObject = __webpack_require__(15);
12931var check = function (O, proto) {
12932 anObject(O);
12933 if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
12934};
12935module.exports = {
12936 set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
12937 function (test, buggy, set) {
12938 try {
12939 set = __webpack_require__(22)(Function.call, __webpack_require__(76).f(Object.prototype, '__proto__').set, 2);
12940 set(test, []);
12941 buggy = !(test instanceof Array);
12942 } catch (e) { buggy = true; }
12943 return function setPrototypeOf(O, proto) {
12944 check(O, proto);
12945 if (buggy) O.__proto__ = proto;
12946 else set(O, proto);
12947 return O;
12948 };
12949 }({}, false) : undefined),
12950 check: check
12951};
12952
12953
12954/***/ }),
12955/* 334 */
12956/***/ (function(module, exports, __webpack_require__) {
12957
12958__webpack_require__(335);
12959var $Object = __webpack_require__(1).Object;
12960module.exports = function create(P, D) {
12961 return $Object.create(P, D);
12962};
12963
12964
12965/***/ }),
12966/* 335 */
12967/***/ (function(module, exports, __webpack_require__) {
12968
12969var $export = __webpack_require__(4);
12970// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
12971$export($export.S, 'Object', { create: __webpack_require__(60) });
12972
12973
12974/***/ }),
12975/* 336 */
12976/***/ (function(module, exports, __webpack_require__) {
12977
12978"use strict";
12979
12980
12981exports.__esModule = true;
12982
12983exports.default = function (instance, Constructor) {
12984 if (!(instance instanceof Constructor)) {
12985 throw new TypeError("Cannot call a class as a function");
12986 }
12987};
12988
12989/***/ }),
12990/* 337 */
12991/***/ (function(module, exports, __webpack_require__) {
12992
12993"use strict";
12994
12995
12996exports.__esModule = true;
12997
12998var _defineProperty = __webpack_require__(71);
12999
13000var _defineProperty2 = _interopRequireDefault(_defineProperty);
13001
13002function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13003
13004exports.default = function () {
13005 function defineProperties(target, props) {
13006 for (var i = 0; i < props.length; i++) {
13007 var descriptor = props[i];
13008 descriptor.enumerable = descriptor.enumerable || false;
13009 descriptor.configurable = true;
13010 if ("value" in descriptor) descriptor.writable = true;
13011 (0, _defineProperty2.default)(target, descriptor.key, descriptor);
13012 }
13013 }
13014
13015 return function (Constructor, protoProps, staticProps) {
13016 if (protoProps) defineProperties(Constructor.prototype, protoProps);
13017 if (staticProps) defineProperties(Constructor, staticProps);
13018 return Constructor;
13019 };
13020}();
13021
13022/***/ }),
13023/* 338 */
13024/***/ (function(module, exports, __webpack_require__) {
13025
13026__webpack_require__(37);
13027__webpack_require__(35);
13028module.exports = __webpack_require__(339);
13029
13030
13031/***/ }),
13032/* 339 */
13033/***/ (function(module, exports, __webpack_require__) {
13034
13035var anObject = __webpack_require__(15);
13036var get = __webpack_require__(90);
13037module.exports = __webpack_require__(1).getIterator = function (it) {
13038 var iterFn = get(it);
13039 if (typeof iterFn != 'function') throw TypeError(it + ' is not iterable!');
13040 return anObject(iterFn.call(it));
13041};
13042
13043
13044/***/ }),
13045/* 340 */
13046/***/ (function(module, exports, __webpack_require__) {
13047
13048"use strict";
13049
13050
13051// base64 character set, plus padding character (=)
13052var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
13053
13054module.exports = function (string) {
13055 var result = '';
13056
13057 for (var i = 0; i < string.length;) {
13058 var a = string.charCodeAt(i++);
13059 var b = string.charCodeAt(i++);
13060 var c = string.charCodeAt(i++);
13061 if (a > 255 || b > 255 || c > 255) {
13062 throw new TypeError('Failed to encode base64: The string to be encoded contains characters outside of the Latin1 range.');
13063 }
13064
13065 var bitmap = a << 16 | b << 8 | c;
13066 result += b64.charAt(bitmap >> 18 & 63) + b64.charAt(bitmap >> 12 & 63) + b64.charAt(bitmap >> 6 & 63) + b64.charAt(bitmap & 63);
13067 }
13068
13069 // To determine the final padding
13070 var rest = string.length % 3;
13071 // If there's need of padding, replace the last 'A's with equal signs
13072 return rest ? result.slice(0, rest - 3) + '==='.substring(rest) : result;
13073};
13074
13075/***/ }),
13076/* 341 */
13077/***/ (function(module, exports, __webpack_require__) {
13078
13079"use strict";
13080
13081
13082var _ = __webpack_require__(0);
13083var ajax = __webpack_require__(72);
13084
13085module.exports = function upload(uploadInfo, data, file) {
13086 var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
13087
13088
13089 return ajax({
13090 url: uploadInfo.upload_url,
13091 method: 'PUT',
13092 data: data,
13093 headers: _.extend({
13094 'Content-Type': file.get('mime_type'),
13095 'Cache-Control': 'public, max-age=31536000'
13096 }, file._uploadHeaders),
13097 onprogress: saveOptions.onprogress
13098 }).then(function () {
13099 file.attributes.url = uploadInfo.url;
13100 file._bucket = uploadInfo.bucket;
13101 file.id = uploadInfo.objectId;
13102 return file;
13103 });
13104};
13105
13106/***/ }),
13107/* 342 */
13108/***/ (function(module, exports, __webpack_require__) {
13109
13110(function(){
13111 var crypt = __webpack_require__(343),
13112 utf8 = __webpack_require__(187).utf8,
13113 isBuffer = __webpack_require__(344),
13114 bin = __webpack_require__(187).bin,
13115
13116 // The core
13117 md5 = function (message, options) {
13118 // Convert to byte array
13119 if (message.constructor == String)
13120 if (options && options.encoding === 'binary')
13121 message = bin.stringToBytes(message);
13122 else
13123 message = utf8.stringToBytes(message);
13124 else if (isBuffer(message))
13125 message = Array.prototype.slice.call(message, 0);
13126 else if (!Array.isArray(message))
13127 message = message.toString();
13128 // else, assume byte array already
13129
13130 var m = crypt.bytesToWords(message),
13131 l = message.length * 8,
13132 a = 1732584193,
13133 b = -271733879,
13134 c = -1732584194,
13135 d = 271733878;
13136
13137 // Swap endian
13138 for (var i = 0; i < m.length; i++) {
13139 m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF |
13140 ((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00;
13141 }
13142
13143 // Padding
13144 m[l >>> 5] |= 0x80 << (l % 32);
13145 m[(((l + 64) >>> 9) << 4) + 14] = l;
13146
13147 // Method shortcuts
13148 var FF = md5._ff,
13149 GG = md5._gg,
13150 HH = md5._hh,
13151 II = md5._ii;
13152
13153 for (var i = 0; i < m.length; i += 16) {
13154
13155 var aa = a,
13156 bb = b,
13157 cc = c,
13158 dd = d;
13159
13160 a = FF(a, b, c, d, m[i+ 0], 7, -680876936);
13161 d = FF(d, a, b, c, m[i+ 1], 12, -389564586);
13162 c = FF(c, d, a, b, m[i+ 2], 17, 606105819);
13163 b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);
13164 a = FF(a, b, c, d, m[i+ 4], 7, -176418897);
13165 d = FF(d, a, b, c, m[i+ 5], 12, 1200080426);
13166 c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);
13167 b = FF(b, c, d, a, m[i+ 7], 22, -45705983);
13168 a = FF(a, b, c, d, m[i+ 8], 7, 1770035416);
13169 d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);
13170 c = FF(c, d, a, b, m[i+10], 17, -42063);
13171 b = FF(b, c, d, a, m[i+11], 22, -1990404162);
13172 a = FF(a, b, c, d, m[i+12], 7, 1804603682);
13173 d = FF(d, a, b, c, m[i+13], 12, -40341101);
13174 c = FF(c, d, a, b, m[i+14], 17, -1502002290);
13175 b = FF(b, c, d, a, m[i+15], 22, 1236535329);
13176
13177 a = GG(a, b, c, d, m[i+ 1], 5, -165796510);
13178 d = GG(d, a, b, c, m[i+ 6], 9, -1069501632);
13179 c = GG(c, d, a, b, m[i+11], 14, 643717713);
13180 b = GG(b, c, d, a, m[i+ 0], 20, -373897302);
13181 a = GG(a, b, c, d, m[i+ 5], 5, -701558691);
13182 d = GG(d, a, b, c, m[i+10], 9, 38016083);
13183 c = GG(c, d, a, b, m[i+15], 14, -660478335);
13184 b = GG(b, c, d, a, m[i+ 4], 20, -405537848);
13185 a = GG(a, b, c, d, m[i+ 9], 5, 568446438);
13186 d = GG(d, a, b, c, m[i+14], 9, -1019803690);
13187 c = GG(c, d, a, b, m[i+ 3], 14, -187363961);
13188 b = GG(b, c, d, a, m[i+ 8], 20, 1163531501);
13189 a = GG(a, b, c, d, m[i+13], 5, -1444681467);
13190 d = GG(d, a, b, c, m[i+ 2], 9, -51403784);
13191 c = GG(c, d, a, b, m[i+ 7], 14, 1735328473);
13192 b = GG(b, c, d, a, m[i+12], 20, -1926607734);
13193
13194 a = HH(a, b, c, d, m[i+ 5], 4, -378558);
13195 d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);
13196 c = HH(c, d, a, b, m[i+11], 16, 1839030562);
13197 b = HH(b, c, d, a, m[i+14], 23, -35309556);
13198 a = HH(a, b, c, d, m[i+ 1], 4, -1530992060);
13199 d = HH(d, a, b, c, m[i+ 4], 11, 1272893353);
13200 c = HH(c, d, a, b, m[i+ 7], 16, -155497632);
13201 b = HH(b, c, d, a, m[i+10], 23, -1094730640);
13202 a = HH(a, b, c, d, m[i+13], 4, 681279174);
13203 d = HH(d, a, b, c, m[i+ 0], 11, -358537222);
13204 c = HH(c, d, a, b, m[i+ 3], 16, -722521979);
13205 b = HH(b, c, d, a, m[i+ 6], 23, 76029189);
13206 a = HH(a, b, c, d, m[i+ 9], 4, -640364487);
13207 d = HH(d, a, b, c, m[i+12], 11, -421815835);
13208 c = HH(c, d, a, b, m[i+15], 16, 530742520);
13209 b = HH(b, c, d, a, m[i+ 2], 23, -995338651);
13210
13211 a = II(a, b, c, d, m[i+ 0], 6, -198630844);
13212 d = II(d, a, b, c, m[i+ 7], 10, 1126891415);
13213 c = II(c, d, a, b, m[i+14], 15, -1416354905);
13214 b = II(b, c, d, a, m[i+ 5], 21, -57434055);
13215 a = II(a, b, c, d, m[i+12], 6, 1700485571);
13216 d = II(d, a, b, c, m[i+ 3], 10, -1894986606);
13217 c = II(c, d, a, b, m[i+10], 15, -1051523);
13218 b = II(b, c, d, a, m[i+ 1], 21, -2054922799);
13219 a = II(a, b, c, d, m[i+ 8], 6, 1873313359);
13220 d = II(d, a, b, c, m[i+15], 10, -30611744);
13221 c = II(c, d, a, b, m[i+ 6], 15, -1560198380);
13222 b = II(b, c, d, a, m[i+13], 21, 1309151649);
13223 a = II(a, b, c, d, m[i+ 4], 6, -145523070);
13224 d = II(d, a, b, c, m[i+11], 10, -1120210379);
13225 c = II(c, d, a, b, m[i+ 2], 15, 718787259);
13226 b = II(b, c, d, a, m[i+ 9], 21, -343485551);
13227
13228 a = (a + aa) >>> 0;
13229 b = (b + bb) >>> 0;
13230 c = (c + cc) >>> 0;
13231 d = (d + dd) >>> 0;
13232 }
13233
13234 return crypt.endian([a, b, c, d]);
13235 };
13236
13237 // Auxiliary functions
13238 md5._ff = function (a, b, c, d, x, s, t) {
13239 var n = a + (b & c | ~b & d) + (x >>> 0) + t;
13240 return ((n << s) | (n >>> (32 - s))) + b;
13241 };
13242 md5._gg = function (a, b, c, d, x, s, t) {
13243 var n = a + (b & d | c & ~d) + (x >>> 0) + t;
13244 return ((n << s) | (n >>> (32 - s))) + b;
13245 };
13246 md5._hh = function (a, b, c, d, x, s, t) {
13247 var n = a + (b ^ c ^ d) + (x >>> 0) + t;
13248 return ((n << s) | (n >>> (32 - s))) + b;
13249 };
13250 md5._ii = function (a, b, c, d, x, s, t) {
13251 var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;
13252 return ((n << s) | (n >>> (32 - s))) + b;
13253 };
13254
13255 // Package private blocksize
13256 md5._blocksize = 16;
13257 md5._digestsize = 16;
13258
13259 module.exports = function (message, options) {
13260 if (message === undefined || message === null)
13261 throw new Error('Illegal argument ' + message);
13262
13263 var digestbytes = crypt.wordsToBytes(md5(message, options));
13264 return options && options.asBytes ? digestbytes :
13265 options && options.asString ? bin.bytesToString(digestbytes) :
13266 crypt.bytesToHex(digestbytes);
13267 };
13268
13269})();
13270
13271
13272/***/ }),
13273/* 343 */
13274/***/ (function(module, exports) {
13275
13276(function() {
13277 var base64map
13278 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
13279
13280 crypt = {
13281 // Bit-wise rotation left
13282 rotl: function(n, b) {
13283 return (n << b) | (n >>> (32 - b));
13284 },
13285
13286 // Bit-wise rotation right
13287 rotr: function(n, b) {
13288 return (n << (32 - b)) | (n >>> b);
13289 },
13290
13291 // Swap big-endian to little-endian and vice versa
13292 endian: function(n) {
13293 // If number given, swap endian
13294 if (n.constructor == Number) {
13295 return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;
13296 }
13297
13298 // Else, assume array and swap all items
13299 for (var i = 0; i < n.length; i++)
13300 n[i] = crypt.endian(n[i]);
13301 return n;
13302 },
13303
13304 // Generate an array of any length of random bytes
13305 randomBytes: function(n) {
13306 for (var bytes = []; n > 0; n--)
13307 bytes.push(Math.floor(Math.random() * 256));
13308 return bytes;
13309 },
13310
13311 // Convert a byte array to big-endian 32-bit words
13312 bytesToWords: function(bytes) {
13313 for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)
13314 words[b >>> 5] |= bytes[i] << (24 - b % 32);
13315 return words;
13316 },
13317
13318 // Convert big-endian 32-bit words to a byte array
13319 wordsToBytes: function(words) {
13320 for (var bytes = [], b = 0; b < words.length * 32; b += 8)
13321 bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
13322 return bytes;
13323 },
13324
13325 // Convert a byte array to a hex string
13326 bytesToHex: function(bytes) {
13327 for (var hex = [], i = 0; i < bytes.length; i++) {
13328 hex.push((bytes[i] >>> 4).toString(16));
13329 hex.push((bytes[i] & 0xF).toString(16));
13330 }
13331 return hex.join('');
13332 },
13333
13334 // Convert a hex string to a byte array
13335 hexToBytes: function(hex) {
13336 for (var bytes = [], c = 0; c < hex.length; c += 2)
13337 bytes.push(parseInt(hex.substr(c, 2), 16));
13338 return bytes;
13339 },
13340
13341 // Convert a byte array to a base-64 string
13342 bytesToBase64: function(bytes) {
13343 for (var base64 = [], i = 0; i < bytes.length; i += 3) {
13344 var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
13345 for (var j = 0; j < 4; j++)
13346 if (i * 8 + j * 6 <= bytes.length * 8)
13347 base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));
13348 else
13349 base64.push('=');
13350 }
13351 return base64.join('');
13352 },
13353
13354 // Convert a base-64 string to a byte array
13355 base64ToBytes: function(base64) {
13356 // Remove non-base-64 characters
13357 base64 = base64.replace(/[^A-Z0-9+\/]/ig, '');
13358
13359 for (var bytes = [], i = 0, imod4 = 0; i < base64.length;
13360 imod4 = ++i % 4) {
13361 if (imod4 == 0) continue;
13362 bytes.push(((base64map.indexOf(base64.charAt(i - 1))
13363 & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))
13364 | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));
13365 }
13366 return bytes;
13367 }
13368 };
13369
13370 module.exports = crypt;
13371})();
13372
13373
13374/***/ }),
13375/* 344 */
13376/***/ (function(module, exports) {
13377
13378/*!
13379 * Determine if an object is a Buffer
13380 *
13381 * @author Feross Aboukhadijeh <https://feross.org>
13382 * @license MIT
13383 */
13384
13385// The _isBuffer check is for Safari 5-7 support, because it's missing
13386// Object.prototype.constructor. Remove this eventually
13387module.exports = function (obj) {
13388 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
13389}
13390
13391function isBuffer (obj) {
13392 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
13393}
13394
13395// For Node v0.10 support. Remove this eventually.
13396function isSlowBuffer (obj) {
13397 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
13398}
13399
13400
13401/***/ }),
13402/* 345 */
13403/***/ (function(module, exports, __webpack_require__) {
13404
13405"use strict";
13406
13407
13408var dataURItoBlob = function dataURItoBlob(dataURI, type) {
13409 var byteString;
13410
13411 // 传入的 base64,不是 dataURL
13412 if (dataURI.indexOf('base64') < 0) {
13413 byteString = atob(dataURI);
13414 } else if (dataURI.split(',')[0].indexOf('base64') >= 0) {
13415 type = type || dataURI.split(',')[0].split(':')[1].split(';')[0];
13416 byteString = atob(dataURI.split(',')[1]);
13417 } else {
13418 byteString = unescape(dataURI.split(',')[1]);
13419 }
13420 var ia = new Uint8Array(byteString.length);
13421 for (var i = 0; i < byteString.length; i++) {
13422 ia[i] = byteString.charCodeAt(i);
13423 }
13424 return new Blob([ia], { type: type });
13425};
13426
13427module.exports = dataURItoBlob;
13428
13429/***/ }),
13430/* 346 */
13431/***/ (function(module, exports, __webpack_require__) {
13432
13433"use strict";
13434
13435
13436var _getOwnPropertyDescriptor = __webpack_require__(188);
13437
13438var _getOwnPropertyDescriptor2 = _interopRequireDefault(_getOwnPropertyDescriptor);
13439
13440var _stringify = __webpack_require__(21);
13441
13442var _stringify2 = _interopRequireDefault(_stringify);
13443
13444var _slicedToArray2 = __webpack_require__(349);
13445
13446var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
13447
13448var _promise = __webpack_require__(3);
13449
13450var _promise2 = _interopRequireDefault(_promise);
13451
13452function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13453
13454var _ = __webpack_require__(0);
13455var AVError = __webpack_require__(34);
13456
13457var _require = __webpack_require__(14),
13458 _request = _require._request;
13459
13460var _require2 = __webpack_require__(19),
13461 isNullOrUndefined = _require2.isNullOrUndefined,
13462 ensureArray = _require2.ensureArray,
13463 transformFetchOptions = _require2.transformFetchOptions,
13464 setValue = _require2.setValue,
13465 findValue = _require2.findValue,
13466 isPlainObject = _require2.isPlainObject,
13467 continueWhile = _require2.continueWhile;
13468
13469var recursiveToPointer = function recursiveToPointer(value) {
13470 if (_.isArray(value)) return value.map(recursiveToPointer);
13471 if (isPlainObject(value)) return _.mapObject(value, recursiveToPointer);
13472 if (_.isObject(value) && value._toPointer) return value._toPointer();
13473 return value;
13474};
13475
13476var RESERVED_KEYS = ['objectId', 'createdAt', 'updatedAt'];
13477var checkReservedKey = function checkReservedKey(key) {
13478 if (RESERVED_KEYS.indexOf(key) !== -1) {
13479 throw new Error('key[' + key + '] is reserved');
13480 }
13481};
13482
13483var handleBatchResults = function handleBatchResults(results) {
13484 var firstError = _.find(results, function (result) {
13485 return result instanceof Error;
13486 });
13487 if (!firstError) {
13488 return results;
13489 }
13490 var error = new AVError(firstError.code, firstError.message);
13491 error.results = results;
13492 throw error;
13493};
13494
13495// Helper function to get a value from a Backbone object as a property
13496// or as a function.
13497function getValue(object, prop) {
13498 if (!(object && object[prop])) {
13499 return null;
13500 }
13501 return _.isFunction(object[prop]) ? object[prop]() : object[prop];
13502}
13503
13504// AV.Object is analogous to the Java AVObject.
13505// It also implements the same interface as a Backbone model.
13506
13507module.exports = function (AV) {
13508 /**
13509 * Creates a new model with defined attributes. A client id (cid) is
13510 * automatically generated and assigned for you.
13511 *
13512 * <p>You won't normally call this method directly. It is recommended that
13513 * you use a subclass of <code>AV.Object</code> instead, created by calling
13514 * <code>extend</code>.</p>
13515 *
13516 * <p>However, if you don't want to use a subclass, or aren't sure which
13517 * subclass is appropriate, you can use this form:<pre>
13518 * var object = new AV.Object("ClassName");
13519 * </pre>
13520 * That is basically equivalent to:<pre>
13521 * var MyClass = AV.Object.extend("ClassName");
13522 * var object = new MyClass();
13523 * </pre></p>
13524 *
13525 * @param {Object} attributes The initial set of data to store in the object.
13526 * @param {Object} options A set of Backbone-like options for creating the
13527 * object. The only option currently supported is "collection".
13528 * @see AV.Object.extend
13529 *
13530 * @class
13531 *
13532 * <p>The fundamental unit of AV data, which implements the Backbone Model
13533 * interface.</p>
13534 */
13535 AV.Object = function (attributes, options) {
13536 // Allow new AV.Object("ClassName") as a shortcut to _create.
13537 if (_.isString(attributes)) {
13538 return AV.Object._create.apply(this, arguments);
13539 }
13540
13541 attributes = attributes || {};
13542 if (options && options.parse) {
13543 attributes = this.parse(attributes);
13544 attributes = this._mergeMagicFields(attributes);
13545 }
13546 var defaults = getValue(this, 'defaults');
13547 if (defaults) {
13548 attributes = _.extend({}, defaults, attributes);
13549 }
13550 if (options && options.collection) {
13551 this.collection = options.collection;
13552 }
13553
13554 this._serverData = {}; // The last known data for this object from cloud.
13555 this._opSetQueue = [{}]; // List of sets of changes to the data.
13556 this._flags = {};
13557 this.attributes = {}; // The best estimate of this's current data.
13558
13559 this._hashedJSON = {}; // Hash of values of containers at last save.
13560 this._escapedAttributes = {};
13561 this.cid = _.uniqueId('c');
13562 this.changed = {};
13563 this._silent = {};
13564 this._pending = {};
13565 this.set(attributes, { silent: true });
13566 this.changed = {};
13567 this._silent = {};
13568 this._pending = {};
13569 this._hasData = true;
13570 this._previousAttributes = _.clone(this.attributes);
13571 this.initialize.apply(this, arguments);
13572 };
13573
13574 /**
13575 * @lends AV.Object.prototype
13576 * @property {String} id The objectId of the AV Object.
13577 */
13578
13579 /**
13580 * Saves the given list of AV.Object.
13581 * If any error is encountered, stops and calls the error handler.
13582 *
13583 * @example
13584 * AV.Object.saveAll([object1, object2, ...]).then(function(list) {
13585 * // All the objects were saved.
13586 * }, function(error) {
13587 * // An error occurred while saving one of the objects.
13588 * });
13589 *
13590 * @param {Array} list A list of <code>AV.Object</code>.
13591 */
13592 AV.Object.saveAll = function (list, options) {
13593 return AV.Object._deepSaveAsync(list, null, options);
13594 };
13595
13596 /**
13597 * Fetch the given list of AV.Object.
13598 *
13599 * @param {AV.Object[]} objects A list of <code>AV.Object</code>
13600 * @param {AuthOptions} options
13601 * @return {Promise.<AV.Object[]>} The given list of <code>AV.Object</code>, updated
13602 */
13603
13604 AV.Object.fetchAll = function (objects, options) {
13605 return _promise2.default.resolve().then(function () {
13606 return _request('batch', null, null, 'POST', {
13607 requests: _.map(objects, function (object) {
13608 if (!object.className) throw new Error('object must have className to fetch');
13609 if (!object.id) throw new Error('object must have id to fetch');
13610 if (object.dirty()) throw new Error('object is modified but not saved');
13611 return {
13612 method: 'GET',
13613 path: '/1.1/classes/' + object.className + '/' + object.id
13614 };
13615 })
13616 }, options);
13617 }).then(function (response) {
13618 var results = _.map(objects, function (object, i) {
13619 if (response[i].success) {
13620 var fetchedAttrs = object.parse(response[i].success);
13621 object._cleanupUnsetKeys(fetchedAttrs);
13622 object._finishFetch(fetchedAttrs);
13623 return object;
13624 }
13625 if (response[i].success === null) {
13626 return new AVError(AVError.OBJECT_NOT_FOUND, 'Object not found.');
13627 }
13628 return new AVError(response[i].error.code, response[i].error.error);
13629 });
13630 return handleBatchResults(results);
13631 });
13632 };
13633
13634 // Attach all inheritable methods to the AV.Object prototype.
13635 _.extend(AV.Object.prototype, AV.Events,
13636 /** @lends AV.Object.prototype */{
13637 _fetchWhenSave: false,
13638
13639 /**
13640 * Initialize is an empty function by default. Override it with your own
13641 * initialization logic.
13642 */
13643 initialize: function initialize() {},
13644
13645 /**
13646 * Set whether to enable fetchWhenSave option when updating object.
13647 * When set true, SDK would fetch the latest object after saving.
13648 * Default is false.
13649 *
13650 * @deprecated use AV.Object#save with options.fetchWhenSave instead
13651 * @param {boolean} enable true to enable fetchWhenSave option.
13652 */
13653 fetchWhenSave: function fetchWhenSave(enable) {
13654 console.warn('AV.Object#fetchWhenSave is deprecated, use AV.Object#save with options.fetchWhenSave instead.');
13655 if (!_.isBoolean(enable)) {
13656 throw new Error('Expect boolean value for fetchWhenSave');
13657 }
13658 this._fetchWhenSave = enable;
13659 },
13660
13661 /**
13662 * Returns the object's objectId.
13663 * @return {String} the objectId.
13664 */
13665 getObjectId: function getObjectId() {
13666 return this.id;
13667 },
13668
13669 /**
13670 * Returns the object's createdAt attribute.
13671 * @return {Date}
13672 */
13673 getCreatedAt: function getCreatedAt() {
13674 return this.createdAt;
13675 },
13676
13677 /**
13678 * Returns the object's updatedAt attribute.
13679 * @return {Date}
13680 */
13681 getUpdatedAt: function getUpdatedAt() {
13682 return this.updatedAt;
13683 },
13684
13685 /**
13686 * Returns a JSON version of the object.
13687 * @return {Object}
13688 */
13689 toJSON: function toJSON(key, holder) {
13690 var seenObjects = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
13691
13692 return this._toFullJSON(seenObjects, false);
13693 },
13694
13695 /**
13696 * Returns a JSON version of the object with meta data.
13697 * Inverse to {@link AV.parseJSON}
13698 * @since 3.0.0
13699 * @return {Object}
13700 */
13701 toFullJSON: function toFullJSON() {
13702 var seenObjects = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
13703
13704 return this._toFullJSON(seenObjects);
13705 },
13706
13707
13708 _toFullJSON: function _toFullJSON(seenObjects) {
13709 var _this = this;
13710
13711 var full = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
13712
13713 var json = _.clone(this.attributes);
13714 if (_.isArray(seenObjects)) {
13715 var newSeenObjects = seenObjects.concat(this);
13716 }
13717 AV._objectEach(json, function (val, key) {
13718 json[key] = AV._encode(val, newSeenObjects, undefined, full);
13719 });
13720 AV._objectEach(this._operations, function (val, key) {
13721 json[key] = val;
13722 });
13723
13724 if (_.has(this, 'id')) {
13725 json.objectId = this.id;
13726 }
13727 ['createdAt', 'updatedAt'].forEach(function (key) {
13728 if (_.has(_this, key)) {
13729 var val = _this[key];
13730 json[key] = _.isDate(val) ? val.toJSON() : val;
13731 }
13732 });
13733 if (full) {
13734 json.__type = 'Object';
13735 if (_.isArray(seenObjects) && seenObjects.length) json.__type = 'Pointer';
13736 json.className = this.className;
13737 }
13738 return json;
13739 },
13740
13741 /**
13742 * Updates _hashedJSON to reflect the current state of this object.
13743 * Adds any changed hash values to the set of pending changes.
13744 * @private
13745 */
13746 _refreshCache: function _refreshCache() {
13747 var self = this;
13748 if (self._refreshingCache) {
13749 return;
13750 }
13751 self._refreshingCache = true;
13752 AV._objectEach(this.attributes, function (value, key) {
13753 if (value instanceof AV.Object) {
13754 value._refreshCache();
13755 } else if (_.isObject(value)) {
13756 if (self._resetCacheForKey(key)) {
13757 self.set(key, new AV.Op.Set(value), { silent: true });
13758 }
13759 }
13760 });
13761 delete self._refreshingCache;
13762 },
13763
13764 /**
13765 * Returns true if this object has been modified since its last
13766 * save/refresh. If an attribute is specified, it returns true only if that
13767 * particular attribute has been modified since the last save/refresh.
13768 * @param {String} attr An attribute name (optional).
13769 * @return {Boolean}
13770 */
13771 dirty: function dirty(attr) {
13772 this._refreshCache();
13773
13774 var currentChanges = _.last(this._opSetQueue);
13775
13776 if (attr) {
13777 return currentChanges[attr] ? true : false;
13778 }
13779 if (!this.id) {
13780 return true;
13781 }
13782 if (_.keys(currentChanges).length > 0) {
13783 return true;
13784 }
13785 return false;
13786 },
13787
13788 /**
13789 * Returns the keys of the modified attribute since its last save/refresh.
13790 * @return {String[]}
13791 */
13792 dirtyKeys: function dirtyKeys() {
13793 this._refreshCache();
13794 var currentChanges = _.last(this._opSetQueue);
13795 return _.keys(currentChanges);
13796 },
13797
13798 /**
13799 * Gets a Pointer referencing this Object.
13800 * @private
13801 */
13802 _toPointer: function _toPointer() {
13803 // if (!this.id) {
13804 // throw new Error("Can't serialize an unsaved AV.Object");
13805 // }
13806 return {
13807 __type: 'Pointer',
13808 className: this.className,
13809 objectId: this.id
13810 };
13811 },
13812
13813 /**
13814 * Gets the value of an attribute.
13815 * @param {String} attr The string name of an attribute.
13816 */
13817 get: function get(attr) {
13818 switch (attr) {
13819 case 'objectId':
13820 return this.id;
13821 case 'createdAt':
13822 case 'updatedAt':
13823 return this[attr];
13824 default:
13825 return this.attributes[attr];
13826 }
13827 },
13828
13829 /**
13830 * Gets a relation on the given class for the attribute.
13831 * @param {String} attr The attribute to get the relation for.
13832 * @return {AV.Relation}
13833 */
13834 relation: function relation(attr) {
13835 var value = this.get(attr);
13836 if (value) {
13837 if (!(value instanceof AV.Relation)) {
13838 throw new Error('Called relation() on non-relation field ' + attr);
13839 }
13840 value._ensureParentAndKey(this, attr);
13841 return value;
13842 } else {
13843 return new AV.Relation(this, attr);
13844 }
13845 },
13846
13847 /**
13848 * Gets the HTML-escaped value of an attribute.
13849 */
13850 escape: function escape(attr) {
13851 var html = this._escapedAttributes[attr];
13852 if (html) {
13853 return html;
13854 }
13855 var val = this.attributes[attr];
13856 var escaped;
13857 if (isNullOrUndefined(val)) {
13858 escaped = '';
13859 } else {
13860 escaped = _.escape(val.toString());
13861 }
13862 this._escapedAttributes[attr] = escaped;
13863 return escaped;
13864 },
13865
13866 /**
13867 * Returns <code>true</code> if the attribute contains a value that is not
13868 * null or undefined.
13869 * @param {String} attr The string name of the attribute.
13870 * @return {Boolean}
13871 */
13872 has: function has(attr) {
13873 return !isNullOrUndefined(this.attributes[attr]);
13874 },
13875
13876 /**
13877 * Pulls "special" fields like objectId, createdAt, etc. out of attrs
13878 * and puts them on "this" directly. Removes them from attrs.
13879 * @param attrs - A dictionary with the data for this AV.Object.
13880 * @private
13881 */
13882 _mergeMagicFields: function _mergeMagicFields(attrs) {
13883 // Check for changes of magic fields.
13884 var model = this;
13885 var specialFields = ['objectId', 'createdAt', 'updatedAt'];
13886 AV._arrayEach(specialFields, function (attr) {
13887 if (attrs[attr]) {
13888 if (attr === 'objectId') {
13889 model.id = attrs[attr];
13890 } else if ((attr === 'createdAt' || attr === 'updatedAt') && !_.isDate(attrs[attr])) {
13891 model[attr] = AV._parseDate(attrs[attr]);
13892 } else {
13893 model[attr] = attrs[attr];
13894 }
13895 delete attrs[attr];
13896 }
13897 });
13898 return attrs;
13899 },
13900
13901 /**
13902 * Returns the json to be sent to the server.
13903 * @private
13904 */
13905 _startSave: function _startSave() {
13906 this._opSetQueue.push({});
13907 },
13908
13909 /**
13910 * Called when a save fails because of an error. Any changes that were part
13911 * of the save need to be merged with changes made after the save. This
13912 * might throw an exception is you do conflicting operations. For example,
13913 * if you do:
13914 * object.set("foo", "bar");
13915 * object.set("invalid field name", "baz");
13916 * object.save();
13917 * object.increment("foo");
13918 * then this will throw when the save fails and the client tries to merge
13919 * "bar" with the +1.
13920 * @private
13921 */
13922 _cancelSave: function _cancelSave() {
13923 var failedChanges = _.first(this._opSetQueue);
13924 this._opSetQueue = _.rest(this._opSetQueue);
13925 var nextChanges = _.first(this._opSetQueue);
13926 AV._objectEach(failedChanges, function (op, key) {
13927 var op1 = failedChanges[key];
13928 var op2 = nextChanges[key];
13929 if (op1 && op2) {
13930 nextChanges[key] = op2._mergeWithPrevious(op1);
13931 } else if (op1) {
13932 nextChanges[key] = op1;
13933 }
13934 });
13935 this._saving = this._saving - 1;
13936 },
13937
13938 /**
13939 * Called when a save completes successfully. This merges the changes that
13940 * were saved into the known server data, and overrides it with any data
13941 * sent directly from the server.
13942 * @private
13943 */
13944 _finishSave: function _finishSave(serverData) {
13945 // Grab a copy of any object referenced by this object. These instances
13946 // may have already been fetched, and we don't want to lose their data.
13947 // Note that doing it like this means we will unify separate copies of the
13948 // same object, but that's a risk we have to take.
13949 var fetchedObjects = {};
13950 AV._traverse(this.attributes, function (object) {
13951 if (object instanceof AV.Object && object.id && object._hasData) {
13952 fetchedObjects[object.id] = object;
13953 }
13954 });
13955
13956 var savedChanges = _.first(this._opSetQueue);
13957 this._opSetQueue = _.rest(this._opSetQueue);
13958 this._applyOpSet(savedChanges, this._serverData);
13959 this._mergeMagicFields(serverData);
13960 var self = this;
13961 AV._objectEach(serverData, function (value, key) {
13962 self._serverData[key] = AV._decode(value, key);
13963
13964 // Look for any objects that might have become unfetched and fix them
13965 // by replacing their values with the previously observed values.
13966 var fetched = AV._traverse(self._serverData[key], function (object) {
13967 if (object instanceof AV.Object && fetchedObjects[object.id]) {
13968 return fetchedObjects[object.id];
13969 }
13970 });
13971 if (fetched) {
13972 self._serverData[key] = fetched;
13973 }
13974 });
13975 this._rebuildAllEstimatedData();
13976 var opSetQueue = this._opSetQueue.map(_.clone);
13977 this._refreshCache();
13978 this._opSetQueue = opSetQueue;
13979 this._saving = this._saving - 1;
13980 },
13981
13982 /**
13983 * Called when a fetch or login is complete to set the known server data to
13984 * the given object.
13985 * @private
13986 */
13987 _finishFetch: function _finishFetch(serverData, hasData) {
13988 // Clear out any changes the user might have made previously.
13989 this._opSetQueue = [{}];
13990
13991 // Bring in all the new server data.
13992 this._mergeMagicFields(serverData);
13993 var self = this;
13994 AV._objectEach(serverData, function (value, key) {
13995 self._serverData[key] = AV._decode(value, key);
13996 });
13997
13998 // Refresh the attributes.
13999 this._rebuildAllEstimatedData();
14000
14001 // Clear out the cache of mutable containers.
14002 this._refreshCache();
14003 this._opSetQueue = [{}];
14004
14005 this._hasData = hasData;
14006 },
14007
14008 /**
14009 * Applies the set of AV.Op in opSet to the object target.
14010 * @private
14011 */
14012 _applyOpSet: function _applyOpSet(opSet, target) {
14013 var self = this;
14014 AV._objectEach(opSet, function (change, key) {
14015 var _findValue = findValue(target, key),
14016 _findValue2 = (0, _slicedToArray3.default)(_findValue, 3),
14017 value = _findValue2[0],
14018 actualTarget = _findValue2[1],
14019 actualKey = _findValue2[2];
14020
14021 setValue(target, key, change._estimate(value, self, key));
14022 if (actualTarget && actualTarget[actualKey] === AV.Op._UNSET) {
14023 delete actualTarget[actualKey];
14024 }
14025 });
14026 },
14027
14028 /**
14029 * Replaces the cached value for key with the current value.
14030 * Returns true if the new value is different than the old value.
14031 * @private
14032 */
14033 _resetCacheForKey: function _resetCacheForKey(key) {
14034 var value = this.attributes[key];
14035 if (_.isObject(value) && !(value instanceof AV.Object) && !(value instanceof AV.File)) {
14036 var json = (0, _stringify2.default)(recursiveToPointer(value));
14037 if (this._hashedJSON[key] !== json) {
14038 var wasSet = !!this._hashedJSON[key];
14039 this._hashedJSON[key] = json;
14040 return wasSet;
14041 }
14042 }
14043 return false;
14044 },
14045
14046 /**
14047 * Populates attributes[key] by starting with the last known data from the
14048 * server, and applying all of the local changes that have been made to that
14049 * key since then.
14050 * @private
14051 */
14052 _rebuildEstimatedDataForKey: function _rebuildEstimatedDataForKey(key) {
14053 var self = this;
14054 delete this.attributes[key];
14055 if (this._serverData[key]) {
14056 this.attributes[key] = this._serverData[key];
14057 }
14058 AV._arrayEach(this._opSetQueue, function (opSet) {
14059 var op = opSet[key];
14060 if (op) {
14061 var _findValue3 = findValue(self.attributes, key),
14062 _findValue4 = (0, _slicedToArray3.default)(_findValue3, 4),
14063 value = _findValue4[0],
14064 actualTarget = _findValue4[1],
14065 actualKey = _findValue4[2],
14066 firstKey = _findValue4[3];
14067
14068 setValue(self.attributes, key, op._estimate(value, self, key));
14069 if (actualTarget && actualTarget[actualKey] === AV.Op._UNSET) {
14070 delete actualTarget[actualKey];
14071 }
14072 self._resetCacheForKey(firstKey);
14073 }
14074 });
14075 },
14076
14077 /**
14078 * Populates attributes by starting with the last known data from the
14079 * server, and applying all of the local changes that have been made since
14080 * then.
14081 * @private
14082 */
14083 _rebuildAllEstimatedData: function _rebuildAllEstimatedData() {
14084 var self = this;
14085
14086 var previousAttributes = _.clone(this.attributes);
14087
14088 this.attributes = _.clone(this._serverData);
14089 AV._arrayEach(this._opSetQueue, function (opSet) {
14090 self._applyOpSet(opSet, self.attributes);
14091 AV._objectEach(opSet, function (op, key) {
14092 self._resetCacheForKey(key);
14093 });
14094 });
14095
14096 // Trigger change events for anything that changed because of the fetch.
14097 AV._objectEach(previousAttributes, function (oldValue, key) {
14098 if (self.attributes[key] !== oldValue) {
14099 self.trigger('change:' + key, self, self.attributes[key], {});
14100 }
14101 });
14102 AV._objectEach(this.attributes, function (newValue, key) {
14103 if (!_.has(previousAttributes, key)) {
14104 self.trigger('change:' + key, self, newValue, {});
14105 }
14106 });
14107 },
14108
14109 /**
14110 * Sets a hash of model attributes on the object, firing
14111 * <code>"change"</code> unless you choose to silence it.
14112 *
14113 * <p>You can call it with an object containing keys and values, or with one
14114 * key and value. For example:</p>
14115 *
14116 * @example
14117 * gameTurn.set({
14118 * player: player1,
14119 * diceRoll: 2
14120 * });
14121 *
14122 * game.set("currentPlayer", player2);
14123 *
14124 * game.set("finished", true);
14125 *
14126 * @param {String} key The key to set.
14127 * @param {Any} value The value to give it.
14128 * @param {Object} [options]
14129 * @param {Boolean} [options.silent]
14130 * @return {AV.Object} self if succeeded, throws if the value is not valid.
14131 * @see AV.Object#validate
14132 */
14133 set: function set(key, value, options) {
14134 var attrs;
14135 if (_.isObject(key) || isNullOrUndefined(key)) {
14136 attrs = _.mapObject(key, function (v, k) {
14137 checkReservedKey(k);
14138 return AV._decode(v, k);
14139 });
14140 options = value;
14141 } else {
14142 attrs = {};
14143 checkReservedKey(key);
14144 attrs[key] = AV._decode(value, key);
14145 }
14146
14147 // Extract attributes and options.
14148 options = options || {};
14149 if (!attrs) {
14150 return this;
14151 }
14152 if (attrs instanceof AV.Object) {
14153 attrs = attrs.attributes;
14154 }
14155
14156 // If the unset option is used, every attribute should be a Unset.
14157 if (options.unset) {
14158 AV._objectEach(attrs, function (unused_value, key) {
14159 attrs[key] = new AV.Op.Unset();
14160 });
14161 }
14162
14163 // Apply all the attributes to get the estimated values.
14164 var dataToValidate = _.clone(attrs);
14165 var self = this;
14166 AV._objectEach(dataToValidate, function (value, key) {
14167 if (value instanceof AV.Op) {
14168 dataToValidate[key] = value._estimate(self.attributes[key], self, key);
14169 if (dataToValidate[key] === AV.Op._UNSET) {
14170 delete dataToValidate[key];
14171 }
14172 }
14173 });
14174
14175 // Run validation.
14176 this._validate(attrs, options);
14177
14178 options.changes = {};
14179 var escaped = this._escapedAttributes;
14180
14181 // Update attributes.
14182 AV._arrayEach(_.keys(attrs), function (attr) {
14183 var val = attrs[attr];
14184
14185 // If this is a relation object we need to set the parent correctly,
14186 // since the location where it was parsed does not have access to
14187 // this object.
14188 if (val instanceof AV.Relation) {
14189 val.parent = self;
14190 }
14191
14192 if (!(val instanceof AV.Op)) {
14193 val = new AV.Op.Set(val);
14194 }
14195
14196 // See if this change will actually have any effect.
14197 var isRealChange = true;
14198 if (val instanceof AV.Op.Set && _.isEqual(self.attributes[attr], val.value)) {
14199 isRealChange = false;
14200 }
14201
14202 if (isRealChange) {
14203 delete escaped[attr];
14204 if (options.silent) {
14205 self._silent[attr] = true;
14206 } else {
14207 options.changes[attr] = true;
14208 }
14209 }
14210
14211 var currentChanges = _.last(self._opSetQueue);
14212 currentChanges[attr] = val._mergeWithPrevious(currentChanges[attr]);
14213 self._rebuildEstimatedDataForKey(attr);
14214
14215 if (isRealChange) {
14216 self.changed[attr] = self.attributes[attr];
14217 if (!options.silent) {
14218 self._pending[attr] = true;
14219 }
14220 } else {
14221 delete self.changed[attr];
14222 delete self._pending[attr];
14223 }
14224 });
14225
14226 if (!options.silent) {
14227 this.change(options);
14228 }
14229 return this;
14230 },
14231
14232 /**
14233 * Remove an attribute from the model, firing <code>"change"</code> unless
14234 * you choose to silence it. This is a noop if the attribute doesn't
14235 * exist.
14236 * @param key {String} The key.
14237 */
14238 unset: function unset(attr, options) {
14239 options = options || {};
14240 options.unset = true;
14241 return this.set(attr, null, options);
14242 },
14243
14244 /**
14245 * Atomically increments the value of the given attribute the next time the
14246 * object is saved. If no amount is specified, 1 is used by default.
14247 *
14248 * @param key {String} The key.
14249 * @param amount {Number} The amount to increment by.
14250 */
14251 increment: function increment(attr, amount) {
14252 if (_.isUndefined(amount) || _.isNull(amount)) {
14253 amount = 1;
14254 }
14255 return this.set(attr, new AV.Op.Increment(amount));
14256 },
14257
14258 /**
14259 * Atomically add an object to the end of the array associated with a given
14260 * key.
14261 * @param key {String} The key.
14262 * @param item {} The item to add.
14263 */
14264 add: function add(attr, item) {
14265 return this.set(attr, new AV.Op.Add(ensureArray(item)));
14266 },
14267
14268 /**
14269 * Atomically add an object to the array associated with a given key, only
14270 * if it is not already present in the array. The position of the insert is
14271 * not guaranteed.
14272 *
14273 * @param key {String} The key.
14274 * @param item {} The object to add.
14275 */
14276 addUnique: function addUnique(attr, item) {
14277 return this.set(attr, new AV.Op.AddUnique(ensureArray(item)));
14278 },
14279
14280 /**
14281 * Atomically remove all instances of an object from the array associated
14282 * with a given key.
14283 *
14284 * @param key {String} The key.
14285 * @param item {} The object to remove.
14286 */
14287 remove: function remove(attr, item) {
14288 return this.set(attr, new AV.Op.Remove(ensureArray(item)));
14289 },
14290
14291 /**
14292 * Atomically apply a "bit and" operation on the value associated with a
14293 * given key.
14294 *
14295 * @param key {String} The key.
14296 * @param value {Number} The value to apply.
14297 */
14298 bitAnd: function bitAnd(attr, value) {
14299 return this.set(attr, new AV.Op.BitAnd(value));
14300 },
14301
14302
14303 /**
14304 * Atomically apply a "bit or" operation on the value associated with a
14305 * given key.
14306 *
14307 * @param key {String} The key.
14308 * @param value {Number} The value to apply.
14309 */
14310 bitOr: function bitOr(attr, value) {
14311 return this.set(attr, new AV.Op.BitOr(value));
14312 },
14313
14314
14315 /**
14316 * Atomically apply a "bit xor" operation on the value associated with a
14317 * given key.
14318 *
14319 * @param key {String} The key.
14320 * @param value {Number} The value to apply.
14321 */
14322 bitXor: function bitXor(attr, value) {
14323 return this.set(attr, new AV.Op.BitXor(value));
14324 },
14325
14326
14327 /**
14328 * Returns an instance of a subclass of AV.Op describing what kind of
14329 * modification has been performed on this field since the last time it was
14330 * saved. For example, after calling object.increment("x"), calling
14331 * object.op("x") would return an instance of AV.Op.Increment.
14332 *
14333 * @param key {String} The key.
14334 * @returns {AV.Op} The operation, or undefined if none.
14335 */
14336 op: function op(attr) {
14337 return _.last(this._opSetQueue)[attr];
14338 },
14339
14340 /**
14341 * Clear all attributes on the model, firing <code>"change"</code> unless
14342 * you choose to silence it.
14343 */
14344 clear: function clear(options) {
14345 options = options || {};
14346 options.unset = true;
14347 var keysToClear = _.extend(this.attributes, this._operations);
14348 return this.set(keysToClear, options);
14349 },
14350
14351 /**
14352 * Clears any (or specific) changes to the model made since the last save.
14353 * @param {string|string[]} [keys] specify keys to revert.
14354 */
14355 revert: function revert(keys) {
14356 var lastOp = _.last(this._opSetQueue);
14357 var _keys = ensureArray(keys || _.keys(lastOp));
14358 _keys.forEach(function (key) {
14359 delete lastOp[key];
14360 });
14361 this._rebuildAllEstimatedData();
14362 return this;
14363 },
14364
14365
14366 /**
14367 * Returns a JSON-encoded set of operations to be sent with the next save
14368 * request.
14369 * @private
14370 */
14371 _getSaveJSON: function _getSaveJSON() {
14372 var json = _.clone(_.first(this._opSetQueue));
14373 AV._objectEach(json, function (op, key) {
14374 json[key] = op.toJSON();
14375 });
14376 return json;
14377 },
14378
14379 /**
14380 * Returns true if this object can be serialized for saving.
14381 * @private
14382 */
14383 _canBeSerialized: function _canBeSerialized() {
14384 return AV.Object._canBeSerializedAsValue(this.attributes);
14385 },
14386
14387 /**
14388 * Fetch the model from the server. If the server's representation of the
14389 * model differs from its current attributes, they will be overriden,
14390 * triggering a <code>"change"</code> event.
14391 * @param {Object} fetchOptions Optional options to set 'keys',
14392 * 'include' and 'includeACL' option.
14393 * @param {AuthOptions} options
14394 * @return {Promise} A promise that is fulfilled when the fetch
14395 * completes.
14396 */
14397 fetch: function fetch() {
14398 var fetchOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
14399 var options = arguments[1];
14400
14401 if (!this.id) {
14402 throw new Error('Cannot fetch unsaved object');
14403 }
14404 var self = this;
14405 var request = _request('classes', this.className, this.id, 'GET', transformFetchOptions(fetchOptions), options);
14406 return request.then(function (response) {
14407 var fetchedAttrs = self.parse(response);
14408 self._cleanupUnsetKeys(fetchedAttrs, fetchOptions.keys ? ensureArray(fetchOptions.keys).join(',').split(',') : undefined);
14409 self._finishFetch(fetchedAttrs, true);
14410 return self;
14411 });
14412 },
14413
14414 _cleanupUnsetKeys: function _cleanupUnsetKeys(fetchedAttrs) {
14415 var _this2 = this;
14416
14417 var fetchedKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _.keys(this._serverData);
14418
14419 _.forEach(fetchedKeys, function (key) {
14420 if (fetchedAttrs[key] === undefined) delete _this2._serverData[key];
14421 });
14422 },
14423
14424
14425 /**
14426 * Set a hash of model attributes, and save the model to the server.
14427 * updatedAt will be updated when the request returns.
14428 * You can either call it as:<pre>
14429 * object.save();</pre>
14430 * or<pre>
14431 * object.save(null, options);</pre>
14432 * or<pre>
14433 * object.save(attrs, options);</pre>
14434 * or<pre>
14435 * object.save(key, value, options);</pre>
14436 *
14437 * @example
14438 * gameTurn.save({
14439 * player: "Jake Cutter",
14440 * diceRoll: 2
14441 * }).then(function(gameTurnAgain) {
14442 * // The save was successful.
14443 * }, function(error) {
14444 * // The save failed. Error is an instance of AVError.
14445 * });
14446 *
14447 * @param {AuthOptions} options AuthOptions plus:
14448 * @param {Boolean} options.fetchWhenSave fetch and update object after save succeeded
14449 * @param {AV.Query} options.query Save object only when it matches the query
14450 * @return {Promise} A promise that is fulfilled when the save
14451 * completes.
14452 * @see AVError
14453 */
14454 save: function save(arg1, arg2, arg3) {
14455 var attrs, current, options;
14456 if (_.isObject(arg1) || isNullOrUndefined(arg1)) {
14457 attrs = arg1;
14458 options = arg2;
14459 } else {
14460 attrs = {};
14461 attrs[arg1] = arg2;
14462 options = arg3;
14463 }
14464
14465 options = _.clone(options) || {};
14466 if (options.wait) {
14467 current = _.clone(this.attributes);
14468 }
14469
14470 var setOptions = _.clone(options) || {};
14471 if (setOptions.wait) {
14472 setOptions.silent = true;
14473 }
14474 if (attrs) {
14475 this.set(attrs, setOptions);
14476 }
14477
14478 var model = this;
14479
14480 var unsavedChildren = [];
14481 var unsavedFiles = [];
14482 AV.Object._findUnsavedChildren(model, unsavedChildren, unsavedFiles);
14483 if (unsavedChildren.length + unsavedFiles.length > 1) {
14484 return AV.Object._deepSaveAsync(this, model, options);
14485 }
14486
14487 this._startSave();
14488 this._saving = (this._saving || 0) + 1;
14489
14490 this._allPreviousSaves = this._allPreviousSaves || _promise2.default.resolve();
14491 this._allPreviousSaves = this._allPreviousSaves.catch(function (e) {}).then(function () {
14492 var method = model.id ? 'PUT' : 'POST';
14493
14494 var json = model._getSaveJSON();
14495 var query = {};
14496
14497 if (model._fetchWhenSave || options.fetchWhenSave) {
14498 query['new'] = 'true';
14499 }
14500 // user login option
14501 if (options._failOnNotExist) {
14502 query.failOnNotExist = 'true';
14503 }
14504
14505 if (options.query) {
14506 var queryParams;
14507 if (typeof options.query._getParams === 'function') {
14508 queryParams = options.query._getParams();
14509 if (queryParams) {
14510 query.where = queryParams.where;
14511 }
14512 }
14513 if (!query.where) {
14514 var error = new Error('options.query is not an AV.Query');
14515 throw error;
14516 }
14517 }
14518
14519 _.extend(json, model._flags);
14520
14521 var route = 'classes';
14522 var className = model.className;
14523 if (model.className === '_User' && !model.id) {
14524 // Special-case user sign-up.
14525 route = 'users';
14526 className = null;
14527 }
14528 //hook makeRequest in options.
14529 var makeRequest = options._makeRequest || _request;
14530 var requestPromise = makeRequest(route, className, model.id, method, json, options, query);
14531
14532 requestPromise = requestPromise.then(function (resp) {
14533 var serverAttrs = model.parse(resp);
14534 if (options.wait) {
14535 serverAttrs = _.extend(attrs || {}, serverAttrs);
14536 }
14537 model._finishSave(serverAttrs);
14538 if (options.wait) {
14539 model.set(current, setOptions);
14540 }
14541 return model;
14542 }, function (error) {
14543 model._cancelSave();
14544 throw error;
14545 });
14546
14547 return requestPromise;
14548 });
14549 return this._allPreviousSaves;
14550 },
14551
14552 /**
14553 * Destroy this model on the server if it was already persisted.
14554 * Optimistically removes the model from its collection, if it has one.
14555 * @param {AuthOptions} options AuthOptions plus:
14556 * @param {Boolean} [options.wait] wait for the server to respond
14557 * before removal.
14558 *
14559 * @return {Promise} A promise that is fulfilled when the destroy
14560 * completes.
14561 */
14562 destroy: function destroy(options) {
14563 options = options || {};
14564 var model = this;
14565
14566 var triggerDestroy = function triggerDestroy() {
14567 model.trigger('destroy', model, model.collection, options);
14568 };
14569
14570 if (!this.id) {
14571 return triggerDestroy();
14572 }
14573
14574 if (!options.wait) {
14575 triggerDestroy();
14576 }
14577
14578 var request = _request('classes', this.className, this.id, 'DELETE', this._flags, options);
14579 return request.then(function () {
14580 if (options.wait) {
14581 triggerDestroy();
14582 }
14583 return model;
14584 });
14585 },
14586
14587 /**
14588 * Converts a response into the hash of attributes to be set on the model.
14589 * @ignore
14590 */
14591 parse: function parse(resp) {
14592 var output = _.clone(resp);
14593 ['createdAt', 'updatedAt'].forEach(function (key) {
14594 if (output[key]) {
14595 output[key] = AV._parseDate(output[key]);
14596 }
14597 });
14598 if (output.createdAt && !output.updatedAt) {
14599 output.updatedAt = output.createdAt;
14600 }
14601 return output;
14602 },
14603
14604 /**
14605 * Creates a new model with identical attributes to this one.
14606 * @return {AV.Object}
14607 */
14608 clone: function clone() {
14609 return new this.constructor(this.attributes);
14610 },
14611
14612 /**
14613 * Returns true if this object has never been saved to AV.
14614 * @return {Boolean}
14615 */
14616 isNew: function isNew() {
14617 return !this.id;
14618 },
14619
14620 /**
14621 * Call this method to manually fire a `"change"` event for this model and
14622 * a `"change:attribute"` event for each changed attribute.
14623 * Calling this will cause all objects observing the model to update.
14624 */
14625 change: function change(options) {
14626 options = options || {};
14627 var changing = this._changing;
14628 this._changing = true;
14629
14630 // Silent changes become pending changes.
14631 var self = this;
14632 AV._objectEach(this._silent, function (attr) {
14633 self._pending[attr] = true;
14634 });
14635
14636 // Silent changes are triggered.
14637 var changes = _.extend({}, options.changes, this._silent);
14638 this._silent = {};
14639 AV._objectEach(changes, function (unused_value, attr) {
14640 self.trigger('change:' + attr, self, self.get(attr), options);
14641 });
14642 if (changing) {
14643 return this;
14644 }
14645
14646 // This is to get around lint not letting us make a function in a loop.
14647 var deleteChanged = function deleteChanged(value, attr) {
14648 if (!self._pending[attr] && !self._silent[attr]) {
14649 delete self.changed[attr];
14650 }
14651 };
14652
14653 // Continue firing `"change"` events while there are pending changes.
14654 while (!_.isEmpty(this._pending)) {
14655 this._pending = {};
14656 this.trigger('change', this, options);
14657 // Pending and silent changes still remain.
14658 AV._objectEach(this.changed, deleteChanged);
14659 self._previousAttributes = _.clone(this.attributes);
14660 }
14661
14662 this._changing = false;
14663 return this;
14664 },
14665
14666 /**
14667 * Gets the previous value of an attribute, recorded at the time the last
14668 * <code>"change"</code> event was fired.
14669 * @param {String} attr Name of the attribute to get.
14670 */
14671 previous: function previous(attr) {
14672 if (!arguments.length || !this._previousAttributes) {
14673 return null;
14674 }
14675 return this._previousAttributes[attr];
14676 },
14677
14678 /**
14679 * Gets all of the attributes of the model at the time of the previous
14680 * <code>"change"</code> event.
14681 * @return {Object}
14682 */
14683 previousAttributes: function previousAttributes() {
14684 return _.clone(this._previousAttributes);
14685 },
14686
14687 /**
14688 * Checks if the model is currently in a valid state. It's only possible to
14689 * get into an *invalid* state if you're using silent changes.
14690 * @return {Boolean}
14691 */
14692 isValid: function isValid() {
14693 try {
14694 this.validate(this.attributes);
14695 } catch (error) {
14696 return false;
14697 }
14698 return true;
14699 },
14700
14701 /**
14702 * You should not call this function directly unless you subclass
14703 * <code>AV.Object</code>, in which case you can override this method
14704 * to provide additional validation on <code>set</code> and
14705 * <code>save</code>. Your implementation should throw an Error if
14706 * the attrs is invalid
14707 *
14708 * @param {Object} attrs The current data to validate.
14709 * @see AV.Object#set
14710 */
14711 validate: function validate(attrs) {
14712 if (_.has(attrs, 'ACL') && !(attrs.ACL instanceof AV.ACL)) {
14713 throw new AVError(AVError.OTHER_CAUSE, 'ACL must be a AV.ACL.');
14714 }
14715 },
14716
14717 /**
14718 * Run validation against a set of incoming attributes, returning `true`
14719 * if all is well. If a specific `error` callback has been passed,
14720 * call that instead of firing the general `"error"` event.
14721 * @private
14722 */
14723 _validate: function _validate(attrs, options) {
14724 if (options.silent || !this.validate) {
14725 return;
14726 }
14727 attrs = _.extend({}, this.attributes, attrs);
14728 this.validate(attrs);
14729 },
14730
14731 /**
14732 * Returns the ACL for this object.
14733 * @returns {AV.ACL} An instance of AV.ACL.
14734 * @see AV.Object#get
14735 */
14736 getACL: function getACL() {
14737 return this.get('ACL');
14738 },
14739
14740 /**
14741 * Sets the ACL to be used for this object.
14742 * @param {AV.ACL} acl An instance of AV.ACL.
14743 * @param {Object} options Optional Backbone-like options object to be
14744 * passed in to set.
14745 * @return {AV.Object} self
14746 * @see AV.Object#set
14747 */
14748 setACL: function setACL(acl, options) {
14749 return this.set('ACL', acl, options);
14750 },
14751
14752 disableBeforeHook: function disableBeforeHook() {
14753 this.ignoreHook('beforeSave');
14754 this.ignoreHook('beforeUpdate');
14755 this.ignoreHook('beforeDelete');
14756 },
14757
14758 disableAfterHook: function disableAfterHook() {
14759 this.ignoreHook('afterSave');
14760 this.ignoreHook('afterUpdate');
14761 this.ignoreHook('afterDelete');
14762 },
14763
14764 ignoreHook: function ignoreHook(hookName) {
14765 if (!_.contains(['beforeSave', 'afterSave', 'beforeUpdate', 'afterUpdate', 'beforeDelete', 'afterDelete'], hookName)) {
14766 throw new Error('Unsupported hookName: ' + hookName);
14767 }
14768
14769 if (!AV.hookKey) {
14770 throw new Error('ignoreHook required hookKey');
14771 }
14772
14773 if (!this._flags.__ignore_hooks) {
14774 this._flags.__ignore_hooks = [];
14775 }
14776
14777 this._flags.__ignore_hooks.push(hookName);
14778 }
14779 });
14780
14781 /**
14782 * Creates an instance of a subclass of AV.Object for the give classname
14783 * and id.
14784 * @param {String|Function} class the className or a subclass of AV.Object.
14785 * @param {String} id The object id of this model.
14786 * @return {AV.Object} A new subclass instance of AV.Object.
14787 */
14788 AV.Object.createWithoutData = function (klass, id, hasData) {
14789 var _klass = void 0;
14790 if (_.isString(klass)) {
14791 _klass = AV.Object._getSubclass(klass);
14792 } else if (klass.prototype && klass.prototype instanceof AV.Object) {
14793 _klass = klass;
14794 } else {
14795 throw new Error('class must be a string or a subclass of AV.Object.');
14796 }
14797 if (!id) {
14798 throw new TypeError('The objectId must be provided');
14799 }
14800 var object = new _klass();
14801 object.id = id;
14802 object._hasData = hasData;
14803 return object;
14804 };
14805 /**
14806 * Delete objects in batch.
14807 * @param {AV.Object[]} objects The <code>AV.Object</code> array to be deleted.
14808 * @param {AuthOptions} options
14809 * @return {Promise} A promise that is fulfilled when the save
14810 * completes.
14811 */
14812 AV.Object.destroyAll = function (objects) {
14813 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
14814
14815 if (!objects || objects.length === 0) {
14816 return _promise2.default.resolve();
14817 }
14818 var objectsByClassNameAndFlags = _.groupBy(objects, function (object) {
14819 return (0, _stringify2.default)({
14820 className: object.className,
14821 flags: object._flags
14822 });
14823 });
14824 var body = {
14825 requests: _.map(objectsByClassNameAndFlags, function (objects) {
14826 var ids = _.map(objects, 'id').join(',');
14827 return {
14828 method: 'DELETE',
14829 path: '/1.1/classes/' + objects[0].className + '/' + ids,
14830 body: objects[0]._flags
14831 };
14832 })
14833 };
14834 return _request('batch', null, null, 'POST', body, options).then(function (response) {
14835 var firstError = _.find(response, function (result) {
14836 return !result.success;
14837 });
14838 if (firstError) throw new AVError(firstError.error.code, firstError.error.error);
14839 return undefined;
14840 });
14841 };
14842
14843 /**
14844 * Returns the appropriate subclass for making new instances of the given
14845 * className string.
14846 * @private
14847 */
14848 AV.Object._getSubclass = function (className) {
14849 if (!_.isString(className)) {
14850 throw new Error('AV.Object._getSubclass requires a string argument.');
14851 }
14852 var ObjectClass = AV.Object._classMap[className];
14853 if (!ObjectClass) {
14854 ObjectClass = AV.Object.extend(className);
14855 AV.Object._classMap[className] = ObjectClass;
14856 }
14857 return ObjectClass;
14858 };
14859
14860 /**
14861 * Creates an instance of a subclass of AV.Object for the given classname.
14862 * @private
14863 */
14864 AV.Object._create = function (className, attributes, options) {
14865 var ObjectClass = AV.Object._getSubclass(className);
14866 return new ObjectClass(attributes, options);
14867 };
14868
14869 // Set up a map of className to class so that we can create new instances of
14870 // AV Objects from JSON automatically.
14871 AV.Object._classMap = {};
14872
14873 AV.Object._extend = AV._extend;
14874
14875 /**
14876 * Creates a new model with defined attributes,
14877 * It's the same with
14878 * <pre>
14879 * new AV.Object(attributes, options);
14880 * </pre>
14881 * @param {Object} attributes The initial set of data to store in the object.
14882 * @param {Object} options A set of Backbone-like options for creating the
14883 * object. The only option currently supported is "collection".
14884 * @return {AV.Object}
14885 * @since v0.4.4
14886 * @see AV.Object
14887 * @see AV.Object.extend
14888 */
14889 AV.Object['new'] = function (attributes, options) {
14890 return new AV.Object(attributes, options);
14891 };
14892
14893 /**
14894 * Creates a new subclass of AV.Object for the given AV class name.
14895 *
14896 * <p>Every extension of a AV class will inherit from the most recent
14897 * previous extension of that class. When a AV.Object is automatically
14898 * created by parsing JSON, it will use the most recent extension of that
14899 * class.</p>
14900 *
14901 * @example
14902 * var MyClass = AV.Object.extend("MyClass", {
14903 * // Instance properties
14904 * }, {
14905 * // Class properties
14906 * });
14907 *
14908 * @param {String} className The name of the AV class backing this model.
14909 * @param {Object} protoProps Instance properties to add to instances of the
14910 * class returned from this method.
14911 * @param {Object} classProps Class properties to add the class returned from
14912 * this method.
14913 * @return {Class} A new subclass of AV.Object.
14914 */
14915 AV.Object.extend = function (className, protoProps, classProps) {
14916 // Handle the case with only two args.
14917 if (!_.isString(className)) {
14918 if (className && _.has(className, 'className')) {
14919 return AV.Object.extend(className.className, className, protoProps);
14920 } else {
14921 throw new Error("AV.Object.extend's first argument should be the className.");
14922 }
14923 }
14924
14925 // If someone tries to subclass "User", coerce it to the right type.
14926 if (className === 'User') {
14927 className = '_User';
14928 }
14929
14930 var NewClassObject = null;
14931 if (_.has(AV.Object._classMap, className)) {
14932 var OldClassObject = AV.Object._classMap[className];
14933 // This new subclass has been told to extend both from "this" and from
14934 // OldClassObject. This is multiple inheritance, which isn't supported.
14935 // For now, let's just pick one.
14936 if (protoProps || classProps) {
14937 NewClassObject = OldClassObject._extend(protoProps, classProps);
14938 } else {
14939 return OldClassObject;
14940 }
14941 } else {
14942 protoProps = protoProps || {};
14943 protoProps._className = className;
14944 NewClassObject = this._extend(protoProps, classProps);
14945 }
14946 // Extending a subclass should reuse the classname automatically.
14947 NewClassObject.extend = function (arg0) {
14948 if (_.isString(arg0) || arg0 && _.has(arg0, 'className')) {
14949 return AV.Object.extend.apply(NewClassObject, arguments);
14950 }
14951 var newArguments = [className].concat(_.toArray(arguments));
14952 return AV.Object.extend.apply(NewClassObject, newArguments);
14953 };
14954 // Add the query property descriptor.
14955 Object.defineProperty(NewClassObject, 'query', (0, _getOwnPropertyDescriptor2.default)(AV.Object, 'query'));
14956 NewClassObject['new'] = function (attributes, options) {
14957 return new NewClassObject(attributes, options);
14958 };
14959 AV.Object._classMap[className] = NewClassObject;
14960 return NewClassObject;
14961 };
14962
14963 // ES6 class syntax support
14964 Object.defineProperty(AV.Object.prototype, 'className', {
14965 get: function get() {
14966 var className = this._className || this.constructor._LCClassName || this.constructor.name;
14967 // If someone tries to subclass "User", coerce it to the right type.
14968 if (className === 'User') {
14969 return '_User';
14970 }
14971 return className;
14972 }
14973 });
14974
14975 /**
14976 * Register a class.
14977 * If a subclass of <code>AV.Object</code> is defined with your own implement
14978 * rather then <code>AV.Object.extend</code>, the subclass must be registered.
14979 * @param {Function} klass A subclass of <code>AV.Object</code>
14980 * @param {String} [name] Specify the name of the class. Useful when the class might be uglified.
14981 * @example
14982 * class Person extend AV.Object {}
14983 * AV.Object.register(Person);
14984 */
14985 AV.Object.register = function (klass, name) {
14986 if (!(klass.prototype instanceof AV.Object)) {
14987 throw new Error('registered class is not a subclass of AV.Object');
14988 }
14989 var className = name || klass.name;
14990 if (!className.length) {
14991 throw new Error('registered class must be named');
14992 }
14993 if (name) {
14994 klass._LCClassName = name;
14995 }
14996 AV.Object._classMap[className] = klass;
14997 };
14998
14999 /**
15000 * Get a new Query of the current class
15001 * @name query
15002 * @memberof AV.Object
15003 * @type AV.Query
15004 * @readonly
15005 * @since v3.1.0
15006 * @example
15007 * const Post = AV.Object.extend('Post');
15008 * Post.query.equalTo('author', 'leancloud').find().then();
15009 */
15010 Object.defineProperty(AV.Object, 'query', {
15011 get: function get() {
15012 return new AV.Query(this.prototype.className);
15013 }
15014 });
15015
15016 AV.Object._findUnsavedChildren = function (objects, children, files) {
15017 AV._traverse(objects, function (object) {
15018 if (object instanceof AV.Object) {
15019 if (object.dirty()) {
15020 children.push(object);
15021 }
15022 return;
15023 }
15024
15025 if (object instanceof AV.File) {
15026 if (!object.id) {
15027 files.push(object);
15028 }
15029 return;
15030 }
15031 });
15032 };
15033
15034 AV.Object._canBeSerializedAsValue = function (object) {
15035 var canBeSerializedAsValue = true;
15036
15037 if (object instanceof AV.Object || object instanceof AV.File) {
15038 canBeSerializedAsValue = !!object.id;
15039 } else if (_.isArray(object)) {
15040 AV._arrayEach(object, function (child) {
15041 if (!AV.Object._canBeSerializedAsValue(child)) {
15042 canBeSerializedAsValue = false;
15043 }
15044 });
15045 } else if (_.isObject(object)) {
15046 AV._objectEach(object, function (child) {
15047 if (!AV.Object._canBeSerializedAsValue(child)) {
15048 canBeSerializedAsValue = false;
15049 }
15050 });
15051 }
15052
15053 return canBeSerializedAsValue;
15054 };
15055
15056 AV.Object._deepSaveAsync = function (object, model, options) {
15057 var unsavedChildren = [];
15058 var unsavedFiles = [];
15059 AV.Object._findUnsavedChildren(object, unsavedChildren, unsavedFiles);
15060
15061 unsavedFiles = _.uniq(unsavedFiles);
15062
15063 var promise = _promise2.default.resolve();
15064 _.each(unsavedFiles, function (file) {
15065 promise = promise.then(function () {
15066 return file.save();
15067 });
15068 });
15069
15070 var objects = _.uniq(unsavedChildren);
15071 var remaining = _.uniq(objects);
15072
15073 return promise.then(function () {
15074 return continueWhile(function () {
15075 return remaining.length > 0;
15076 }, function () {
15077 // Gather up all the objects that can be saved in this batch.
15078 var batch = [];
15079 var newRemaining = [];
15080 AV._arrayEach(remaining, function (object) {
15081 if (object._canBeSerialized()) {
15082 batch.push(object);
15083 } else {
15084 newRemaining.push(object);
15085 }
15086 });
15087 remaining = newRemaining;
15088
15089 // If we can't save any objects, there must be a circular reference.
15090 if (batch.length === 0) {
15091 return _promise2.default.reject(new AVError(AVError.OTHER_CAUSE, 'Tried to save a batch with a cycle.'));
15092 }
15093
15094 // Reserve a spot in every object's save queue.
15095 var readyToStart = _promise2.default.resolve(_.map(batch, function (object) {
15096 return object._allPreviousSaves || _promise2.default.resolve();
15097 }));
15098
15099 // Save a single batch, whether previous saves succeeded or failed.
15100 var bathSavePromise = readyToStart.then(function () {
15101 return _request('batch', null, null, 'POST', {
15102 requests: _.map(batch, function (object) {
15103 var method = object.id ? 'PUT' : 'POST';
15104
15105 var json = object._getSaveJSON();
15106
15107 _.extend(json, object._flags);
15108
15109 var route = 'classes';
15110 var className = object.className;
15111 var path = '/' + route + '/' + className;
15112 if (object.className === '_User' && !object.id) {
15113 // Special-case user sign-up.
15114 path = '/users';
15115 }
15116
15117 var path = '/1.1' + path;
15118 if (object.id) {
15119 path = path + '/' + object.id;
15120 }
15121
15122 object._startSave();
15123
15124 return {
15125 method: method,
15126 path: path,
15127 body: json,
15128 params: options && options.fetchWhenSave ? { fetchWhenSave: true } : undefined
15129 };
15130 })
15131 }, options).then(function (response) {
15132 var results = _.map(batch, function (object, i) {
15133 if (response[i].success) {
15134 object._finishSave(object.parse(response[i].success));
15135 return object;
15136 }
15137 object._cancelSave();
15138 return new AVError(response[i].error.code, response[i].error.error);
15139 });
15140 return handleBatchResults(results);
15141 });
15142 });
15143 AV._arrayEach(batch, function (object) {
15144 object._allPreviousSaves = bathSavePromise;
15145 });
15146 return bathSavePromise;
15147 });
15148 }).then(function () {
15149 return object;
15150 });
15151 };
15152};
15153
15154/***/ }),
15155/* 347 */
15156/***/ (function(module, exports, __webpack_require__) {
15157
15158__webpack_require__(348);
15159var $Object = __webpack_require__(1).Object;
15160module.exports = function getOwnPropertyDescriptor(it, key) {
15161 return $Object.getOwnPropertyDescriptor(it, key);
15162};
15163
15164
15165/***/ }),
15166/* 348 */
15167/***/ (function(module, exports, __webpack_require__) {
15168
15169// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
15170var toIObject = __webpack_require__(26);
15171var $getOwnPropertyDescriptor = __webpack_require__(76).f;
15172
15173__webpack_require__(70)('getOwnPropertyDescriptor', function () {
15174 return function getOwnPropertyDescriptor(it, key) {
15175 return $getOwnPropertyDescriptor(toIObject(it), key);
15176 };
15177});
15178
15179
15180/***/ }),
15181/* 349 */
15182/***/ (function(module, exports, __webpack_require__) {
15183
15184"use strict";
15185
15186
15187exports.__esModule = true;
15188
15189var _isIterable2 = __webpack_require__(112);
15190
15191var _isIterable3 = _interopRequireDefault(_isIterable2);
15192
15193var _getIterator2 = __webpack_require__(186);
15194
15195var _getIterator3 = _interopRequireDefault(_getIterator2);
15196
15197function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15198
15199exports.default = function () {
15200 function sliceIterator(arr, i) {
15201 var _arr = [];
15202 var _n = true;
15203 var _d = false;
15204 var _e = undefined;
15205
15206 try {
15207 for (var _i = (0, _getIterator3.default)(arr), _s; !(_n = (_s = _i.next()).done); _n = true) {
15208 _arr.push(_s.value);
15209
15210 if (i && _arr.length === i) break;
15211 }
15212 } catch (err) {
15213 _d = true;
15214 _e = err;
15215 } finally {
15216 try {
15217 if (!_n && _i["return"]) _i["return"]();
15218 } finally {
15219 if (_d) throw _e;
15220 }
15221 }
15222
15223 return _arr;
15224 }
15225
15226 return function (arr, i) {
15227 if (Array.isArray(arr)) {
15228 return arr;
15229 } else if ((0, _isIterable3.default)(Object(arr))) {
15230 return sliceIterator(arr, i);
15231 } else {
15232 throw new TypeError("Invalid attempt to destructure non-iterable instance");
15233 }
15234 };
15235}();
15236
15237/***/ }),
15238/* 350 */
15239/***/ (function(module, exports, __webpack_require__) {
15240
15241__webpack_require__(37);
15242__webpack_require__(35);
15243module.exports = __webpack_require__(351);
15244
15245
15246/***/ }),
15247/* 351 */
15248/***/ (function(module, exports, __webpack_require__) {
15249
15250var classof = __webpack_require__(63);
15251var ITERATOR = __webpack_require__(8)('iterator');
15252var Iterators = __webpack_require__(36);
15253module.exports = __webpack_require__(1).isIterable = function (it) {
15254 var O = Object(it);
15255 return O[ITERATOR] !== undefined
15256 || '@@iterator' in O
15257 // eslint-disable-next-line no-prototype-builtins
15258 || Iterators.hasOwnProperty(classof(O));
15259};
15260
15261
15262/***/ }),
15263/* 352 */
15264/***/ (function(module, exports, __webpack_require__) {
15265
15266"use strict";
15267
15268
15269var _ = __webpack_require__(0);
15270var AVError = __webpack_require__(34);
15271
15272module.exports = function (AV) {
15273 AV.Role = AV.Object.extend('_Role',
15274 /** @lends AV.Role.prototype */{
15275 // Instance Methods
15276
15277 /**
15278 * Represents a Role on the AV server. Roles represent groupings of
15279 * Users for the purposes of granting permissions (e.g. specifying an ACL
15280 * for an Object). Roles are specified by their sets of child users and
15281 * child roles, all of which are granted any permissions that the parent
15282 * role has.
15283 *
15284 * <p>Roles must have a name (which cannot be changed after creation of the
15285 * role), and must specify an ACL.</p>
15286 * An AV.Role is a local representation of a role persisted to the AV
15287 * cloud.
15288 * @class AV.Role
15289 * @param {String} name The name of the Role to create.
15290 * @param {AV.ACL} acl The ACL for this role.
15291 */
15292 constructor: function constructor(name, acl) {
15293 if (_.isString(name)) {
15294 AV.Object.prototype.constructor.call(this, null, null);
15295 this.setName(name);
15296 } else {
15297 AV.Object.prototype.constructor.call(this, name, acl);
15298 }
15299 if (acl) {
15300 if (!(acl instanceof AV.ACL)) {
15301 throw new TypeError('acl must be an instance of AV.ACL');
15302 } else {
15303 this.setACL(acl);
15304 }
15305 }
15306 },
15307
15308 /**
15309 * Gets the name of the role. You can alternatively call role.get("name")
15310 *
15311 * @return {String} the name of the role.
15312 */
15313 getName: function getName() {
15314 return this.get('name');
15315 },
15316
15317 /**
15318 * Sets the name for a role. This value must be set before the role has
15319 * been saved to the server, and cannot be set once the role has been
15320 * saved.
15321 *
15322 * <p>
15323 * A role's name can only contain alphanumeric characters, _, -, and
15324 * spaces.
15325 * </p>
15326 *
15327 * <p>This is equivalent to calling role.set("name", name)</p>
15328 *
15329 * @param {String} name The name of the role.
15330 */
15331 setName: function setName(name, options) {
15332 return this.set('name', name, options);
15333 },
15334
15335 /**
15336 * Gets the AV.Relation for the AV.Users that are direct
15337 * children of this role. These users are granted any privileges that this
15338 * role has been granted (e.g. read or write access through ACLs). You can
15339 * add or remove users from the role through this relation.
15340 *
15341 * <p>This is equivalent to calling role.relation("users")</p>
15342 *
15343 * @return {AV.Relation} the relation for the users belonging to this
15344 * role.
15345 */
15346 getUsers: function getUsers() {
15347 return this.relation('users');
15348 },
15349
15350 /**
15351 * Gets the AV.Relation for the AV.Roles that are direct
15352 * children of this role. These roles' users are granted any privileges that
15353 * this role has been granted (e.g. read or write access through ACLs). You
15354 * can add or remove child roles from this role through this relation.
15355 *
15356 * <p>This is equivalent to calling role.relation("roles")</p>
15357 *
15358 * @return {AV.Relation} the relation for the roles belonging to this
15359 * role.
15360 */
15361 getRoles: function getRoles() {
15362 return this.relation('roles');
15363 },
15364
15365 /**
15366 * @ignore
15367 */
15368 validate: function validate(attrs, options) {
15369 if ('name' in attrs && attrs.name !== this.getName()) {
15370 var newName = attrs.name;
15371 if (this.id && this.id !== attrs.objectId) {
15372 // Check to see if the objectId being set matches this.id.
15373 // This happens during a fetch -- the id is set before calling fetch.
15374 // Let the name be set in this case.
15375 return new AVError(AVError.OTHER_CAUSE, "A role's name can only be set before it has been saved.");
15376 }
15377 if (!_.isString(newName)) {
15378 return new AVError(AVError.OTHER_CAUSE, "A role's name must be a String.");
15379 }
15380 if (!/^[0-9a-zA-Z\-_ ]+$/.test(newName)) {
15381 return new AVError(AVError.OTHER_CAUSE, "A role's name can only contain alphanumeric characters, _," + ' -, and spaces.');
15382 }
15383 }
15384 if (AV.Object.prototype.validate) {
15385 return AV.Object.prototype.validate.call(this, attrs, options);
15386 }
15387 return false;
15388 }
15389 });
15390};
15391
15392/***/ }),
15393/* 353 */
15394/***/ (function(module, exports, __webpack_require__) {
15395
15396"use strict";
15397
15398
15399var _stringify = __webpack_require__(21);
15400
15401var _stringify2 = _interopRequireDefault(_stringify);
15402
15403var _defineProperty2 = __webpack_require__(354);
15404
15405var _defineProperty3 = _interopRequireDefault(_defineProperty2);
15406
15407var _promise = __webpack_require__(3);
15408
15409var _promise2 = _interopRequireDefault(_promise);
15410
15411function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15412
15413var _ = __webpack_require__(0);
15414var uuid = __webpack_require__(177);
15415var AVError = __webpack_require__(34);
15416
15417var _require = __webpack_require__(14),
15418 AVRequest = _require._request,
15419 request = _require.request;
15420
15421var _require2 = __webpack_require__(43),
15422 getAdapter = _require2.getAdapter;
15423
15424var PLATFORM_ANONYMOUS = 'anonymous';
15425var PLATFORM_QQAPP = 'lc_qqapp';
15426
15427var mergeUnionDataIntoAuthData = function mergeUnionDataIntoAuthData() {
15428 var defaultUnionIdPlatform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'weixin';
15429 return function (authData, unionId) {
15430 var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
15431 _ref$unionIdPlatform = _ref.unionIdPlatform,
15432 unionIdPlatform = _ref$unionIdPlatform === undefined ? defaultUnionIdPlatform : _ref$unionIdPlatform,
15433 _ref$asMainAccount = _ref.asMainAccount,
15434 asMainAccount = _ref$asMainAccount === undefined ? false : _ref$asMainAccount;
15435
15436 if (typeof unionId !== 'string') throw new AVError(AVError.OTHER_CAUSE, 'unionId is not a string');
15437 if (typeof unionIdPlatform !== 'string') throw new AVError(AVError.OTHER_CAUSE, 'unionIdPlatform is not a string');
15438
15439 return _.extend({}, authData, {
15440 platform: unionIdPlatform,
15441 unionid: unionId,
15442 main_account: Boolean(asMainAccount)
15443 });
15444 };
15445};
15446
15447module.exports = function (AV) {
15448 /**
15449 * @class
15450 *
15451 * <p>An AV.User object is a local representation of a user persisted to the
15452 * LeanCloud server. This class is a subclass of an AV.Object, and retains the
15453 * same functionality of an AV.Object, but also extends it with various
15454 * user specific methods, like authentication, signing up, and validation of
15455 * uniqueness.</p>
15456 */
15457 AV.User = AV.Object.extend('_User',
15458 /** @lends AV.User.prototype */{
15459 // Instance Variables
15460 _isCurrentUser: false,
15461
15462 // Instance Methods
15463
15464 /**
15465 * Internal method to handle special fields in a _User response.
15466 * @private
15467 */
15468 _mergeMagicFields: function _mergeMagicFields(attrs) {
15469 if (attrs.sessionToken) {
15470 this._sessionToken = attrs.sessionToken;
15471 delete attrs.sessionToken;
15472 }
15473 return AV.User.__super__._mergeMagicFields.call(this, attrs);
15474 },
15475
15476 /**
15477 * Removes null values from authData (which exist temporarily for
15478 * unlinking)
15479 * @private
15480 */
15481 _cleanupAuthData: function _cleanupAuthData() {
15482 if (!this.isCurrent()) {
15483 return;
15484 }
15485 var authData = this.get('authData');
15486 if (!authData) {
15487 return;
15488 }
15489 AV._objectEach(this.get('authData'), function (value, key) {
15490 if (!authData[key]) {
15491 delete authData[key];
15492 }
15493 });
15494 },
15495
15496 /**
15497 * Synchronizes authData for all providers.
15498 * @private
15499 */
15500 _synchronizeAllAuthData: function _synchronizeAllAuthData() {
15501 var authData = this.get('authData');
15502 if (!authData) {
15503 return;
15504 }
15505
15506 var self = this;
15507 AV._objectEach(this.get('authData'), function (value, key) {
15508 self._synchronizeAuthData(key);
15509 });
15510 },
15511
15512 /**
15513 * Synchronizes auth data for a provider (e.g. puts the access token in the
15514 * right place to be used by the Facebook SDK).
15515 * @private
15516 */
15517 _synchronizeAuthData: function _synchronizeAuthData(provider) {
15518 if (!this.isCurrent()) {
15519 return;
15520 }
15521 var authType;
15522 if (_.isString(provider)) {
15523 authType = provider;
15524 provider = AV.User._authProviders[authType];
15525 } else {
15526 authType = provider.getAuthType();
15527 }
15528 var authData = this.get('authData');
15529 if (!authData || !provider) {
15530 return;
15531 }
15532 var success = provider.restoreAuthentication(authData[authType]);
15533 if (!success) {
15534 this.dissociateAuthData(provider);
15535 }
15536 },
15537
15538 _handleSaveResult: function _handleSaveResult(makeCurrent) {
15539 // Clean up and synchronize the authData object, removing any unset values
15540 if (makeCurrent && !AV._config.disableCurrentUser) {
15541 this._isCurrentUser = true;
15542 }
15543 this._cleanupAuthData();
15544 this._synchronizeAllAuthData();
15545 // Don't keep the password around.
15546 delete this._serverData.password;
15547 this._rebuildEstimatedDataForKey('password');
15548 this._refreshCache();
15549 if ((makeCurrent || this.isCurrent()) && !AV._config.disableCurrentUser) {
15550 // Some old version of leanengine-node-sdk will overwrite
15551 // AV.User._saveCurrentUser which returns no Promise.
15552 // So we need a Promise wrapper.
15553 return _promise2.default.resolve(AV.User._saveCurrentUser(this));
15554 } else {
15555 return _promise2.default.resolve();
15556 }
15557 },
15558
15559 /**
15560 * Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can
15561 * call linkWith on the user (even if it doesn't exist yet on the server).
15562 * @private
15563 */
15564 _linkWith: function _linkWith(provider, data) {
15565 var _this = this;
15566
15567 var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
15568 _ref2$failOnNotExist = _ref2.failOnNotExist,
15569 failOnNotExist = _ref2$failOnNotExist === undefined ? false : _ref2$failOnNotExist;
15570
15571 var authType;
15572 if (_.isString(provider)) {
15573 authType = provider;
15574 provider = AV.User._authProviders[provider];
15575 } else {
15576 authType = provider.getAuthType();
15577 }
15578 if (data) {
15579 return this.save({ authData: (0, _defineProperty3.default)({}, authType, data) }, {
15580 fetchWhenSave: !!this.get('authData'),
15581 _failOnNotExist: failOnNotExist
15582 }).then(function (model) {
15583 return model._handleSaveResult(true).then(function () {
15584 return model;
15585 });
15586 });
15587 } else {
15588 return provider.authenticate().then(function (result) {
15589 return _this._linkWith(provider, result);
15590 });
15591 }
15592 },
15593
15594 /**
15595 * Associate the user with a third party authData.
15596 * @since 3.3.0
15597 * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 }
15598 * @param {string} platform Available platform for sign up.
15599 * @return {Promise<AV.User>} A promise that is fulfilled with the user when completed.
15600 * @example user.associateWithAuthData({
15601 * openid: 'abc123',
15602 * access_token: '123abc',
15603 * expires_in: 1382686496
15604 * }, 'weixin').then(function(user) {
15605 * //Access user here
15606 * }).catch(function(error) {
15607 * //console.error("error: ", error);
15608 * });
15609 */
15610 associateWithAuthData: function associateWithAuthData(authData, platform) {
15611 return this._linkWith(platform, authData);
15612 },
15613
15614
15615 /**
15616 * Associate the user with a third party authData and unionId.
15617 * @since 3.5.0
15618 * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 }
15619 * @param {string} platform Available platform for sign up.
15620 * @param {string} unionId
15621 * @param {Object} [unionLoginOptions]
15622 * @param {string} [unionLoginOptions.unionIdPlatform = 'weixin'] unionId platform
15623 * @param {boolean} [unionLoginOptions.asMainAccount = false] If true, the unionId will be associated with the user.
15624 * @return {Promise<AV.User>} A promise that is fulfilled with the user when completed.
15625 * @example user.associateWithAuthDataAndUnionId({
15626 * openid: 'abc123',
15627 * access_token: '123abc',
15628 * expires_in: 1382686496
15629 * }, 'weixin', 'union123', {
15630 * unionIdPlatform: 'weixin',
15631 * asMainAccount: true,
15632 * }).then(function(user) {
15633 * //Access user here
15634 * }).catch(function(error) {
15635 * //console.error("error: ", error);
15636 * });
15637 */
15638 associateWithAuthDataAndUnionId: function associateWithAuthDataAndUnionId(authData, platform, unionId, unionOptions) {
15639 return this._linkWith(platform, mergeUnionDataIntoAuthData()(authData, unionId, unionOptions));
15640 },
15641
15642
15643 /**
15644 * Associate the user with the identity of the current mini-app.
15645 * @since 4.6.0
15646 * @param {Object} [authInfo]
15647 * @param {Object} [option]
15648 * @param {Boolean} [option.failOnNotExist] If true, the login request will fail when no user matches this authInfo.authData exists.
15649 * @return {Promise<AV.User>}
15650 */
15651 associateWithMiniApp: function associateWithMiniApp(authInfo, option) {
15652 var _this2 = this;
15653
15654 if (authInfo === undefined) {
15655 var getAuthInfo = getAdapter('getAuthInfo');
15656 return getAuthInfo().then(function (authInfo) {
15657 return _this2._linkWith(authInfo.provider, authInfo.authData, option);
15658 });
15659 }
15660 return this._linkWith(authInfo.provider, authInfo.authData, option);
15661 },
15662
15663
15664 /**
15665 * 将用户与 QQ 小程序用户进行关联。适用于为已经在用户系统中存在的用户关联当前使用 QQ 小程序的微信帐号。
15666 * 仅在 QQ 小程序中可用。
15667 *
15668 * @deprecated Please use {@link AV.User#associateWithMiniApp}
15669 * @since 4.2.0
15670 * @param {Object} [options]
15671 * @param {boolean} [options.preferUnionId = false] 如果服务端在登录时获取到了用户的 UnionId,是否将 UnionId 保存在用户账号中。
15672 * @param {string} [options.unionIdPlatform = 'qq'] (only take effect when preferUnionId) unionId platform
15673 * @param {boolean} [options.asMainAccount = true] (only take effect when preferUnionId) If true, the unionId will be associated with the user.
15674 * @return {Promise<AV.User>}
15675 */
15676 associateWithQQApp: function associateWithQQApp() {
15677 var _this3 = this;
15678
15679 var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
15680 _ref3$preferUnionId = _ref3.preferUnionId,
15681 preferUnionId = _ref3$preferUnionId === undefined ? false : _ref3$preferUnionId,
15682 _ref3$unionIdPlatform = _ref3.unionIdPlatform,
15683 unionIdPlatform = _ref3$unionIdPlatform === undefined ? 'qq' : _ref3$unionIdPlatform,
15684 _ref3$asMainAccount = _ref3.asMainAccount,
15685 asMainAccount = _ref3$asMainAccount === undefined ? true : _ref3$asMainAccount;
15686
15687 var getAuthInfo = getAdapter('getAuthInfo');
15688 return getAuthInfo({
15689 preferUnionId: preferUnionId,
15690 asMainAccount: asMainAccount,
15691 platform: unionIdPlatform
15692 }).then(function (authInfo) {
15693 authInfo.provider = PLATFORM_QQAPP;
15694 return _this3.associateWithMiniApp(authInfo);
15695 });
15696 },
15697
15698
15699 /**
15700 * 将用户与微信小程序用户进行关联。适用于为已经在用户系统中存在的用户关联当前使用微信小程序的微信帐号。
15701 * 仅在微信小程序中可用。
15702 *
15703 * @deprecated Please use {@link AV.User#associateWithMiniApp}
15704 * @since 3.13.0
15705 * @param {Object} [options]
15706 * @param {boolean} [options.preferUnionId = false] 当用户满足 {@link https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/union-id.html 获取 UnionId 的条件} 时,是否将 UnionId 保存在用户账号中。
15707 * @param {string} [options.unionIdPlatform = 'weixin'] (only take effect when preferUnionId) unionId platform
15708 * @param {boolean} [options.asMainAccount = true] (only take effect when preferUnionId) If true, the unionId will be associated with the user.
15709 * @return {Promise<AV.User>}
15710 */
15711 associateWithWeapp: function associateWithWeapp() {
15712 var _this4 = this;
15713
15714 var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
15715 _ref4$preferUnionId = _ref4.preferUnionId,
15716 preferUnionId = _ref4$preferUnionId === undefined ? false : _ref4$preferUnionId,
15717 _ref4$unionIdPlatform = _ref4.unionIdPlatform,
15718 unionIdPlatform = _ref4$unionIdPlatform === undefined ? 'weixin' : _ref4$unionIdPlatform,
15719 _ref4$asMainAccount = _ref4.asMainAccount,
15720 asMainAccount = _ref4$asMainAccount === undefined ? true : _ref4$asMainAccount;
15721
15722 var getAuthInfo = getAdapter('getAuthInfo');
15723 return getAuthInfo({
15724 preferUnionId: preferUnionId,
15725 asMainAccount: asMainAccount,
15726 platform: unionIdPlatform
15727 }).then(function (authInfo) {
15728 return _this4.associateWithMiniApp(authInfo);
15729 });
15730 },
15731
15732
15733 /**
15734 * @deprecated renamed to {@link AV.User#associateWithWeapp}
15735 * @return {Promise<AV.User>}
15736 */
15737 linkWithWeapp: function linkWithWeapp(options) {
15738 console.warn('DEPRECATED: User#linkWithWeapp 已废弃,请使用 User#associateWithWeapp 代替');
15739 return this.associateWithWeapp(options);
15740 },
15741
15742
15743 /**
15744 * 将用户与 QQ 小程序用户进行关联。适用于为已经在用户系统中存在的用户关联当前使用 QQ 小程序的 QQ 帐号。
15745 * 仅在 QQ 小程序中可用。
15746 *
15747 * @deprecated Please use {@link AV.User#associateWithMiniApp}
15748 * @since 4.2.0
15749 * @param {string} unionId
15750 * @param {Object} [unionOptions]
15751 * @param {string} [unionOptions.unionIdPlatform = 'qq'] unionId platform
15752 * @param {boolean} [unionOptions.asMainAccount = false] If true, the unionId will be associated with the user.
15753 * @return {Promise<AV.User>}
15754 */
15755 associateWithQQAppWithUnionId: function associateWithQQAppWithUnionId(unionId) {
15756 var _this5 = this;
15757
15758 var _ref5 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
15759 _ref5$unionIdPlatform = _ref5.unionIdPlatform,
15760 unionIdPlatform = _ref5$unionIdPlatform === undefined ? 'qq' : _ref5$unionIdPlatform,
15761 _ref5$asMainAccount = _ref5.asMainAccount,
15762 asMainAccount = _ref5$asMainAccount === undefined ? false : _ref5$asMainAccount;
15763
15764 var getAuthInfo = getAdapter('getAuthInfo');
15765 return getAuthInfo({ platform: unionIdPlatform }).then(function (authInfo) {
15766 authInfo = AV.User.mergeUnionId(authInfo, unionId, { asMainAccount: asMainAccount });
15767 authInfo.provider = PLATFORM_QQAPP;
15768 return _this5.associateWithMiniApp(authInfo);
15769 });
15770 },
15771
15772
15773 /**
15774 * 将用户与微信小程序用户进行关联。适用于为已经在用户系统中存在的用户关联当前使用微信小程序的微信帐号。
15775 * 仅在微信小程序中可用。
15776 *
15777 * @deprecated Please use {@link AV.User#associateWithMiniApp}
15778 * @since 3.13.0
15779 * @param {string} unionId
15780 * @param {Object} [unionOptions]
15781 * @param {string} [unionOptions.unionIdPlatform = 'weixin'] unionId platform
15782 * @param {boolean} [unionOptions.asMainAccount = false] If true, the unionId will be associated with the user.
15783 * @return {Promise<AV.User>}
15784 */
15785 associateWithWeappWithUnionId: function associateWithWeappWithUnionId(unionId) {
15786 var _this6 = this;
15787
15788 var _ref6 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
15789 _ref6$unionIdPlatform = _ref6.unionIdPlatform,
15790 unionIdPlatform = _ref6$unionIdPlatform === undefined ? 'weixin' : _ref6$unionIdPlatform,
15791 _ref6$asMainAccount = _ref6.asMainAccount,
15792 asMainAccount = _ref6$asMainAccount === undefined ? false : _ref6$asMainAccount;
15793
15794 var getAuthInfo = getAdapter('getAuthInfo');
15795 return getAuthInfo({ platform: unionIdPlatform }).then(function (authInfo) {
15796 authInfo = AV.User.mergeUnionId(authInfo, unionId, { asMainAccount: asMainAccount });
15797 return _this6.associateWithMiniApp(authInfo);
15798 });
15799 },
15800
15801
15802 /**
15803 * Unlinks a user from a service.
15804 * @param {string} platform
15805 * @return {Promise<AV.User>}
15806 * @since 3.3.0
15807 */
15808 dissociateAuthData: function dissociateAuthData(provider) {
15809 this.unset('authData.' + provider);
15810 return this.save().then(function (model) {
15811 return model._handleSaveResult(true).then(function () {
15812 return model;
15813 });
15814 });
15815 },
15816
15817
15818 /**
15819 * @private
15820 * @deprecated
15821 */
15822 _unlinkFrom: function _unlinkFrom(provider) {
15823 console.warn('DEPRECATED: User#_unlinkFrom 已废弃,请使用 User#dissociateAuthData 代替');
15824 return this.dissociateAuthData(provider);
15825 },
15826
15827
15828 /**
15829 * Checks whether a user is linked to a service.
15830 * @private
15831 */
15832 _isLinked: function _isLinked(provider) {
15833 var authType;
15834 if (_.isString(provider)) {
15835 authType = provider;
15836 } else {
15837 authType = provider.getAuthType();
15838 }
15839 var authData = this.get('authData') || {};
15840 return !!authData[authType];
15841 },
15842
15843 /**
15844 * Checks whether a user is anonymous.
15845 * @since 3.9.0
15846 * @return {boolean}
15847 */
15848 isAnonymous: function isAnonymous() {
15849 return this._isLinked(PLATFORM_ANONYMOUS);
15850 },
15851
15852
15853 logOut: function logOut() {
15854 this._logOutWithAll();
15855 this._isCurrentUser = false;
15856 },
15857
15858 /**
15859 * Deauthenticates all providers.
15860 * @private
15861 */
15862 _logOutWithAll: function _logOutWithAll() {
15863 var authData = this.get('authData');
15864 if (!authData) {
15865 return;
15866 }
15867 var self = this;
15868 AV._objectEach(this.get('authData'), function (value, key) {
15869 self._logOutWith(key);
15870 });
15871 },
15872
15873 /**
15874 * Deauthenticates a single provider (e.g. removing access tokens from the
15875 * Facebook SDK).
15876 * @private
15877 */
15878 _logOutWith: function _logOutWith(provider) {
15879 if (!this.isCurrent()) {
15880 return;
15881 }
15882 if (_.isString(provider)) {
15883 provider = AV.User._authProviders[provider];
15884 }
15885 if (provider && provider.deauthenticate) {
15886 provider.deauthenticate();
15887 }
15888 },
15889
15890 /**
15891 * Signs up a new user. You should call this instead of save for
15892 * new AV.Users. This will create a new AV.User on the server, and
15893 * also persist the session on disk so that you can access the user using
15894 * <code>current</code>.
15895 *
15896 * <p>A username and password must be set before calling signUp.</p>
15897 *
15898 * @param {Object} attrs Extra fields to set on the new user, or null.
15899 * @param {AuthOptions} options
15900 * @return {Promise} A promise that is fulfilled when the signup
15901 * finishes.
15902 * @see AV.User.signUp
15903 */
15904 signUp: function signUp(attrs, options) {
15905 var error;
15906
15907 var username = attrs && attrs.username || this.get('username');
15908 if (!username || username === '') {
15909 error = new AVError(AVError.OTHER_CAUSE, 'Cannot sign up user with an empty name.');
15910 throw error;
15911 }
15912
15913 var password = attrs && attrs.password || this.get('password');
15914 if (!password || password === '') {
15915 error = new AVError(AVError.OTHER_CAUSE, 'Cannot sign up user with an empty password.');
15916 throw error;
15917 }
15918
15919 return this.save(attrs, options).then(function (model) {
15920 if (model.isAnonymous()) {
15921 model.unset('authData.' + PLATFORM_ANONYMOUS);
15922 model._opSetQueue = [{}];
15923 }
15924 return model._handleSaveResult(true).then(function () {
15925 return model;
15926 });
15927 });
15928 },
15929
15930 /**
15931 * Signs up a new user with mobile phone and sms code.
15932 * You should call this instead of save for
15933 * new AV.Users. This will create a new AV.User on the server, and
15934 * also persist the session on disk so that you can access the user using
15935 * <code>current</code>.
15936 *
15937 * <p>A username and password must be set before calling signUp.</p>
15938 *
15939 * @param {Object} attrs Extra fields to set on the new user, or null.
15940 * @param {AuthOptions} options
15941 * @return {Promise} A promise that is fulfilled when the signup
15942 * finishes.
15943 * @see AV.User.signUpOrlogInWithMobilePhone
15944 * @see AV.Cloud.requestSmsCode
15945 */
15946 signUpOrlogInWithMobilePhone: function signUpOrlogInWithMobilePhone(attrs) {
15947 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
15948
15949 var error;
15950
15951 var mobilePhoneNumber = attrs && attrs.mobilePhoneNumber || this.get('mobilePhoneNumber');
15952 if (!mobilePhoneNumber || mobilePhoneNumber === '') {
15953 error = new AVError(AVError.OTHER_CAUSE, 'Cannot sign up or login user by mobilePhoneNumber ' + 'with an empty mobilePhoneNumber.');
15954 throw error;
15955 }
15956
15957 var smsCode = attrs && attrs.smsCode || this.get('smsCode');
15958 if (!smsCode || smsCode === '') {
15959 error = new AVError(AVError.OTHER_CAUSE, 'Cannot sign up or login user by mobilePhoneNumber ' + 'with an empty smsCode.');
15960 throw error;
15961 }
15962
15963 options._makeRequest = function (route, className, id, method, json) {
15964 return AVRequest('usersByMobilePhone', null, null, 'POST', json);
15965 };
15966 return this.save(attrs, options).then(function (model) {
15967 delete model.attributes.smsCode;
15968 delete model._serverData.smsCode;
15969 return model._handleSaveResult(true).then(function () {
15970 return model;
15971 });
15972 });
15973 },
15974
15975 /**
15976 * The same with {@link AV.User.loginWithAuthData}, except that you can set attributes before login.
15977 * @since 3.7.0
15978 */
15979 loginWithAuthData: function loginWithAuthData(authData, platform, options) {
15980 return this._linkWith(platform, authData, options);
15981 },
15982
15983
15984 /**
15985 * The same with {@link AV.User.loginWithAuthDataAndUnionId}, except that you can set attributes before login.
15986 * @since 3.7.0
15987 */
15988 loginWithAuthDataAndUnionId: function loginWithAuthDataAndUnionId(authData, platform, unionId, unionLoginOptions) {
15989 return this.loginWithAuthData(mergeUnionDataIntoAuthData()(authData, unionId, unionLoginOptions), platform, unionLoginOptions);
15990 },
15991
15992
15993 /**
15994 * The same with {@link AV.User.loginWithWeapp}, except that you can set attributes before login.
15995 * @deprecated please use {@link AV.User#loginWithMiniApp}
15996 * @since 3.7.0
15997 * @param {Object} [options]
15998 * @param {boolean} [options.failOnNotExist] If true, the login request will fail when no user matches this authData exists.
15999 * @param {boolean} [options.preferUnionId] 当用户满足 {@link https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/union-id.html 获取 UnionId 的条件} 时,是否使用 UnionId 登录。(since 3.13.0)
16000 * @param {string} [options.unionIdPlatform = 'weixin'] (only take effect when preferUnionId) unionId platform
16001 * @param {boolean} [options.asMainAccount = true] (only take effect when preferUnionId) If true, the unionId will be associated with the user.
16002 * @return {Promise<AV.User>}
16003 */
16004 loginWithWeapp: function loginWithWeapp() {
16005 var _this7 = this;
16006
16007 var _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
16008 _ref7$preferUnionId = _ref7.preferUnionId,
16009 preferUnionId = _ref7$preferUnionId === undefined ? false : _ref7$preferUnionId,
16010 _ref7$unionIdPlatform = _ref7.unionIdPlatform,
16011 unionIdPlatform = _ref7$unionIdPlatform === undefined ? 'weixin' : _ref7$unionIdPlatform,
16012 _ref7$asMainAccount = _ref7.asMainAccount,
16013 asMainAccount = _ref7$asMainAccount === undefined ? true : _ref7$asMainAccount,
16014 _ref7$failOnNotExist = _ref7.failOnNotExist,
16015 failOnNotExist = _ref7$failOnNotExist === undefined ? false : _ref7$failOnNotExist;
16016
16017 var getAuthInfo = getAdapter('getAuthInfo');
16018 return getAuthInfo({
16019 preferUnionId: preferUnionId,
16020 asMainAccount: asMainAccount,
16021 platform: unionIdPlatform
16022 }).then(function (authInfo) {
16023 return _this7.loginWithMiniApp(authInfo, { failOnNotExist: failOnNotExist });
16024 });
16025 },
16026
16027
16028 /**
16029 * The same with {@link AV.User.loginWithWeappWithUnionId}, except that you can set attributes before login.
16030 * @deprecated please use {@link AV.User#loginWithMiniApp}
16031 * @since 3.13.0
16032 */
16033 loginWithWeappWithUnionId: function loginWithWeappWithUnionId(unionId) {
16034 var _this8 = this;
16035
16036 var _ref8 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
16037 _ref8$unionIdPlatform = _ref8.unionIdPlatform,
16038 unionIdPlatform = _ref8$unionIdPlatform === undefined ? 'weixin' : _ref8$unionIdPlatform,
16039 _ref8$asMainAccount = _ref8.asMainAccount,
16040 asMainAccount = _ref8$asMainAccount === undefined ? false : _ref8$asMainAccount,
16041 _ref8$failOnNotExist = _ref8.failOnNotExist,
16042 failOnNotExist = _ref8$failOnNotExist === undefined ? false : _ref8$failOnNotExist;
16043
16044 var getAuthInfo = getAdapter('getAuthInfo');
16045 return getAuthInfo({ platform: unionIdPlatform }).then(function (authInfo) {
16046 authInfo = AV.User.mergeUnionId(authInfo, unionId, { asMainAccount: asMainAccount });
16047 return _this8.loginWithMiniApp(authInfo, { failOnNotExist: failOnNotExist });
16048 });
16049 },
16050
16051
16052 /**
16053 * The same with {@link AV.User.loginWithQQApp}, except that you can set attributes before login.
16054 * @deprecated please use {@link AV.User#loginWithMiniApp}
16055 * @since 4.2.0
16056 * @param {Object} [options]
16057 * @param {boolean} [options.failOnNotExist] If true, the login request will fail when no user matches this authData exists.
16058 * @param {boolean} [options.preferUnionId] 如果服务端在登录时获取到了用户的 UnionId,是否将 UnionId 保存在用户账号中。
16059 * @param {string} [options.unionIdPlatform = 'qq'] (only take effect when preferUnionId) unionId platform
16060 * @param {boolean} [options.asMainAccount = true] (only take effect when preferUnionId) If true, the unionId will be associated with the user.
16061 */
16062 loginWithQQApp: function loginWithQQApp() {
16063 var _this9 = this;
16064
16065 var _ref9 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
16066 _ref9$preferUnionId = _ref9.preferUnionId,
16067 preferUnionId = _ref9$preferUnionId === undefined ? false : _ref9$preferUnionId,
16068 _ref9$unionIdPlatform = _ref9.unionIdPlatform,
16069 unionIdPlatform = _ref9$unionIdPlatform === undefined ? 'qq' : _ref9$unionIdPlatform,
16070 _ref9$asMainAccount = _ref9.asMainAccount,
16071 asMainAccount = _ref9$asMainAccount === undefined ? true : _ref9$asMainAccount,
16072 _ref9$failOnNotExist = _ref9.failOnNotExist,
16073 failOnNotExist = _ref9$failOnNotExist === undefined ? false : _ref9$failOnNotExist;
16074
16075 var getAuthInfo = getAdapter('getAuthInfo');
16076 return getAuthInfo({
16077 preferUnionId: preferUnionId,
16078 asMainAccount: asMainAccount,
16079 platform: unionIdPlatform
16080 }).then(function (authInfo) {
16081 authInfo.provider = PLATFORM_QQAPP;
16082 return _this9.loginWithMiniApp(authInfo, { failOnNotExist: failOnNotExist });
16083 });
16084 },
16085
16086
16087 /**
16088 * The same with {@link AV.User.loginWithQQAppWithUnionId}, except that you can set attributes before login.
16089 * @deprecated please use {@link AV.User#loginWithMiniApp}
16090 * @since 4.2.0
16091 */
16092 loginWithQQAppWithUnionId: function loginWithQQAppWithUnionId(unionId) {
16093 var _this10 = this;
16094
16095 var _ref10 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
16096 _ref10$unionIdPlatfor = _ref10.unionIdPlatform,
16097 unionIdPlatform = _ref10$unionIdPlatfor === undefined ? 'qq' : _ref10$unionIdPlatfor,
16098 _ref10$asMainAccount = _ref10.asMainAccount,
16099 asMainAccount = _ref10$asMainAccount === undefined ? false : _ref10$asMainAccount,
16100 _ref10$failOnNotExist = _ref10.failOnNotExist,
16101 failOnNotExist = _ref10$failOnNotExist === undefined ? false : _ref10$failOnNotExist;
16102
16103 var getAuthInfo = getAdapter('getAuthInfo');
16104 return getAuthInfo({ platform: unionIdPlatform }).then(function (authInfo) {
16105 authInfo = AV.User.mergeUnionId(authInfo, unionId, { asMainAccount: asMainAccount });
16106 authInfo.provider = PLATFORM_QQAPP;
16107 return _this10.loginWithMiniApp(authInfo, { failOnNotExist: failOnNotExist });
16108 });
16109 },
16110
16111
16112 /**
16113 * The same with {@link AV.User.loginWithMiniApp}, except that you can set attributes before login.
16114 * @since 4.6.0
16115 */
16116 loginWithMiniApp: function loginWithMiniApp(authInfo, option) {
16117 var _this11 = this;
16118
16119 if (authInfo === undefined) {
16120 var getAuthInfo = getAdapter('getAuthInfo');
16121 return getAuthInfo().then(function (authInfo) {
16122 return _this11.loginWithAuthData(authInfo.authData, authInfo.provider, option);
16123 });
16124 }
16125 return this.loginWithAuthData(authInfo.authData, authInfo.provider, option);
16126 },
16127
16128
16129 /**
16130 * Logs in a AV.User. On success, this saves the session to localStorage,
16131 * so you can retrieve the currently logged in user using
16132 * <code>current</code>.
16133 *
16134 * <p>A username and password must be set before calling logIn.</p>
16135 *
16136 * @see AV.User.logIn
16137 * @return {Promise} A promise that is fulfilled with the user when
16138 * the login is complete.
16139 */
16140 logIn: function logIn() {
16141 var model = this;
16142 var request = AVRequest('login', null, null, 'POST', this.toJSON());
16143 return request.then(function (resp) {
16144 var serverAttrs = model.parse(resp);
16145 model._finishFetch(serverAttrs);
16146 return model._handleSaveResult(true).then(function () {
16147 if (!serverAttrs.smsCode) delete model.attributes['smsCode'];
16148 return model;
16149 });
16150 });
16151 },
16152 /**
16153 * @see AV.Object#save
16154 */
16155 save: function save(arg1, arg2, arg3) {
16156 var attrs, options;
16157 if (_.isObject(arg1) || _.isNull(arg1) || _.isUndefined(arg1)) {
16158 attrs = arg1;
16159 options = arg2;
16160 } else {
16161 attrs = {};
16162 attrs[arg1] = arg2;
16163 options = arg3;
16164 }
16165 options = options || {};
16166
16167 return AV.Object.prototype.save.call(this, attrs, options).then(function (model) {
16168 return model._handleSaveResult(false).then(function () {
16169 return model;
16170 });
16171 });
16172 },
16173
16174 /**
16175 * Follow a user
16176 * @since 0.3.0
16177 * @param {Object | AV.User | String} options if an AV.User or string is given, it will be used as the target user.
16178 * @param {AV.User | String} options.user The target user or user's objectId to follow.
16179 * @param {Object} [options.attributes] key-value attributes dictionary to be used as
16180 * conditions of followerQuery/followeeQuery.
16181 * @param {AuthOptions} [authOptions]
16182 */
16183 follow: function follow(options, authOptions) {
16184 if (!this.id) {
16185 throw new Error('Please signin.');
16186 }
16187 var user = void 0;
16188 var attributes = void 0;
16189 if (options.user) {
16190 user = options.user;
16191 attributes = options.attributes;
16192 } else {
16193 user = options;
16194 }
16195 var userObjectId = _.isString(user) ? user : user.id;
16196 if (!userObjectId) {
16197 throw new Error('Invalid target user.');
16198 }
16199 var route = 'users/' + this.id + '/friendship/' + userObjectId;
16200 var request = AVRequest(route, null, null, 'POST', AV._encode(attributes), authOptions);
16201 return request;
16202 },
16203
16204 /**
16205 * Unfollow a user.
16206 * @since 0.3.0
16207 * @param {Object | AV.User | String} options if an AV.User or string is given, it will be used as the target user.
16208 * @param {AV.User | String} options.user The target user or user's objectId to unfollow.
16209 * @param {AuthOptions} [authOptions]
16210 */
16211 unfollow: function unfollow(options, authOptions) {
16212 if (!this.id) {
16213 throw new Error('Please signin.');
16214 }
16215 var user = void 0;
16216 if (options.user) {
16217 user = options.user;
16218 } else {
16219 user = options;
16220 }
16221 var userObjectId = _.isString(user) ? user : user.id;
16222 if (!userObjectId) {
16223 throw new Error('Invalid target user.');
16224 }
16225 var route = 'users/' + this.id + '/friendship/' + userObjectId;
16226 var request = AVRequest(route, null, null, 'DELETE', null, authOptions);
16227 return request;
16228 },
16229
16230 /**
16231 * Get the user's followers and followees.
16232 * @since 4.8.0
16233 * @param {Object} [options]
16234 * @param {Number} [options.skip]
16235 * @param {Number} [options.limit]
16236 * @param {AuthOptions} [authOptions]
16237 */
16238 getFollowersAndFollowees: function getFollowersAndFollowees(options, authOptions) {
16239 if (!this.id) {
16240 throw new Error('Please signin.');
16241 }
16242 return request({
16243 method: 'GET',
16244 path: '/users/' + this.id + '/followersAndFollowees',
16245 query: {
16246 skip: options && options.skip,
16247 limit: options && options.limit,
16248 include: 'follower,followee',
16249 keys: 'follower,followee'
16250 },
16251 authOptions: authOptions
16252 }).then(function (_ref11) {
16253 var followers = _ref11.followers,
16254 followees = _ref11.followees;
16255 return {
16256 followers: followers.map(function (_ref12) {
16257 var follower = _ref12.follower;
16258 return AV._decode(follower);
16259 }),
16260 followees: followees.map(function (_ref13) {
16261 var followee = _ref13.followee;
16262 return AV._decode(followee);
16263 })
16264 };
16265 });
16266 },
16267
16268 /**
16269 *Create a follower query to query the user's followers.
16270 * @since 0.3.0
16271 * @see AV.User#followerQuery
16272 */
16273 followerQuery: function followerQuery() {
16274 return AV.User.followerQuery(this.id);
16275 },
16276
16277 /**
16278 *Create a followee query to query the user's followees.
16279 * @since 0.3.0
16280 * @see AV.User#followeeQuery
16281 */
16282 followeeQuery: function followeeQuery() {
16283 return AV.User.followeeQuery(this.id);
16284 },
16285
16286 /**
16287 * @see AV.Object#fetch
16288 */
16289 fetch: function fetch(fetchOptions, options) {
16290 return AV.Object.prototype.fetch.call(this, fetchOptions, options).then(function (model) {
16291 return model._handleSaveResult(false).then(function () {
16292 return model;
16293 });
16294 });
16295 },
16296
16297 /**
16298 * Update user's new password safely based on old password.
16299 * @param {String} oldPassword the old password.
16300 * @param {String} newPassword the new password.
16301 * @param {AuthOptions} options
16302 */
16303 updatePassword: function updatePassword(oldPassword, newPassword, options) {
16304 var _this12 = this;
16305
16306 var route = 'users/' + this.id + '/updatePassword';
16307 var params = {
16308 old_password: oldPassword,
16309 new_password: newPassword
16310 };
16311 var request = AVRequest(route, null, null, 'PUT', params, options);
16312 return request.then(function (resp) {
16313 _this12._finishFetch(_this12.parse(resp));
16314 return _this12._handleSaveResult(true).then(function () {
16315 return resp;
16316 });
16317 });
16318 },
16319
16320 /**
16321 * Returns true if <code>current</code> would return this user.
16322 * @see AV.User#current
16323 */
16324 isCurrent: function isCurrent() {
16325 return this._isCurrentUser;
16326 },
16327
16328 /**
16329 * Returns get("username").
16330 * @return {String}
16331 * @see AV.Object#get
16332 */
16333 getUsername: function getUsername() {
16334 return this.get('username');
16335 },
16336
16337 /**
16338 * Returns get("mobilePhoneNumber").
16339 * @return {String}
16340 * @see AV.Object#get
16341 */
16342 getMobilePhoneNumber: function getMobilePhoneNumber() {
16343 return this.get('mobilePhoneNumber');
16344 },
16345
16346 /**
16347 * Calls set("mobilePhoneNumber", phoneNumber, options) and returns the result.
16348 * @param {String} mobilePhoneNumber
16349 * @return {Boolean}
16350 * @see AV.Object#set
16351 */
16352 setMobilePhoneNumber: function setMobilePhoneNumber(phone, options) {
16353 return this.set('mobilePhoneNumber', phone, options);
16354 },
16355
16356 /**
16357 * Calls set("username", username, options) and returns the result.
16358 * @param {String} username
16359 * @return {Boolean}
16360 * @see AV.Object#set
16361 */
16362 setUsername: function setUsername(username, options) {
16363 return this.set('username', username, options);
16364 },
16365
16366 /**
16367 * Calls set("password", password, options) and returns the result.
16368 * @param {String} password
16369 * @return {Boolean}
16370 * @see AV.Object#set
16371 */
16372 setPassword: function setPassword(password, options) {
16373 return this.set('password', password, options);
16374 },
16375
16376 /**
16377 * Returns get("email").
16378 * @return {String}
16379 * @see AV.Object#get
16380 */
16381 getEmail: function getEmail() {
16382 return this.get('email');
16383 },
16384
16385 /**
16386 * Calls set("email", email, options) and returns the result.
16387 * @param {String} email
16388 * @param {AuthOptions} options
16389 * @return {Boolean}
16390 * @see AV.Object#set
16391 */
16392 setEmail: function setEmail(email, options) {
16393 return this.set('email', email, options);
16394 },
16395
16396 /**
16397 * Checks whether this user is the current user and has been authenticated.
16398 * @deprecated 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),
16399 * 如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id
16400 * @return (Boolean) whether this user is the current user and is logged in.
16401 */
16402 authenticated: function authenticated() {
16403 console.warn('DEPRECATED: 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id。');
16404 return !!this._sessionToken && !AV._config.disableCurrentUser && AV.User.current() && AV.User.current().id === this.id;
16405 },
16406
16407 /**
16408 * Detects if current sessionToken is valid.
16409 *
16410 * @since 2.0.0
16411 * @return Promise.<Boolean>
16412 */
16413 isAuthenticated: function isAuthenticated() {
16414 var _this13 = this;
16415
16416 return _promise2.default.resolve().then(function () {
16417 return !!_this13._sessionToken && AV.User._fetchUserBySessionToken(_this13._sessionToken).then(function () {
16418 return true;
16419 }, function (error) {
16420 if (error.code === 211) {
16421 return false;
16422 }
16423 throw error;
16424 });
16425 });
16426 },
16427
16428
16429 /**
16430 * Get sessionToken of current user.
16431 * @return {String} sessionToken
16432 */
16433 getSessionToken: function getSessionToken() {
16434 return this._sessionToken;
16435 },
16436
16437
16438 /**
16439 * Refresh sessionToken of current user.
16440 * @since 2.1.0
16441 * @param {AuthOptions} [options]
16442 * @return {Promise.<AV.User>} user with refreshed sessionToken
16443 */
16444 refreshSessionToken: function refreshSessionToken(options) {
16445 var _this14 = this;
16446
16447 return AVRequest('users/' + this.id + '/refreshSessionToken', null, null, 'PUT', null, options).then(function (response) {
16448 _this14._finishFetch(response);
16449 return _this14._handleSaveResult(true).then(function () {
16450 return _this14;
16451 });
16452 });
16453 },
16454
16455
16456 /**
16457 * Get this user's Roles.
16458 * @param {AuthOptions} [options]
16459 * @return {Promise.<AV.Role[]>} A promise that is fulfilled with the roles when
16460 * the query is complete.
16461 */
16462 getRoles: function getRoles(options) {
16463 return AV.Relation.reverseQuery('_Role', 'users', this).find(options);
16464 }
16465 },
16466 /** @lends AV.User */{
16467 // Class Variables
16468
16469 // The currently logged-in user.
16470 _currentUser: null,
16471
16472 // Whether currentUser is known to match the serialized version on disk.
16473 // This is useful for saving a localstorage check if you try to load
16474 // _currentUser frequently while there is none stored.
16475 _currentUserMatchesDisk: false,
16476
16477 // The localStorage key suffix that the current user is stored under.
16478 _CURRENT_USER_KEY: 'currentUser',
16479
16480 // The mapping of auth provider names to actual providers
16481 _authProviders: {},
16482
16483 // Class Methods
16484
16485 /**
16486 * Signs up a new user with a username (or email) and password.
16487 * This will create a new AV.User on the server, and also persist the
16488 * session in localStorage so that you can access the user using
16489 * {@link #current}.
16490 *
16491 * @param {String} username The username (or email) to sign up with.
16492 * @param {String} password The password to sign up with.
16493 * @param {Object} [attrs] Extra fields to set on the new user.
16494 * @param {AuthOptions} [options]
16495 * @return {Promise} A promise that is fulfilled with the user when
16496 * the signup completes.
16497 * @see AV.User#signUp
16498 */
16499 signUp: function signUp(username, password, attrs, options) {
16500 attrs = attrs || {};
16501 attrs.username = username;
16502 attrs.password = password;
16503 var user = AV.Object._create('_User');
16504 return user.signUp(attrs, options);
16505 },
16506
16507 /**
16508 * Logs in a user with a username (or email) and password. On success, this
16509 * saves the session to disk, so you can retrieve the currently logged in
16510 * user using <code>current</code>.
16511 *
16512 * @param {String} username The username (or email) to log in with.
16513 * @param {String} password The password to log in with.
16514 * @return {Promise} A promise that is fulfilled with the user when
16515 * the login completes.
16516 * @see AV.User#logIn
16517 */
16518 logIn: function logIn(username, password) {
16519 var user = AV.Object._create('_User');
16520 user._finishFetch({ username: username, password: password });
16521 return user.logIn();
16522 },
16523
16524 /**
16525 * Logs in a user with a session token. On success, this saves the session
16526 * to disk, so you can retrieve the currently logged in user using
16527 * <code>current</code>.
16528 *
16529 * @param {String} sessionToken The sessionToken to log in with.
16530 * @return {Promise} A promise that is fulfilled with the user when
16531 * the login completes.
16532 */
16533 become: function become(sessionToken) {
16534 return this._fetchUserBySessionToken(sessionToken).then(function (user) {
16535 return user._handleSaveResult(true).then(function () {
16536 return user;
16537 });
16538 });
16539 },
16540
16541 _fetchUserBySessionToken: function _fetchUserBySessionToken(sessionToken) {
16542 if (sessionToken === undefined) {
16543 return _promise2.default.reject(new Error('The sessionToken cannot be undefined'));
16544 }
16545
16546 var user = AV.Object._create('_User');
16547 return request({
16548 method: 'GET',
16549 path: '/users/me',
16550 authOptions: {
16551 sessionToken: sessionToken
16552 }
16553 }).then(function (resp) {
16554 var serverAttrs = user.parse(resp);
16555 user._finishFetch(serverAttrs);
16556 return user;
16557 });
16558 },
16559
16560 /**
16561 * Logs in a user with a mobile phone number and sms code sent by
16562 * AV.User.requestLoginSmsCode.On success, this
16563 * saves the session to disk, so you can retrieve the currently logged in
16564 * user using <code>current</code>.
16565 *
16566 * @param {String} mobilePhone The user's mobilePhoneNumber
16567 * @param {String} smsCode The sms code sent by AV.User.requestLoginSmsCode
16568 * @return {Promise} A promise that is fulfilled with the user when
16569 * the login completes.
16570 * @see AV.User#logIn
16571 */
16572 logInWithMobilePhoneSmsCode: function logInWithMobilePhoneSmsCode(mobilePhone, smsCode) {
16573 var user = AV.Object._create('_User');
16574 user._finishFetch({ mobilePhoneNumber: mobilePhone, smsCode: smsCode });
16575 return user.logIn();
16576 },
16577
16578 /**
16579 * Signs up or logs in a user with a mobilePhoneNumber and smsCode.
16580 * On success, this saves the session to disk, so you can retrieve the currently
16581 * logged in user using <code>current</code>.
16582 *
16583 * @param {String} mobilePhoneNumber The user's mobilePhoneNumber.
16584 * @param {String} smsCode The sms code sent by AV.Cloud.requestSmsCode
16585 * @param {Object} attributes The user's other attributes such as username etc.
16586 * @param {AuthOptions} options
16587 * @return {Promise} A promise that is fulfilled with the user when
16588 * the login completes.
16589 * @see AV.User#signUpOrlogInWithMobilePhone
16590 * @see AV.Cloud.requestSmsCode
16591 */
16592 signUpOrlogInWithMobilePhone: function signUpOrlogInWithMobilePhone(mobilePhoneNumber, smsCode, attrs, options) {
16593 attrs = attrs || {};
16594 attrs.mobilePhoneNumber = mobilePhoneNumber;
16595 attrs.smsCode = smsCode;
16596 var user = AV.Object._create('_User');
16597 return user.signUpOrlogInWithMobilePhone(attrs, options);
16598 },
16599
16600 /**
16601 * Logs in a user with a mobile phone number and password. On success, this
16602 * saves the session to disk, so you can retrieve the currently logged in
16603 * user using <code>current</code>.
16604 *
16605 * @param {String} mobilePhone The user's mobilePhoneNumber
16606 * @param {String} password The password to log in with.
16607 * @return {Promise} A promise that is fulfilled with the user when
16608 * the login completes.
16609 * @see AV.User#logIn
16610 */
16611 logInWithMobilePhone: function logInWithMobilePhone(mobilePhone, password) {
16612 var user = AV.Object._create('_User');
16613 user._finishFetch({
16614 mobilePhoneNumber: mobilePhone,
16615 password: password
16616 });
16617 return user.logIn();
16618 },
16619
16620 /**
16621 * Logs in a user with email and password.
16622 *
16623 * @since 3.13.0
16624 * @param {String} email The user's email.
16625 * @param {String} password The password to log in with.
16626 * @return {Promise} A promise that is fulfilled with the user when
16627 * the login completes.
16628 */
16629 loginWithEmail: function loginWithEmail(email, password) {
16630 var user = AV.Object._create('_User');
16631 user._finishFetch({
16632 email: email,
16633 password: password
16634 });
16635 return user.logIn();
16636 },
16637
16638
16639 /**
16640 * Signs up or logs in a user with a third party auth data(AccessToken).
16641 * On success, this saves the session to disk, so you can retrieve the currently
16642 * logged in user using <code>current</code>.
16643 *
16644 * @since 3.7.0
16645 * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 }
16646 * @param {string} platform Available platform for sign up.
16647 * @param {Object} [options]
16648 * @param {boolean} [options.failOnNotExist] If true, the login request will fail when no user matches this authData exists.
16649 * @return {Promise} A promise that is fulfilled with the user when
16650 * the login completes.
16651 * @example AV.User.loginWithAuthData({
16652 * openid: 'abc123',
16653 * access_token: '123abc',
16654 * expires_in: 1382686496
16655 * }, 'weixin').then(function(user) {
16656 * //Access user here
16657 * }).catch(function(error) {
16658 * //console.error("error: ", error);
16659 * });
16660 * @see {@link https://leancloud.cn/docs/js_guide.html#绑定第三方平台账户}
16661 */
16662 loginWithAuthData: function loginWithAuthData(authData, platform, options) {
16663 return AV.User._logInWith(platform, authData, options);
16664 },
16665
16666
16667 /**
16668 * @deprecated renamed to {@link AV.User.loginWithAuthData}
16669 */
16670 signUpOrlogInWithAuthData: function signUpOrlogInWithAuthData() {
16671 console.warn('DEPRECATED: User.signUpOrlogInWithAuthData 已废弃,请使用 User#loginWithAuthData 代替');
16672 return this.loginWithAuthData.apply(this, arguments);
16673 },
16674
16675
16676 /**
16677 * Signs up or logs in a user with a third party authData and unionId.
16678 * @since 3.7.0
16679 * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 }
16680 * @param {string} platform Available platform for sign up.
16681 * @param {string} unionId
16682 * @param {Object} [unionLoginOptions]
16683 * @param {string} [unionLoginOptions.unionIdPlatform = 'weixin'] unionId platform
16684 * @param {boolean} [unionLoginOptions.asMainAccount = false] If true, the unionId will be associated with the user.
16685 * @param {boolean} [unionLoginOptions.failOnNotExist] If true, the login request will fail when no user matches this authData exists.
16686 * @return {Promise<AV.User>} A promise that is fulfilled with the user when completed.
16687 * @example AV.User.loginWithAuthDataAndUnionId({
16688 * openid: 'abc123',
16689 * access_token: '123abc',
16690 * expires_in: 1382686496
16691 * }, 'weixin', 'union123', {
16692 * unionIdPlatform: 'weixin',
16693 * asMainAccount: true,
16694 * }).then(function(user) {
16695 * //Access user here
16696 * }).catch(function(error) {
16697 * //console.error("error: ", error);
16698 * });
16699 */
16700 loginWithAuthDataAndUnionId: function loginWithAuthDataAndUnionId(authData, platform, unionId, unionLoginOptions) {
16701 return this.loginWithAuthData(mergeUnionDataIntoAuthData()(authData, unionId, unionLoginOptions), platform, unionLoginOptions);
16702 },
16703
16704
16705 /**
16706 * @deprecated renamed to {@link AV.User.loginWithAuthDataAndUnionId}
16707 * @since 3.5.0
16708 */
16709 signUpOrlogInWithAuthDataAndUnionId: function signUpOrlogInWithAuthDataAndUnionId() {
16710 console.warn('DEPRECATED: User.signUpOrlogInWithAuthDataAndUnionId 已废弃,请使用 User#loginWithAuthDataAndUnionId 代替');
16711 return this.loginWithAuthDataAndUnionId.apply(this, arguments);
16712 },
16713
16714
16715 /**
16716 * Merge unionId into authInfo.
16717 * @since 4.6.0
16718 * @param {Object} authInfo
16719 * @param {String} unionId
16720 * @param {Object} [unionIdOption]
16721 * @param {Boolean} [unionIdOption.asMainAccount] If true, the unionId will be associated with the user.
16722 */
16723 mergeUnionId: function mergeUnionId(authInfo, unionId) {
16724 var _ref14 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
16725 _ref14$asMainAccount = _ref14.asMainAccount,
16726 asMainAccount = _ref14$asMainAccount === undefined ? false : _ref14$asMainAccount;
16727
16728 authInfo = JSON.parse((0, _stringify2.default)(authInfo));
16729 var _authInfo = authInfo,
16730 authData = _authInfo.authData,
16731 platform = _authInfo.platform;
16732
16733 authData.platform = platform;
16734 authData.main_account = asMainAccount;
16735 authData.unionid = unionId;
16736 return authInfo;
16737 },
16738
16739
16740 /**
16741 * 使用当前使用微信小程序的微信用户身份注册或登录,成功后用户的 session 会在设备上持久化保存,之后可以使用 AV.User.current() 获取当前登录用户。
16742 * 仅在微信小程序中可用。
16743 *
16744 * @deprecated please use {@link AV.User.loginWithMiniApp}
16745 * @since 2.0.0
16746 * @param {Object} [options]
16747 * @param {boolean} [options.preferUnionId] 当用户满足 {@link https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/union-id.html 获取 UnionId 的条件} 时,是否使用 UnionId 登录。(since 3.13.0)
16748 * @param {string} [options.unionIdPlatform = 'weixin'] (only take effect when preferUnionId) unionId platform
16749 * @param {boolean} [options.asMainAccount = true] (only take effect when preferUnionId) If true, the unionId will be associated with the user.
16750 * @param {boolean} [options.failOnNotExist] If true, the login request will fail when no user matches this authData exists. (since v3.7.0)
16751 * @return {Promise.<AV.User>}
16752 */
16753 loginWithWeapp: function loginWithWeapp() {
16754 var _this15 = this;
16755
16756 var _ref15 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
16757 _ref15$preferUnionId = _ref15.preferUnionId,
16758 preferUnionId = _ref15$preferUnionId === undefined ? false : _ref15$preferUnionId,
16759 _ref15$unionIdPlatfor = _ref15.unionIdPlatform,
16760 unionIdPlatform = _ref15$unionIdPlatfor === undefined ? 'weixin' : _ref15$unionIdPlatfor,
16761 _ref15$asMainAccount = _ref15.asMainAccount,
16762 asMainAccount = _ref15$asMainAccount === undefined ? true : _ref15$asMainAccount,
16763 _ref15$failOnNotExist = _ref15.failOnNotExist,
16764 failOnNotExist = _ref15$failOnNotExist === undefined ? false : _ref15$failOnNotExist;
16765
16766 var getAuthInfo = getAdapter('getAuthInfo');
16767 return getAuthInfo({
16768 preferUnionId: preferUnionId,
16769 asMainAccount: asMainAccount,
16770 platform: unionIdPlatform
16771 }).then(function (authInfo) {
16772 return _this15.loginWithMiniApp(authInfo, { failOnNotExist: failOnNotExist });
16773 });
16774 },
16775
16776
16777 /**
16778 * 使用当前使用微信小程序的微信用户身份注册或登录,
16779 * 仅在微信小程序中可用。
16780 *
16781 * @deprecated please use {@link AV.User.loginWithMiniApp}
16782 * @since 3.13.0
16783 * @param {Object} [unionLoginOptions]
16784 * @param {string} [unionLoginOptions.unionIdPlatform = 'weixin'] unionId platform
16785 * @param {boolean} [unionLoginOptions.asMainAccount = false] If true, the unionId will be associated with the user.
16786 * @param {boolean} [unionLoginOptions.failOnNotExist] If true, the login request will fail when no user matches this authData exists. * @return {Promise.<AV.User>}
16787 */
16788 loginWithWeappWithUnionId: function loginWithWeappWithUnionId(unionId) {
16789 var _this16 = this;
16790
16791 var _ref16 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
16792 _ref16$unionIdPlatfor = _ref16.unionIdPlatform,
16793 unionIdPlatform = _ref16$unionIdPlatfor === undefined ? 'weixin' : _ref16$unionIdPlatfor,
16794 _ref16$asMainAccount = _ref16.asMainAccount,
16795 asMainAccount = _ref16$asMainAccount === undefined ? false : _ref16$asMainAccount,
16796 _ref16$failOnNotExist = _ref16.failOnNotExist,
16797 failOnNotExist = _ref16$failOnNotExist === undefined ? false : _ref16$failOnNotExist;
16798
16799 var getAuthInfo = getAdapter('getAuthInfo');
16800 return getAuthInfo({ platform: unionIdPlatform }).then(function (authInfo) {
16801 authInfo = AV.User.mergeUnionId(authInfo, unionId, { asMainAccount: asMainAccount });
16802 return _this16.loginWithMiniApp(authInfo, { failOnNotExist: failOnNotExist });
16803 });
16804 },
16805
16806
16807 /**
16808 * 使用当前使用 QQ 小程序的 QQ 用户身份注册或登录,成功后用户的 session 会在设备上持久化保存,之后可以使用 AV.User.current() 获取当前登录用户。
16809 * 仅在 QQ 小程序中可用。
16810 *
16811 * @deprecated please use {@link AV.User.loginWithMiniApp}
16812 * @since 4.2.0
16813 * @param {Object} [options]
16814 * @param {boolean} [options.preferUnionId] 如果服务端在登录时获取到了用户的 UnionId,是否将 UnionId 保存在用户账号中。
16815 * @param {string} [options.unionIdPlatform = 'qq'] (only take effect when preferUnionId) unionId platform
16816 * @param {boolean} [options.asMainAccount = true] (only take effect when preferUnionId) If true, the unionId will be associated with the user.
16817 * @param {boolean} [options.failOnNotExist] If true, the login request will fail when no user matches this authData exists. (since v3.7.0)
16818 * @return {Promise.<AV.User>}
16819 */
16820 loginWithQQApp: function loginWithQQApp() {
16821 var _this17 = this;
16822
16823 var _ref17 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
16824 _ref17$preferUnionId = _ref17.preferUnionId,
16825 preferUnionId = _ref17$preferUnionId === undefined ? false : _ref17$preferUnionId,
16826 _ref17$unionIdPlatfor = _ref17.unionIdPlatform,
16827 unionIdPlatform = _ref17$unionIdPlatfor === undefined ? 'qq' : _ref17$unionIdPlatfor,
16828 _ref17$asMainAccount = _ref17.asMainAccount,
16829 asMainAccount = _ref17$asMainAccount === undefined ? true : _ref17$asMainAccount,
16830 _ref17$failOnNotExist = _ref17.failOnNotExist,
16831 failOnNotExist = _ref17$failOnNotExist === undefined ? false : _ref17$failOnNotExist;
16832
16833 var getAuthInfo = getAdapter('getAuthInfo');
16834 return getAuthInfo({
16835 preferUnionId: preferUnionId,
16836 asMainAccount: asMainAccount,
16837 platform: unionIdPlatform
16838 }).then(function (authInfo) {
16839 authInfo.provider = PLATFORM_QQAPP;
16840 return _this17.loginWithMiniApp(authInfo, { failOnNotExist: failOnNotExist });
16841 });
16842 },
16843
16844
16845 /**
16846 * 使用当前使用 QQ 小程序的 QQ 用户身份注册或登录,
16847 * 仅在 QQ 小程序中可用。
16848 *
16849 * @deprecated please use {@link AV.User.loginWithMiniApp}
16850 * @since 4.2.0
16851 * @param {Object} [unionLoginOptions]
16852 * @param {string} [unionLoginOptions.unionIdPlatform = 'qq'] unionId platform
16853 * @param {boolean} [unionLoginOptions.asMainAccount = false] If true, the unionId will be associated with the user.
16854 * @param {boolean} [unionLoginOptions.failOnNotExist] If true, the login request will fail when no user matches this authData exists.
16855 * @return {Promise.<AV.User>}
16856 */
16857 loginWithQQAppWithUnionId: function loginWithQQAppWithUnionId(unionId) {
16858 var _this18 = this;
16859
16860 var _ref18 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
16861 _ref18$unionIdPlatfor = _ref18.unionIdPlatform,
16862 unionIdPlatform = _ref18$unionIdPlatfor === undefined ? 'qq' : _ref18$unionIdPlatfor,
16863 _ref18$asMainAccount = _ref18.asMainAccount,
16864 asMainAccount = _ref18$asMainAccount === undefined ? false : _ref18$asMainAccount,
16865 _ref18$failOnNotExist = _ref18.failOnNotExist,
16866 failOnNotExist = _ref18$failOnNotExist === undefined ? false : _ref18$failOnNotExist;
16867
16868 var getAuthInfo = getAdapter('getAuthInfo');
16869 return getAuthInfo({ platform: unionIdPlatform }).then(function (authInfo) {
16870 authInfo = AV.User.mergeUnionId(authInfo, unionId, { asMainAccount: asMainAccount });
16871 authInfo.provider = PLATFORM_QQAPP;
16872 return _this18.loginWithMiniApp(authInfo, { failOnNotExist: failOnNotExist });
16873 });
16874 },
16875
16876
16877 /**
16878 * Register or login using the identity of the current mini-app.
16879 * @param {Object} authInfo
16880 * @param {Object} [option]
16881 * @param {Boolean} [option.failOnNotExist] If true, the login request will fail when no user matches this authInfo.authData exists.
16882 */
16883 loginWithMiniApp: function loginWithMiniApp(authInfo, option) {
16884 var _this19 = this;
16885
16886 if (authInfo === undefined) {
16887 var getAuthInfo = getAdapter('getAuthInfo');
16888 return getAuthInfo().then(function (authInfo) {
16889 return _this19.loginWithAuthData(authInfo.authData, authInfo.provider, option);
16890 });
16891 }
16892 return this.loginWithAuthData(authInfo.authData, authInfo.provider, option);
16893 },
16894
16895
16896 /**
16897 * Only use for DI in tests to produce deterministic IDs.
16898 */
16899 _genId: function _genId() {
16900 return uuid();
16901 },
16902
16903
16904 /**
16905 * Creates an anonymous user.
16906 *
16907 * @since 3.9.0
16908 * @return {Promise.<AV.User>}
16909 */
16910 loginAnonymously: function loginAnonymously() {
16911 return this.loginWithAuthData({
16912 id: AV.User._genId()
16913 }, 'anonymous');
16914 },
16915 associateWithAuthData: function associateWithAuthData(userObj, platform, authData) {
16916 console.warn('DEPRECATED: User.associateWithAuthData 已废弃,请使用 User#associateWithAuthData 代替');
16917 return userObj._linkWith(platform, authData);
16918 },
16919
16920 /**
16921 * Logs out the currently logged in user session. This will remove the
16922 * session from disk, log out of linked services, and future calls to
16923 * <code>current</code> will return <code>null</code>.
16924 * @return {Promise}
16925 */
16926 logOut: function logOut() {
16927 if (AV._config.disableCurrentUser) {
16928 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');
16929 return _promise2.default.resolve(null);
16930 }
16931
16932 if (AV.User._currentUser !== null) {
16933 AV.User._currentUser._logOutWithAll();
16934 AV.User._currentUser._isCurrentUser = false;
16935 }
16936 AV.User._currentUserMatchesDisk = true;
16937 AV.User._currentUser = null;
16938 return AV.localStorage.removeItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY)).then(function () {
16939 return AV._refreshSubscriptionId();
16940 });
16941 },
16942
16943 /**
16944 *Create a follower query for special user to query the user's followers.
16945 * @param {String} userObjectId The user object id.
16946 * @return {AV.FriendShipQuery}
16947 * @since 0.3.0
16948 */
16949 followerQuery: function followerQuery(userObjectId) {
16950 if (!userObjectId || !_.isString(userObjectId)) {
16951 throw new Error('Invalid user object id.');
16952 }
16953 var query = new AV.FriendShipQuery('_Follower');
16954 query._friendshipTag = 'follower';
16955 query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId));
16956 return query;
16957 },
16958
16959 /**
16960 *Create a followee query for special user to query the user's followees.
16961 * @param {String} userObjectId The user object id.
16962 * @return {AV.FriendShipQuery}
16963 * @since 0.3.0
16964 */
16965 followeeQuery: function followeeQuery(userObjectId) {
16966 if (!userObjectId || !_.isString(userObjectId)) {
16967 throw new Error('Invalid user object id.');
16968 }
16969 var query = new AV.FriendShipQuery('_Followee');
16970 query._friendshipTag = 'followee';
16971 query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId));
16972 return query;
16973 },
16974
16975 /**
16976 * Requests a password reset email to be sent to the specified email address
16977 * associated with the user account. This email allows the user to securely
16978 * reset their password on the AV site.
16979 *
16980 * @param {String} email The email address associated with the user that
16981 * forgot their password.
16982 * @return {Promise}
16983 */
16984 requestPasswordReset: function requestPasswordReset(email) {
16985 var json = { email: email };
16986 var request = AVRequest('requestPasswordReset', null, null, 'POST', json);
16987 return request;
16988 },
16989
16990 /**
16991 * Requests a verify email to be sent to the specified email address
16992 * associated with the user account. This email allows the user to securely
16993 * verify their email address on the AV site.
16994 *
16995 * @param {String} email The email address associated with the user that
16996 * doesn't verify their email address.
16997 * @return {Promise}
16998 */
16999 requestEmailVerify: function requestEmailVerify(email) {
17000 var json = { email: email };
17001 var request = AVRequest('requestEmailVerify', null, null, 'POST', json);
17002 return request;
17003 },
17004
17005 /**
17006 * Requests a verify sms code to be sent to the specified mobile phone
17007 * number associated with the user account. This sms code allows the user to
17008 * verify their mobile phone number by calling AV.User.verifyMobilePhone
17009 *
17010 * @param {String} mobilePhoneNumber The mobile phone number associated with the
17011 * user that doesn't verify their mobile phone number.
17012 * @param {SMSAuthOptions} [options]
17013 * @return {Promise}
17014 */
17015 requestMobilePhoneVerify: function requestMobilePhoneVerify(mobilePhoneNumber) {
17016 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
17017
17018 var data = {
17019 mobilePhoneNumber: mobilePhoneNumber
17020 };
17021 if (options.validateToken) {
17022 data.validate_token = options.validateToken;
17023 }
17024 var request = AVRequest('requestMobilePhoneVerify', null, null, 'POST', data, options);
17025 return request;
17026 },
17027
17028 /**
17029 * Requests a reset password sms code to be sent to the specified mobile phone
17030 * number associated with the user account. This sms code allows the user to
17031 * reset their account's password by calling AV.User.resetPasswordBySmsCode
17032 *
17033 * @param {String} mobilePhoneNumber The mobile phone number associated with the
17034 * user that doesn't verify their mobile phone number.
17035 * @param {SMSAuthOptions} [options]
17036 * @return {Promise}
17037 */
17038 requestPasswordResetBySmsCode: function requestPasswordResetBySmsCode(mobilePhoneNumber) {
17039 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
17040
17041 var data = {
17042 mobilePhoneNumber: mobilePhoneNumber
17043 };
17044 if (options.validateToken) {
17045 data.validate_token = options.validateToken;
17046 }
17047 var request = AVRequest('requestPasswordResetBySmsCode', null, null, 'POST', data, options);
17048 return request;
17049 },
17050
17051 /**
17052 * Requests a change mobile phone number sms code to be sent to the mobilePhoneNumber.
17053 * This sms code allows current user to reset it's mobilePhoneNumber by
17054 * calling {@link AV.User.changePhoneNumber}
17055 * @since 4.7.0
17056 * @param {String} mobilePhoneNumber
17057 * @param {Number} [ttl] ttl of sms code (default is 6 minutes)
17058 * @param {SMSAuthOptions} [options]
17059 * @return {Promise}
17060 */
17061 requestChangePhoneNumber: function requestChangePhoneNumber(mobilePhoneNumber, ttl, options) {
17062 var data = { mobilePhoneNumber: mobilePhoneNumber };
17063 if (ttl) {
17064 data.ttl = options.ttl;
17065 }
17066 if (options && options.validateToken) {
17067 data.validate_token = options.validateToken;
17068 }
17069 return AVRequest('requestChangePhoneNumber', null, null, 'POST', data, options);
17070 },
17071
17072
17073 /**
17074 * Makes a call to reset user's account mobilePhoneNumber by sms code.
17075 * The sms code is sent by {@link AV.User.requestChangePhoneNumber}
17076 * @since 4.7.0
17077 * @param {String} mobilePhoneNumber
17078 * @param {String} code The sms code.
17079 * @return {Promise}
17080 */
17081 changePhoneNumber: function changePhoneNumber(mobilePhoneNumber, code) {
17082 var data = { mobilePhoneNumber: mobilePhoneNumber, code: code };
17083 return AVRequest('changePhoneNumber', null, null, 'POST', data);
17084 },
17085
17086
17087 /**
17088 * Makes a call to reset user's account password by sms code and new password.
17089 * The sms code is sent by AV.User.requestPasswordResetBySmsCode.
17090 * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode
17091 * @param {String} password The new password.
17092 * @return {Promise} A promise that will be resolved with the result
17093 * of the function.
17094 */
17095 resetPasswordBySmsCode: function resetPasswordBySmsCode(code, password) {
17096 var json = { password: password };
17097 var request = AVRequest('resetPasswordBySmsCode', null, code, 'PUT', json);
17098 return request;
17099 },
17100
17101 /**
17102 * Makes a call to verify sms code that sent by AV.User.Cloud.requestSmsCode
17103 * If verify successfully,the user mobilePhoneVerified attribute will be true.
17104 * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode
17105 * @return {Promise} A promise that will be resolved with the result
17106 * of the function.
17107 */
17108 verifyMobilePhone: function verifyMobilePhone(code) {
17109 var request = AVRequest('verifyMobilePhone', null, code, 'POST', null);
17110 return request;
17111 },
17112
17113 /**
17114 * Requests a logIn sms code to be sent to the specified mobile phone
17115 * number associated with the user account. This sms code allows the user to
17116 * login by AV.User.logInWithMobilePhoneSmsCode function.
17117 *
17118 * @param {String} mobilePhoneNumber The mobile phone number associated with the
17119 * user that want to login by AV.User.logInWithMobilePhoneSmsCode
17120 * @param {SMSAuthOptions} [options]
17121 * @return {Promise}
17122 */
17123 requestLoginSmsCode: function requestLoginSmsCode(mobilePhoneNumber) {
17124 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
17125
17126 var data = {
17127 mobilePhoneNumber: mobilePhoneNumber
17128 };
17129 if (options.validateToken) {
17130 data.validate_token = options.validateToken;
17131 }
17132 var request = AVRequest('requestLoginSmsCode', null, null, 'POST', data, options);
17133 return request;
17134 },
17135
17136 /**
17137 * Retrieves the currently logged in AVUser with a valid session,
17138 * either from memory or localStorage, if necessary.
17139 * @return {Promise.<AV.User>} resolved with the currently logged in AV.User.
17140 */
17141 currentAsync: function currentAsync() {
17142 if (AV._config.disableCurrentUser) {
17143 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');
17144 return _promise2.default.resolve(null);
17145 }
17146
17147 if (AV.User._currentUser) {
17148 return _promise2.default.resolve(AV.User._currentUser);
17149 }
17150
17151 if (AV.User._currentUserMatchesDisk) {
17152 return _promise2.default.resolve(AV.User._currentUser);
17153 }
17154
17155 return AV.localStorage.getItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY)).then(function (userData) {
17156 if (!userData) {
17157 return null;
17158 }
17159
17160 // Load the user from local storage.
17161 AV.User._currentUserMatchesDisk = true;
17162
17163 AV.User._currentUser = AV.Object._create('_User');
17164 AV.User._currentUser._isCurrentUser = true;
17165
17166 var json = JSON.parse(userData);
17167 AV.User._currentUser.id = json._id;
17168 delete json._id;
17169 AV.User._currentUser._sessionToken = json._sessionToken;
17170 delete json._sessionToken;
17171 AV.User._currentUser._finishFetch(json);
17172 //AV.User._currentUser.set(json);
17173
17174 AV.User._currentUser._synchronizeAllAuthData();
17175 AV.User._currentUser._refreshCache();
17176 AV.User._currentUser._opSetQueue = [{}];
17177 return AV.User._currentUser;
17178 });
17179 },
17180
17181 /**
17182 * Retrieves the currently logged in AVUser with a valid session,
17183 * either from memory or localStorage, if necessary.
17184 * @return {AV.User} The currently logged in AV.User.
17185 */
17186 current: function current() {
17187 if (AV._config.disableCurrentUser) {
17188 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');
17189 return null;
17190 }
17191
17192 if (AV.localStorage.async) {
17193 var error = new Error('Synchronous API User.current() is not available in this runtime. Use User.currentAsync() instead.');
17194 error.code = 'SYNC_API_NOT_AVAILABLE';
17195 throw error;
17196 }
17197
17198 if (AV.User._currentUser) {
17199 return AV.User._currentUser;
17200 }
17201
17202 if (AV.User._currentUserMatchesDisk) {
17203 return AV.User._currentUser;
17204 }
17205
17206 // Load the user from local storage.
17207 AV.User._currentUserMatchesDisk = true;
17208
17209 var userData = AV.localStorage.getItem(AV._getAVPath(AV.User._CURRENT_USER_KEY));
17210 if (!userData) {
17211 return null;
17212 }
17213 AV.User._currentUser = AV.Object._create('_User');
17214 AV.User._currentUser._isCurrentUser = true;
17215
17216 var json = JSON.parse(userData);
17217 AV.User._currentUser.id = json._id;
17218 delete json._id;
17219 AV.User._currentUser._sessionToken = json._sessionToken;
17220 delete json._sessionToken;
17221 AV.User._currentUser._finishFetch(json);
17222 //AV.User._currentUser.set(json);
17223
17224 AV.User._currentUser._synchronizeAllAuthData();
17225 AV.User._currentUser._refreshCache();
17226 AV.User._currentUser._opSetQueue = [{}];
17227 return AV.User._currentUser;
17228 },
17229
17230 /**
17231 * Persists a user as currentUser to localStorage, and into the singleton.
17232 * @private
17233 */
17234 _saveCurrentUser: function _saveCurrentUser(user) {
17235 var promise;
17236 if (AV.User._currentUser !== user) {
17237 promise = AV.User.logOut();
17238 } else {
17239 promise = _promise2.default.resolve();
17240 }
17241 return promise.then(function () {
17242 user._isCurrentUser = true;
17243 AV.User._currentUser = user;
17244
17245 var json = user._toFullJSON();
17246 json._id = user.id;
17247 json._sessionToken = user._sessionToken;
17248 return AV.localStorage.setItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY), (0, _stringify2.default)(json)).then(function () {
17249 AV.User._currentUserMatchesDisk = true;
17250 return AV._refreshSubscriptionId();
17251 });
17252 });
17253 },
17254
17255 _registerAuthenticationProvider: function _registerAuthenticationProvider(provider) {
17256 AV.User._authProviders[provider.getAuthType()] = provider;
17257 // Synchronize the current user with the auth provider.
17258 if (!AV._config.disableCurrentUser && AV.User.current()) {
17259 AV.User.current()._synchronizeAuthData(provider.getAuthType());
17260 }
17261 },
17262
17263 _logInWith: function _logInWith(provider, authData, options) {
17264 var user = AV.Object._create('_User');
17265 return user._linkWith(provider, authData, options);
17266 }
17267 });
17268};
17269
17270/***/ }),
17271/* 354 */
17272/***/ (function(module, exports, __webpack_require__) {
17273
17274"use strict";
17275
17276
17277exports.__esModule = true;
17278
17279var _defineProperty = __webpack_require__(71);
17280
17281var _defineProperty2 = _interopRequireDefault(_defineProperty);
17282
17283function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17284
17285exports.default = function (obj, key, value) {
17286 if (key in obj) {
17287 (0, _defineProperty2.default)(obj, key, {
17288 value: value,
17289 enumerable: true,
17290 configurable: true,
17291 writable: true
17292 });
17293 } else {
17294 obj[key] = value;
17295 }
17296
17297 return obj;
17298};
17299
17300/***/ }),
17301/* 355 */
17302/***/ (function(module, exports, __webpack_require__) {
17303
17304"use strict";
17305
17306
17307var _stringify = __webpack_require__(21);
17308
17309var _stringify2 = _interopRequireDefault(_stringify);
17310
17311var _promise = __webpack_require__(3);
17312
17313var _promise2 = _interopRequireDefault(_promise);
17314
17315function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17316
17317var _ = __webpack_require__(0);
17318var debug = __webpack_require__(33)('leancloud:query');
17319var AVError = __webpack_require__(34);
17320
17321var _require = __webpack_require__(14),
17322 _request = _require._request,
17323 request = _require.request;
17324
17325var _require2 = __webpack_require__(19),
17326 ensureArray = _require2.ensureArray,
17327 transformFetchOptions = _require2.transformFetchOptions,
17328 continueWhile = _require2.continueWhile;
17329
17330var requires = function requires(value, message) {
17331 if (value === undefined) {
17332 throw new Error(message);
17333 }
17334};
17335
17336// AV.Query is a way to create a list of AV.Objects.
17337module.exports = function (AV) {
17338 /**
17339 * Creates a new AV.Query for the given AV.Object subclass.
17340 * @param {Class|String} objectClass An instance of a subclass of AV.Object, or a AV className string.
17341 * @class
17342 *
17343 * <p>AV.Query defines a query that is used to fetch AV.Objects. The
17344 * most common use case is finding all objects that match a query through the
17345 * <code>find</code> method. For example, this sample code fetches all objects
17346 * of class <code>MyClass</code>. It calls a different function depending on
17347 * whether the fetch succeeded or not.
17348 *
17349 * <pre>
17350 * var query = new AV.Query(MyClass);
17351 * query.find().then(function(results) {
17352 * // results is an array of AV.Object.
17353 * }, function(error) {
17354 * // error is an instance of AVError.
17355 * });</pre></p>
17356 *
17357 * <p>An AV.Query can also be used to retrieve a single object whose id is
17358 * known, through the get method. For example, this sample code fetches an
17359 * object of class <code>MyClass</code> and id <code>myId</code>. It calls a
17360 * different function depending on whether the fetch succeeded or not.
17361 *
17362 * <pre>
17363 * var query = new AV.Query(MyClass);
17364 * query.get(myId).then(function(object) {
17365 * // object is an instance of AV.Object.
17366 * }, function(error) {
17367 * // error is an instance of AVError.
17368 * });</pre></p>
17369 *
17370 * <p>An AV.Query can also be used to count the number of objects that match
17371 * the query without retrieving all of those objects. For example, this
17372 * sample code counts the number of objects of the class <code>MyClass</code>
17373 * <pre>
17374 * var query = new AV.Query(MyClass);
17375 * query.count().then(function(number) {
17376 * // There are number instances of MyClass.
17377 * }, function(error) {
17378 * // error is an instance of AVError.
17379 * });</pre></p>
17380 */
17381 AV.Query = function (objectClass) {
17382 if (_.isString(objectClass)) {
17383 objectClass = AV.Object._getSubclass(objectClass);
17384 }
17385
17386 this.objectClass = objectClass;
17387
17388 this.className = objectClass.prototype.className;
17389
17390 this._where = {};
17391 this._include = [];
17392 this._select = [];
17393 this._limit = -1; // negative limit means, do not send a limit
17394 this._skip = 0;
17395 this._defaultParams = {};
17396 };
17397
17398 /**
17399 * Constructs a AV.Query that is the OR of the passed in queries. For
17400 * example:
17401 * <pre>var compoundQuery = AV.Query.or(query1, query2, query3);</pre>
17402 *
17403 * will create a compoundQuery that is an or of the query1, query2, and
17404 * query3.
17405 * @param {...AV.Query} var_args The list of queries to OR.
17406 * @return {AV.Query} The query that is the OR of the passed in queries.
17407 */
17408 AV.Query.or = function () {
17409 var queries = _.toArray(arguments);
17410 var className = null;
17411 AV._arrayEach(queries, function (q) {
17412 if (_.isNull(className)) {
17413 className = q.className;
17414 }
17415
17416 if (className !== q.className) {
17417 throw new Error('All queries must be for the same class');
17418 }
17419 });
17420 var query = new AV.Query(className);
17421 query._orQuery(queries);
17422 return query;
17423 };
17424
17425 /**
17426 * Constructs a AV.Query that is the AND of the passed in queries. For
17427 * example:
17428 * <pre>var compoundQuery = AV.Query.and(query1, query2, query3);</pre>
17429 *
17430 * will create a compoundQuery that is an 'and' of the query1, query2, and
17431 * query3.
17432 * @param {...AV.Query} var_args The list of queries to AND.
17433 * @return {AV.Query} The query that is the AND of the passed in queries.
17434 */
17435 AV.Query.and = function () {
17436 var queries = _.toArray(arguments);
17437 var className = null;
17438 AV._arrayEach(queries, function (q) {
17439 if (_.isNull(className)) {
17440 className = q.className;
17441 }
17442
17443 if (className !== q.className) {
17444 throw new Error('All queries must be for the same class');
17445 }
17446 });
17447 var query = new AV.Query(className);
17448 query._andQuery(queries);
17449 return query;
17450 };
17451
17452 /**
17453 * Retrieves a list of AVObjects that satisfy the CQL.
17454 * CQL syntax please see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}.
17455 *
17456 * @param {String} cql A CQL string, see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}.
17457 * @param {Array} pvalues An array contains placeholder values.
17458 * @param {AuthOptions} options
17459 * @return {Promise} A promise that is resolved with the results when
17460 * the query completes.
17461 */
17462 AV.Query.doCloudQuery = function (cql, pvalues, options) {
17463 var params = { cql: cql };
17464 if (_.isArray(pvalues)) {
17465 params.pvalues = pvalues;
17466 } else {
17467 options = pvalues;
17468 }
17469
17470 var request = _request('cloudQuery', null, null, 'GET', params, options);
17471 return request.then(function (response) {
17472 //query to process results.
17473 var query = new AV.Query(response.className);
17474 var results = _.map(response.results, function (json) {
17475 var obj = query._newObject(response);
17476 if (obj._finishFetch) {
17477 obj._finishFetch(query._processResult(json), true);
17478 }
17479 return obj;
17480 });
17481 return {
17482 results: results,
17483 count: response.count,
17484 className: response.className
17485 };
17486 });
17487 };
17488
17489 /**
17490 * Return a query with conditions from json.
17491 * This can be useful to send a query from server side to client side.
17492 * @since 4.0.0
17493 * @param {Object} json from {@link AV.Query#toJSON}
17494 * @return {AV.Query}
17495 */
17496 AV.Query.fromJSON = function (_ref) {
17497 var className = _ref.className,
17498 where = _ref.where,
17499 include = _ref.include,
17500 select = _ref.select,
17501 includeACL = _ref.includeACL,
17502 limit = _ref.limit,
17503 skip = _ref.skip,
17504 order = _ref.order;
17505
17506 if (typeof className !== 'string') {
17507 throw new TypeError('Invalid Query JSON, className must be a String.');
17508 }
17509 var query = new AV.Query(className);
17510 _.extend(query, {
17511 _where: where,
17512 _include: include,
17513 _select: select,
17514 _includeACL: includeACL,
17515 _limit: limit,
17516 _skip: skip,
17517 _order: order
17518 });
17519 return query;
17520 };
17521
17522 AV.Query._extend = AV._extend;
17523
17524 _.extend(AV.Query.prototype,
17525 /** @lends AV.Query.prototype */{
17526 //hook to iterate result. Added by dennis<xzhuang@avoscloud.com>.
17527 _processResult: function _processResult(obj) {
17528 return obj;
17529 },
17530
17531 /**
17532 * Constructs an AV.Object whose id is already known by fetching data from
17533 * the server.
17534 *
17535 * @param {String} objectId The id of the object to be fetched.
17536 * @param {AuthOptions} options
17537 * @return {Promise.<AV.Object>}
17538 */
17539 get: function get(objectId, options) {
17540 if (!_.isString(objectId)) {
17541 throw new Error('objectId must be a string');
17542 }
17543 if (objectId === '') {
17544 return _promise2.default.reject(new AVError(AVError.OBJECT_NOT_FOUND, 'Object not found.'));
17545 }
17546
17547 var obj = this._newObject();
17548 obj.id = objectId;
17549
17550 var queryJSON = this._getParams();
17551 var fetchOptions = {};
17552
17553 if (queryJSON.keys) fetchOptions.keys = queryJSON.keys;
17554 if (queryJSON.include) fetchOptions.include = queryJSON.include;
17555 if (queryJSON.includeACL) fetchOptions.includeACL = queryJSON.includeACL;
17556
17557 return _request('classes', this.className, objectId, 'GET', transformFetchOptions(fetchOptions), options).then(function (response) {
17558 if (_.isEmpty(response)) throw new AVError(AVError.OBJECT_NOT_FOUND, 'Object not found.');
17559 obj._finishFetch(obj.parse(response), true);
17560 return obj;
17561 });
17562 },
17563
17564 /**
17565 * Returns a JSON representation of this query.
17566 * @return {Object}
17567 */
17568 toJSON: function toJSON() {
17569 var className = this.className,
17570 where = this._where,
17571 include = this._include,
17572 select = this._select,
17573 includeACL = this._includeACL,
17574 limit = this._limit,
17575 skip = this._skip,
17576 order = this._order;
17577
17578 return {
17579 className: className,
17580 where: where,
17581 include: include,
17582 select: select,
17583 includeACL: includeACL,
17584 limit: limit,
17585 skip: skip,
17586 order: order
17587 };
17588 },
17589
17590
17591 _getParams: function _getParams() {
17592 var params = _.extend({}, this._defaultParams, {
17593 where: this._where
17594 });
17595
17596 if (this._include.length > 0) {
17597 params.include = this._include.join(',');
17598 }
17599 if (this._select.length > 0) {
17600 params.keys = this._select.join(',');
17601 }
17602 if (this._includeACL !== undefined) {
17603 params.returnACL = this._includeACL;
17604 }
17605 if (this._limit >= 0) {
17606 params.limit = this._limit;
17607 }
17608 if (this._skip > 0) {
17609 params.skip = this._skip;
17610 }
17611 if (this._order !== undefined) {
17612 params.order = this._order;
17613 }
17614
17615 return params;
17616 },
17617
17618 _newObject: function _newObject(response) {
17619 var obj;
17620 if (response && response.className) {
17621 obj = new AV.Object(response.className);
17622 } else {
17623 obj = new this.objectClass();
17624 }
17625 return obj;
17626 },
17627 _createRequest: function _createRequest() {
17628 var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this._getParams();
17629 var options = arguments[1];
17630 var path = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '/classes/' + this.className;
17631
17632 if (encodeURIComponent((0, _stringify2.default)(params)).length > 2000) {
17633 var body = {
17634 requests: [{
17635 method: 'GET',
17636 path: '/1.1' + path,
17637 params: params
17638 }]
17639 };
17640 return request({
17641 path: '/batch',
17642 method: 'POST',
17643 data: body,
17644 authOptions: options
17645 }).then(function (response) {
17646 var result = response[0];
17647 if (result.success) {
17648 return result.success;
17649 }
17650 var error = new Error(result.error.error || 'Unknown batch error');
17651 error.code = result.error.code;
17652 throw error;
17653 });
17654 }
17655 return request({
17656 method: 'GET',
17657 path: path,
17658 query: params,
17659 authOptions: options
17660 });
17661 },
17662 _parseResponse: function _parseResponse(response) {
17663 var _this = this;
17664
17665 return _.map(response.results, function (json) {
17666 var obj = _this._newObject(response);
17667 if (obj._finishFetch) {
17668 obj._finishFetch(_this._processResult(json), true);
17669 }
17670 return obj;
17671 });
17672 },
17673
17674
17675 /**
17676 * Retrieves a list of AVObjects that satisfy this query.
17677 *
17678 * @param {AuthOptions} options
17679 * @return {Promise} A promise that is resolved with the results when
17680 * the query completes.
17681 */
17682 find: function find(options) {
17683 var request = this._createRequest(undefined, options);
17684 return request.then(this._parseResponse.bind(this));
17685 },
17686
17687
17688 /**
17689 * Retrieves both AVObjects and total count.
17690 *
17691 * @since 4.12.0
17692 * @param {AuthOptions} options
17693 * @return {Promise} A tuple contains results and count.
17694 */
17695 findAndCount: function findAndCount(options) {
17696 var _this2 = this;
17697
17698 var params = this._getParams();
17699 params.count = 1;
17700 var request = this._createRequest(params, options);
17701
17702 return request.then(function (response) {
17703 return [_this2._parseResponse(response), response.count];
17704 });
17705 },
17706
17707
17708 /**
17709 * scan a Query. masterKey required.
17710 *
17711 * @since 2.1.0
17712 * @param {object} [options]
17713 * @param {string} [options.orderedBy] specify the key to sort
17714 * @param {number} [options.batchSize] specify the batch size for each request
17715 * @param {AuthOptions} [authOptions]
17716 * @return {AsyncIterator.<AV.Object>}
17717 * @example const testIterator = {
17718 * [Symbol.asyncIterator]() {
17719 * return new Query('Test').scan(undefined, { useMasterKey: true });
17720 * },
17721 * };
17722 * for await (const test of testIterator) {
17723 * console.log(test.id);
17724 * }
17725 */
17726 scan: function scan() {
17727 var _this3 = this;
17728
17729 var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
17730 orderedBy = _ref2.orderedBy,
17731 batchSize = _ref2.batchSize;
17732
17733 var authOptions = arguments[1];
17734
17735 var condition = this._getParams();
17736 debug('scan %O', condition);
17737 if (condition.order) {
17738 console.warn('The order of the query is ignored for Query#scan. Checkout the orderedBy option of Query#scan.');
17739 delete condition.order;
17740 }
17741 if (condition.skip) {
17742 console.warn('The skip option of the query is ignored for Query#scan.');
17743 delete condition.skip;
17744 }
17745 if (condition.limit) {
17746 console.warn('The limit option of the query is ignored for Query#scan.');
17747 delete condition.limit;
17748 }
17749 if (orderedBy) condition.scan_key = orderedBy;
17750 if (batchSize) condition.limit = batchSize;
17751 var promise = _promise2.default.resolve([]);
17752 var cursor = void 0;
17753 var endReached = false;
17754 return {
17755 next: function next() {
17756 promise = promise.then(function (remainResults) {
17757 if (endReached) return [];
17758 if (remainResults.length > 1) return remainResults;
17759 // no cursor means we have reached the end
17760 // except for the first time
17761 if (!cursor && remainResults.length !== 0) {
17762 endReached = true;
17763 return remainResults;
17764 }
17765 // when only 1 item left in queue
17766 // start the next request to see if it is the last one
17767 return _request('scan/classes', _this3.className, null, 'GET', cursor ? _.extend({}, condition, { cursor: cursor }) : condition, authOptions).then(function (response) {
17768 cursor = response.cursor;
17769 return _this3._parseResponse(response);
17770 }).then(function (results) {
17771 if (!results.length) endReached = true;
17772 return remainResults.concat(results);
17773 });
17774 });
17775 return promise.then(function (remainResults) {
17776 return remainResults.shift();
17777 }).then(function (result) {
17778 return {
17779 value: result,
17780 done: result === undefined
17781 };
17782 });
17783 }
17784 };
17785 },
17786
17787
17788 /**
17789 * Delete objects retrieved by this query.
17790 * @param {AuthOptions} options
17791 * @return {Promise} A promise that is fulfilled when the save
17792 * completes.
17793 */
17794 destroyAll: function destroyAll(options) {
17795 var self = this;
17796 return self.find(options).then(function (objects) {
17797 return AV.Object.destroyAll(objects, options);
17798 });
17799 },
17800
17801 /**
17802 * Counts the number of objects that match this query.
17803 *
17804 * @param {AuthOptions} options
17805 * @return {Promise} A promise that is resolved with the count when
17806 * the query completes.
17807 */
17808 count: function count(options) {
17809 var params = this._getParams();
17810 params.limit = 0;
17811 params.count = 1;
17812 var request = this._createRequest(params, options);
17813
17814 return request.then(function (response) {
17815 return response.count;
17816 });
17817 },
17818
17819 /**
17820 * Retrieves at most one AV.Object that satisfies this query.
17821 *
17822 * @param {AuthOptions} options
17823 * @return {Promise} A promise that is resolved with the object when
17824 * the query completes.
17825 */
17826 first: function first(options) {
17827 var self = this;
17828
17829 var params = this._getParams();
17830 params.limit = 1;
17831 var request = this._createRequest(params, options);
17832
17833 return request.then(function (response) {
17834 return _.map(response.results, function (json) {
17835 var obj = self._newObject();
17836 if (obj._finishFetch) {
17837 obj._finishFetch(self._processResult(json), true);
17838 }
17839 return obj;
17840 })[0];
17841 });
17842 },
17843
17844 /**
17845 * Sets the number of results to skip before returning any results.
17846 * This is useful for pagination.
17847 * Default is to skip zero results.
17848 * @param {Number} n the number of results to skip.
17849 * @return {AV.Query} Returns the query, so you can chain this call.
17850 */
17851 skip: function skip(n) {
17852 requires(n, 'undefined is not a valid skip value');
17853 this._skip = n;
17854 return this;
17855 },
17856
17857 /**
17858 * Sets the limit of the number of results to return. The default limit is
17859 * 100, with a maximum of 1000 results being returned at a time.
17860 * @param {Number} n the number of results to limit to.
17861 * @return {AV.Query} Returns the query, so you can chain this call.
17862 */
17863 limit: function limit(n) {
17864 requires(n, 'undefined is not a valid limit value');
17865 this._limit = n;
17866 return this;
17867 },
17868
17869 /**
17870 * Add a constraint to the query that requires a particular key's value to
17871 * be equal to the provided value.
17872 * @param {String} key The key to check.
17873 * @param value The value that the AV.Object must contain.
17874 * @return {AV.Query} Returns the query, so you can chain this call.
17875 */
17876 equalTo: function equalTo(key, value) {
17877 requires(key, 'undefined is not a valid key');
17878 requires(value, 'undefined is not a valid value');
17879 this._where[key] = AV._encode(value);
17880 return this;
17881 },
17882
17883 /**
17884 * Helper for condition queries
17885 * @private
17886 */
17887 _addCondition: function _addCondition(key, condition, value) {
17888 requires(key, 'undefined is not a valid condition key');
17889 requires(condition, 'undefined is not a valid condition');
17890 requires(value, 'undefined is not a valid condition value');
17891
17892 // Check if we already have a condition
17893 if (!this._where[key]) {
17894 this._where[key] = {};
17895 }
17896 this._where[key][condition] = AV._encode(value);
17897 return this;
17898 },
17899
17900 /**
17901 * Add a constraint to the query that requires a particular
17902 * <strong>array</strong> key's length to be equal to the provided value.
17903 * @param {String} key The array key to check.
17904 * @param value The length value.
17905 * @return {AV.Query} Returns the query, so you can chain this call.
17906 */
17907 sizeEqualTo: function sizeEqualTo(key, value) {
17908 this._addCondition(key, '$size', value);
17909 return this;
17910 },
17911
17912 /**
17913 * Add a constraint to the query that requires a particular key's value to
17914 * be not equal to the provided value.
17915 * @param {String} key The key to check.
17916 * @param value The value that must not be equalled.
17917 * @return {AV.Query} Returns the query, so you can chain this call.
17918 */
17919 notEqualTo: function notEqualTo(key, value) {
17920 this._addCondition(key, '$ne', value);
17921 return this;
17922 },
17923
17924 /**
17925 * Add a constraint to the query that requires a particular key's value to
17926 * be less than the provided value.
17927 * @param {String} key The key to check.
17928 * @param value The value that provides an upper bound.
17929 * @return {AV.Query} Returns the query, so you can chain this call.
17930 */
17931 lessThan: function lessThan(key, value) {
17932 this._addCondition(key, '$lt', value);
17933 return this;
17934 },
17935
17936 /**
17937 * Add a constraint to the query that requires a particular key's value to
17938 * be greater than the provided value.
17939 * @param {String} key The key to check.
17940 * @param value The value that provides an lower bound.
17941 * @return {AV.Query} Returns the query, so you can chain this call.
17942 */
17943 greaterThan: function greaterThan(key, value) {
17944 this._addCondition(key, '$gt', value);
17945 return this;
17946 },
17947
17948 /**
17949 * Add a constraint to the query that requires a particular key's value to
17950 * be less than or equal to the provided value.
17951 * @param {String} key The key to check.
17952 * @param value The value that provides an upper bound.
17953 * @return {AV.Query} Returns the query, so you can chain this call.
17954 */
17955 lessThanOrEqualTo: function lessThanOrEqualTo(key, value) {
17956 this._addCondition(key, '$lte', value);
17957 return this;
17958 },
17959
17960 /**
17961 * Add a constraint to the query that requires a particular key's value to
17962 * be greater than or equal to the provided value.
17963 * @param {String} key The key to check.
17964 * @param value The value that provides an lower bound.
17965 * @return {AV.Query} Returns the query, so you can chain this call.
17966 */
17967 greaterThanOrEqualTo: function greaterThanOrEqualTo(key, value) {
17968 this._addCondition(key, '$gte', value);
17969 return this;
17970 },
17971
17972 /**
17973 * Add a constraint to the query that requires a particular key's value to
17974 * be contained in the provided list of values.
17975 * @param {String} key The key to check.
17976 * @param {Array} values The values that will match.
17977 * @return {AV.Query} Returns the query, so you can chain this call.
17978 */
17979 containedIn: function containedIn(key, values) {
17980 this._addCondition(key, '$in', values);
17981 return this;
17982 },
17983
17984 /**
17985 * Add a constraint to the query that requires a particular key's value to
17986 * not be contained in the provided list of values.
17987 * @param {String} key The key to check.
17988 * @param {Array} values The values that will not match.
17989 * @return {AV.Query} Returns the query, so you can chain this call.
17990 */
17991 notContainedIn: function notContainedIn(key, values) {
17992 this._addCondition(key, '$nin', values);
17993 return this;
17994 },
17995
17996 /**
17997 * Add a constraint to the query that requires a particular key's value to
17998 * contain each one of the provided list of values.
17999 * @param {String} key The key to check. This key's value must be an array.
18000 * @param {Array} values The values that will match.
18001 * @return {AV.Query} Returns the query, so you can chain this call.
18002 */
18003 containsAll: function containsAll(key, values) {
18004 this._addCondition(key, '$all', values);
18005 return this;
18006 },
18007
18008 /**
18009 * Add a constraint for finding objects that contain the given key.
18010 * @param {String} key The key that should exist.
18011 * @return {AV.Query} Returns the query, so you can chain this call.
18012 */
18013 exists: function exists(key) {
18014 this._addCondition(key, '$exists', true);
18015 return this;
18016 },
18017
18018 /**
18019 * Add a constraint for finding objects that do not contain a given key.
18020 * @param {String} key The key that should not exist
18021 * @return {AV.Query} Returns the query, so you can chain this call.
18022 */
18023 doesNotExist: function doesNotExist(key) {
18024 this._addCondition(key, '$exists', false);
18025 return this;
18026 },
18027
18028 /**
18029 * Add a regular expression constraint for finding string values that match
18030 * the provided regular expression.
18031 * This may be slow for large datasets.
18032 * @param {String} key The key that the string to match is stored in.
18033 * @param {RegExp} regex The regular expression pattern to match.
18034 * @return {AV.Query} Returns the query, so you can chain this call.
18035 */
18036 matches: function matches(key, regex, modifiers) {
18037 this._addCondition(key, '$regex', regex);
18038 if (!modifiers) {
18039 modifiers = '';
18040 }
18041 // Javascript regex options support mig as inline options but store them
18042 // as properties of the object. We support mi & should migrate them to
18043 // modifiers
18044 if (regex.ignoreCase) {
18045 modifiers += 'i';
18046 }
18047 if (regex.multiline) {
18048 modifiers += 'm';
18049 }
18050
18051 if (modifiers && modifiers.length) {
18052 this._addCondition(key, '$options', modifiers);
18053 }
18054 return this;
18055 },
18056
18057 /**
18058 * Add a constraint that requires that a key's value matches a AV.Query
18059 * constraint.
18060 * @param {String} key The key that the contains the object to match the
18061 * query.
18062 * @param {AV.Query} query The query that should match.
18063 * @return {AV.Query} Returns the query, so you can chain this call.
18064 */
18065 matchesQuery: function matchesQuery(key, query) {
18066 var queryJSON = query._getParams();
18067 queryJSON.className = query.className;
18068 this._addCondition(key, '$inQuery', queryJSON);
18069 return this;
18070 },
18071
18072 /**
18073 * Add a constraint that requires that a key's value not matches a
18074 * AV.Query constraint.
18075 * @param {String} key The key that the contains the object to match the
18076 * query.
18077 * @param {AV.Query} query The query that should not match.
18078 * @return {AV.Query} Returns the query, so you can chain this call.
18079 */
18080 doesNotMatchQuery: function doesNotMatchQuery(key, query) {
18081 var queryJSON = query._getParams();
18082 queryJSON.className = query.className;
18083 this._addCondition(key, '$notInQuery', queryJSON);
18084 return this;
18085 },
18086
18087 /**
18088 * Add a constraint that requires that a key's value matches a value in
18089 * an object returned by a different AV.Query.
18090 * @param {String} key The key that contains the value that is being
18091 * matched.
18092 * @param {String} queryKey The key in the objects returned by the query to
18093 * match against.
18094 * @param {AV.Query} query The query to run.
18095 * @return {AV.Query} Returns the query, so you can chain this call.
18096 */
18097 matchesKeyInQuery: function matchesKeyInQuery(key, queryKey, query) {
18098 var queryJSON = query._getParams();
18099 queryJSON.className = query.className;
18100 this._addCondition(key, '$select', { key: queryKey, query: queryJSON });
18101 return this;
18102 },
18103
18104 /**
18105 * Add a constraint that requires that a key's value not match a value in
18106 * an object returned by a different AV.Query.
18107 * @param {String} key The key that contains the value that is being
18108 * excluded.
18109 * @param {String} queryKey The key in the objects returned by the query to
18110 * match against.
18111 * @param {AV.Query} query The query to run.
18112 * @return {AV.Query} Returns the query, so you can chain this call.
18113 */
18114 doesNotMatchKeyInQuery: function doesNotMatchKeyInQuery(key, queryKey, query) {
18115 var queryJSON = query._getParams();
18116 queryJSON.className = query.className;
18117 this._addCondition(key, '$dontSelect', {
18118 key: queryKey,
18119 query: queryJSON
18120 });
18121 return this;
18122 },
18123
18124 /**
18125 * Add constraint that at least one of the passed in queries matches.
18126 * @param {Array} queries
18127 * @return {AV.Query} Returns the query, so you can chain this call.
18128 * @private
18129 */
18130 _orQuery: function _orQuery(queries) {
18131 var queryJSON = _.map(queries, function (q) {
18132 return q._getParams().where;
18133 });
18134
18135 this._where.$or = queryJSON;
18136 return this;
18137 },
18138
18139 /**
18140 * Add constraint that both of the passed in queries matches.
18141 * @param {Array} queries
18142 * @return {AV.Query} Returns the query, so you can chain this call.
18143 * @private
18144 */
18145 _andQuery: function _andQuery(queries) {
18146 var queryJSON = _.map(queries, function (q) {
18147 return q._getParams().where;
18148 });
18149
18150 this._where.$and = queryJSON;
18151 return this;
18152 },
18153
18154 /**
18155 * Converts a string into a regex that matches it.
18156 * Surrounding with \Q .. \E does this, we just need to escape \E's in
18157 * the text separately.
18158 * @private
18159 */
18160 _quote: function _quote(s) {
18161 return '\\Q' + s.replace('\\E', '\\E\\\\E\\Q') + '\\E';
18162 },
18163
18164 /**
18165 * Add a constraint for finding string values that contain a provided
18166 * string. This may be slow for large datasets.
18167 * @param {String} key The key that the string to match is stored in.
18168 * @param {String} substring The substring that the value must contain.
18169 * @return {AV.Query} Returns the query, so you can chain this call.
18170 */
18171 contains: function contains(key, value) {
18172 this._addCondition(key, '$regex', this._quote(value));
18173 return this;
18174 },
18175
18176 /**
18177 * Add a constraint for finding string values that start with a provided
18178 * string. This query will use the backend index, so it will be fast even
18179 * for large datasets.
18180 * @param {String} key The key that the string to match is stored in.
18181 * @param {String} prefix The substring that the value must start with.
18182 * @return {AV.Query} Returns the query, so you can chain this call.
18183 */
18184 startsWith: function startsWith(key, value) {
18185 this._addCondition(key, '$regex', '^' + this._quote(value));
18186 return this;
18187 },
18188
18189 /**
18190 * Add a constraint for finding string values that end with a provided
18191 * string. This will be slow for large datasets.
18192 * @param {String} key The key that the string to match is stored in.
18193 * @param {String} suffix The substring that the value must end with.
18194 * @return {AV.Query} Returns the query, so you can chain this call.
18195 */
18196 endsWith: function endsWith(key, value) {
18197 this._addCondition(key, '$regex', this._quote(value) + '$');
18198 return this;
18199 },
18200
18201 /**
18202 * Sorts the results in ascending order by the given key.
18203 *
18204 * @param {String} key The key to order by.
18205 * @return {AV.Query} Returns the query, so you can chain this call.
18206 */
18207 ascending: function ascending(key) {
18208 requires(key, 'undefined is not a valid key');
18209 this._order = key;
18210 return this;
18211 },
18212
18213 /**
18214 * Also sorts the results in ascending order by the given key. The previous sort keys have
18215 * precedence over this key.
18216 *
18217 * @param {String} key The key to order by
18218 * @return {AV.Query} Returns the query so you can chain this call.
18219 */
18220 addAscending: function addAscending(key) {
18221 requires(key, 'undefined is not a valid key');
18222 if (this._order) this._order += ',' + key;else this._order = key;
18223 return this;
18224 },
18225
18226 /**
18227 * Sorts the results in descending order by the given key.
18228 *
18229 * @param {String} key The key to order by.
18230 * @return {AV.Query} Returns the query, so you can chain this call.
18231 */
18232 descending: function descending(key) {
18233 requires(key, 'undefined is not a valid key');
18234 this._order = '-' + key;
18235 return this;
18236 },
18237
18238 /**
18239 * Also sorts the results in descending order by the given key. The previous sort keys have
18240 * precedence over this key.
18241 *
18242 * @param {String} key The key to order by
18243 * @return {AV.Query} Returns the query so you can chain this call.
18244 */
18245 addDescending: function addDescending(key) {
18246 requires(key, 'undefined is not a valid key');
18247 if (this._order) this._order += ',-' + key;else this._order = '-' + key;
18248 return this;
18249 },
18250
18251 /**
18252 * Add a proximity based constraint for finding objects with key point
18253 * values near the point given.
18254 * @param {String} key The key that the AV.GeoPoint is stored in.
18255 * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.
18256 * @return {AV.Query} Returns the query, so you can chain this call.
18257 */
18258 near: function near(key, point) {
18259 if (!(point instanceof AV.GeoPoint)) {
18260 // Try to cast it to a GeoPoint, so that near("loc", [20,30]) works.
18261 point = new AV.GeoPoint(point);
18262 }
18263 this._addCondition(key, '$nearSphere', point);
18264 return this;
18265 },
18266
18267 /**
18268 * Add a proximity based constraint for finding objects with key point
18269 * values near the point given and within the maximum distance given.
18270 * @param {String} key The key that the AV.GeoPoint is stored in.
18271 * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.
18272 * @param maxDistance Maximum distance (in radians) of results to return.
18273 * @return {AV.Query} Returns the query, so you can chain this call.
18274 */
18275 withinRadians: function withinRadians(key, point, distance) {
18276 this.near(key, point);
18277 this._addCondition(key, '$maxDistance', distance);
18278 return this;
18279 },
18280
18281 /**
18282 * Add a proximity based constraint for finding objects with key point
18283 * values near the point given and within the maximum distance given.
18284 * Radius of earth used is 3958.8 miles.
18285 * @param {String} key The key that the AV.GeoPoint is stored in.
18286 * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.
18287 * @param {Number} maxDistance Maximum distance (in miles) of results to
18288 * return.
18289 * @return {AV.Query} Returns the query, so you can chain this call.
18290 */
18291 withinMiles: function withinMiles(key, point, distance) {
18292 return this.withinRadians(key, point, distance / 3958.8);
18293 },
18294
18295 /**
18296 * Add a proximity based constraint for finding objects with key point
18297 * values near the point given and within the maximum distance given.
18298 * Radius of earth used is 6371.0 kilometers.
18299 * @param {String} key The key that the AV.GeoPoint is stored in.
18300 * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.
18301 * @param {Number} maxDistance Maximum distance (in kilometers) of results
18302 * to return.
18303 * @return {AV.Query} Returns the query, so you can chain this call.
18304 */
18305 withinKilometers: function withinKilometers(key, point, distance) {
18306 return this.withinRadians(key, point, distance / 6371.0);
18307 },
18308
18309 /**
18310 * Add a constraint to the query that requires a particular key's
18311 * coordinates be contained within a given rectangular geographic bounding
18312 * box.
18313 * @param {String} key The key to be constrained.
18314 * @param {AV.GeoPoint} southwest
18315 * The lower-left inclusive corner of the box.
18316 * @param {AV.GeoPoint} northeast
18317 * The upper-right inclusive corner of the box.
18318 * @return {AV.Query} Returns the query, so you can chain this call.
18319 */
18320 withinGeoBox: function withinGeoBox(key, southwest, northeast) {
18321 if (!(southwest instanceof AV.GeoPoint)) {
18322 southwest = new AV.GeoPoint(southwest);
18323 }
18324 if (!(northeast instanceof AV.GeoPoint)) {
18325 northeast = new AV.GeoPoint(northeast);
18326 }
18327 this._addCondition(key, '$within', { $box: [southwest, northeast] });
18328 return this;
18329 },
18330
18331 /**
18332 * Include nested AV.Objects for the provided key. You can use dot
18333 * notation to specify which fields in the included object are also fetch.
18334 * @param {String[]} keys The name of the key to include.
18335 * @return {AV.Query} Returns the query, so you can chain this call.
18336 */
18337 include: function include(keys) {
18338 var _this4 = this;
18339
18340 requires(keys, 'undefined is not a valid key');
18341 _.forEach(arguments, function (keys) {
18342 _this4._include = _this4._include.concat(ensureArray(keys));
18343 });
18344 return this;
18345 },
18346
18347 /**
18348 * Include the ACL.
18349 * @param {Boolean} [value=true] Whether to include the ACL
18350 * @return {AV.Query} Returns the query, so you can chain this call.
18351 */
18352 includeACL: function includeACL() {
18353 var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
18354
18355 this._includeACL = value;
18356 return this;
18357 },
18358
18359 /**
18360 * Restrict the fields of the returned AV.Objects to include only the
18361 * provided keys. If this is called multiple times, then all of the keys
18362 * specified in each of the calls will be included.
18363 * @param {String[]} keys The names of the keys to include.
18364 * @return {AV.Query} Returns the query, so you can chain this call.
18365 */
18366 select: function select(keys) {
18367 var _this5 = this;
18368
18369 requires(keys, 'undefined is not a valid key');
18370 _.forEach(arguments, function (keys) {
18371 _this5._select = _this5._select.concat(ensureArray(keys));
18372 });
18373 return this;
18374 },
18375
18376 /**
18377 * Iterates over each result of a query, calling a callback for each one. If
18378 * the callback returns a promise, the iteration will not continue until
18379 * that promise has been fulfilled. If the callback returns a rejected
18380 * promise, then iteration will stop with that error. The items are
18381 * processed in an unspecified order. The query may not have any sort order,
18382 * and may not use limit or skip.
18383 * @param callback {Function} Callback that will be called with each result
18384 * of the query.
18385 * @return {Promise} A promise that will be fulfilled once the
18386 * iteration has completed.
18387 */
18388 each: function each(callback) {
18389 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
18390
18391 if (this._order || this._skip || this._limit >= 0) {
18392 var error = new Error('Cannot iterate on a query with sort, skip, or limit.');
18393 return _promise2.default.reject(error);
18394 }
18395
18396 var query = new AV.Query(this.objectClass);
18397 // We can override the batch size from the options.
18398 // This is undocumented, but useful for testing.
18399 query._limit = options.batchSize || 100;
18400 query._where = _.clone(this._where);
18401 query._include = _.clone(this._include);
18402
18403 query.ascending('objectId');
18404
18405 var finished = false;
18406 return continueWhile(function () {
18407 return !finished;
18408 }, function () {
18409 return query.find(options).then(function (results) {
18410 var callbacksDone = _promise2.default.resolve();
18411 _.each(results, function (result) {
18412 callbacksDone = callbacksDone.then(function () {
18413 return callback(result);
18414 });
18415 });
18416
18417 return callbacksDone.then(function () {
18418 if (results.length >= query._limit) {
18419 query.greaterThan('objectId', results[results.length - 1].id);
18420 } else {
18421 finished = true;
18422 }
18423 });
18424 });
18425 });
18426 },
18427
18428 /**
18429 * Subscribe the changes of this query.
18430 *
18431 * LiveQuery is not included in the default bundle: {@link https://url.leanapp.cn/enable-live-query}.
18432 *
18433 * @since 3.0.0
18434 * @return {AV.LiveQuery} An eventemitter which can be used to get LiveQuery updates;
18435 */
18436 subscribe: function subscribe(options) {
18437 return AV.LiveQuery.init(this, options);
18438 }
18439 });
18440
18441 AV.FriendShipQuery = AV.Query._extend({
18442 _newObject: function _newObject() {
18443 var UserClass = AV.Object._getSubclass('_User');
18444 return new UserClass();
18445 },
18446 _processResult: function _processResult(json) {
18447 if (json && json[this._friendshipTag]) {
18448 var user = json[this._friendshipTag];
18449 if (user.__type === 'Pointer' && user.className === '_User') {
18450 delete user.__type;
18451 delete user.className;
18452 }
18453 return user;
18454 } else {
18455 return null;
18456 }
18457 }
18458 });
18459};
18460
18461/***/ }),
18462/* 356 */
18463/***/ (function(module, exports, __webpack_require__) {
18464
18465"use strict";
18466
18467
18468var _promise = __webpack_require__(3);
18469
18470var _promise2 = _interopRequireDefault(_promise);
18471
18472function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18473
18474var _ = __webpack_require__(0);
18475var EventEmitter = __webpack_require__(180);
18476
18477var _require = __webpack_require__(19),
18478 inherits = _require.inherits;
18479
18480var _require2 = __webpack_require__(14),
18481 request = _require2.request;
18482
18483var subscribe = function subscribe(queryJSON, subscriptionId) {
18484 return request({
18485 method: 'POST',
18486 path: '/LiveQuery/subscribe',
18487 data: {
18488 query: queryJSON,
18489 id: subscriptionId
18490 }
18491 });
18492};
18493
18494module.exports = function (AV) {
18495 var requireRealtime = function requireRealtime() {
18496 if (!AV._config.realtime) {
18497 throw new Error('LiveQuery not supported. Please use the LiveQuery bundle. https://url.leanapp.cn/enable-live-query');
18498 }
18499 };
18500 /**
18501 * @class
18502 * A LiveQuery, created by {@link AV.Query#subscribe} is an EventEmitter notifies changes of the Query.
18503 * @since 3.0.0
18504 */
18505 AV.LiveQuery = inherits(EventEmitter,
18506 /** @lends AV.LiveQuery.prototype */{
18507 constructor: function constructor(id, client, queryJSON, subscriptionId) {
18508 var _this = this;
18509
18510 EventEmitter.apply(this);
18511 this.id = id;
18512 this._client = client;
18513 this._client.register(this);
18514 this._queryJSON = queryJSON;
18515 this._subscriptionId = subscriptionId;
18516 this._onMessage = this._dispatch.bind(this);
18517 this._onReconnect = function () {
18518 subscribe(_this._queryJSON, _this._subscriptionId).catch(function (error) {
18519 return console.error('LiveQuery resubscribe error: ' + error.message);
18520 });
18521 };
18522 client.on('message', this._onMessage);
18523 client.on('reconnect', this._onReconnect);
18524 },
18525 _dispatch: function _dispatch(message) {
18526 var _this2 = this;
18527
18528 message.forEach(function (_ref) {
18529 var op = _ref.op,
18530 object = _ref.object,
18531 queryId = _ref.query_id,
18532 updatedKeys = _ref.updatedKeys;
18533
18534 if (queryId !== _this2.id) return;
18535 var target = AV.parseJSON(_.extend({
18536 __type: object.className === '_File' ? 'File' : 'Object'
18537 }, object));
18538 if (updatedKeys) {
18539 /**
18540 * An existing AV.Object which fulfills the Query you subscribe is updated.
18541 * @event AV.LiveQuery#update
18542 * @param {AV.Object|AV.File} target updated object
18543 * @param {String[]} updatedKeys updated keys
18544 */
18545 /**
18546 * An existing AV.Object which doesn't fulfill the Query is updated and now it fulfills the Query.
18547 * @event AV.LiveQuery#enter
18548 * @param {AV.Object|AV.File} target updated object
18549 * @param {String[]} updatedKeys updated keys
18550 */
18551 /**
18552 * An existing AV.Object which fulfills the Query is updated and now it doesn't fulfill the Query.
18553 * @event AV.LiveQuery#leave
18554 * @param {AV.Object|AV.File} target updated object
18555 * @param {String[]} updatedKeys updated keys
18556 */
18557 _this2.emit(op, target, updatedKeys);
18558 } else {
18559 /**
18560 * A new AV.Object which fulfills the Query you subscribe is created.
18561 * @event AV.LiveQuery#create
18562 * @param {AV.Object|AV.File} target updated object
18563 */
18564 /**
18565 * An existing AV.Object which fulfills the Query you subscribe is deleted.
18566 * @event AV.LiveQuery#delete
18567 * @param {AV.Object|AV.File} target updated object
18568 */
18569 _this2.emit(op, target);
18570 }
18571 });
18572 },
18573
18574 /**
18575 * unsubscribe the query
18576 *
18577 * @return {Promise}
18578 */
18579 unsubscribe: function unsubscribe() {
18580 var client = this._client;
18581 client.off('message', this._onMessage);
18582 client.off('reconnect', this._onReconnect);
18583 client.deregister(this);
18584 return request({
18585 method: 'POST',
18586 path: '/LiveQuery/unsubscribe',
18587 data: {
18588 id: client.id,
18589 query_id: this.id
18590 }
18591 });
18592 }
18593 },
18594 /** @lends AV.LiveQuery */
18595 {
18596 init: function init(query) {
18597 var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
18598 _ref2$subscriptionId = _ref2.subscriptionId,
18599 userDefinedSubscriptionId = _ref2$subscriptionId === undefined ? AV._getSubscriptionId() : _ref2$subscriptionId;
18600
18601 requireRealtime();
18602 if (!(query instanceof AV.Query)) throw new TypeError('LiveQuery must be inited with a Query');
18603 return _promise2.default.resolve(userDefinedSubscriptionId).then(function (subscriptionId) {
18604 return AV._config.realtime.createLiveQueryClient(subscriptionId).then(function (liveQueryClient) {
18605 var _query$_getParams = query._getParams(),
18606 where = _query$_getParams.where,
18607 keys = _query$_getParams.keys,
18608 returnACL = _query$_getParams.returnACL;
18609
18610 var queryJSON = {
18611 where: where,
18612 keys: keys,
18613 returnACL: returnACL,
18614 className: query.className
18615 };
18616 var promise = subscribe(queryJSON, subscriptionId).then(function (_ref3) {
18617 var queryId = _ref3.query_id;
18618 return new AV.LiveQuery(queryId, liveQueryClient, queryJSON, subscriptionId);
18619 }).finally(function () {
18620 liveQueryClient.deregister(promise);
18621 });
18622 liveQueryClient.register(promise);
18623 return promise;
18624 });
18625 });
18626 },
18627
18628 /**
18629 * Pause the LiveQuery connection. This is useful to deactivate the SDK when the app is swtiched to background.
18630 * @static
18631 * @return void
18632 */
18633 pause: function pause() {
18634 requireRealtime();
18635 return AV._config.realtime.pause();
18636 },
18637
18638 /**
18639 * Resume the LiveQuery connection. All subscriptions will be restored after reconnection.
18640 * @static
18641 * @return void
18642 */
18643 resume: function resume() {
18644 requireRealtime();
18645 return AV._config.realtime.resume();
18646 }
18647 });
18648};
18649
18650/***/ }),
18651/* 357 */
18652/***/ (function(module, exports, __webpack_require__) {
18653
18654"use strict";
18655
18656
18657var _ = __webpack_require__(0);
18658
18659var _require = __webpack_require__(19),
18660 tap = _require.tap;
18661
18662module.exports = function (AV) {
18663 /**
18664 * @class
18665 * @example
18666 * AV.Captcha.request().then(captcha => {
18667 * captcha.bind({
18668 * textInput: 'code', // the id for textInput
18669 * image: 'captcha',
18670 * verifyButton: 'verify',
18671 * }, {
18672 * success: (validateCode) => {}, // next step
18673 * error: (error) => {}, // present error.message to user
18674 * });
18675 * });
18676 */
18677 AV.Captcha = function Captcha(options, authOptions) {
18678 this._options = options;
18679 this._authOptions = authOptions;
18680 /**
18681 * The image url of the captcha
18682 * @type string
18683 */
18684 this.url = undefined;
18685 /**
18686 * The captchaToken of the captcha.
18687 * @type string
18688 */
18689 this.captchaToken = undefined;
18690 /**
18691 * The validateToken of the captcha.
18692 * @type string
18693 */
18694 this.validateToken = undefined;
18695 };
18696
18697 /**
18698 * Refresh the captcha
18699 * @return {Promise.<string>} a new capcha url
18700 */
18701 AV.Captcha.prototype.refresh = function refresh() {
18702 var _this = this;
18703
18704 return AV.Cloud._requestCaptcha(this._options, this._authOptions).then(function (_ref) {
18705 var captchaToken = _ref.captchaToken,
18706 url = _ref.url;
18707
18708 _.extend(_this, { captchaToken: captchaToken, url: url });
18709 return url;
18710 });
18711 };
18712
18713 /**
18714 * Verify the captcha
18715 * @param {String} code The code from user input
18716 * @return {Promise.<string>} validateToken if the code is valid
18717 */
18718 AV.Captcha.prototype.verify = function verify(code) {
18719 var _this2 = this;
18720
18721 return AV.Cloud.verifyCaptcha(code, this.captchaToken).then(tap(function (validateToken) {
18722 return _this2.validateToken = validateToken;
18723 }));
18724 };
18725
18726 if (true) {
18727 /**
18728 * Bind the captcha to HTMLElements. <b>ONLY AVAILABLE in browsers</b>.
18729 * @param [elements]
18730 * @param {String|HTMLInputElement} [elements.textInput] An input element typed text, or the id for the element.
18731 * @param {String|HTMLImageElement} [elements.image] An image element, or the id for the element.
18732 * @param {String|HTMLElement} [elements.verifyButton] A button element, or the id for the element.
18733 * @param [callbacks]
18734 * @param {Function} [callbacks.success] Success callback will be called if the code is verified. The param `validateCode` can be used for further SMS request.
18735 * @param {Function} [callbacks.error] Error callback will be called if something goes wrong, detailed in param `error.message`.
18736 */
18737 AV.Captcha.prototype.bind = function bind(_ref2, _ref3) {
18738 var _this3 = this;
18739
18740 var textInput = _ref2.textInput,
18741 image = _ref2.image,
18742 verifyButton = _ref2.verifyButton;
18743 var success = _ref3.success,
18744 error = _ref3.error;
18745
18746 if (typeof textInput === 'string') {
18747 textInput = document.getElementById(textInput);
18748 if (!textInput) throw new Error('textInput with id ' + textInput + ' not found');
18749 }
18750 if (typeof image === 'string') {
18751 image = document.getElementById(image);
18752 if (!image) throw new Error('image with id ' + image + ' not found');
18753 }
18754 if (typeof verifyButton === 'string') {
18755 verifyButton = document.getElementById(verifyButton);
18756 if (!verifyButton) throw new Error('verifyButton with id ' + verifyButton + ' not found');
18757 }
18758
18759 this.__refresh = function () {
18760 return _this3.refresh().then(function (url) {
18761 image.src = url;
18762 if (textInput) {
18763 textInput.value = '';
18764 textInput.focus();
18765 }
18766 }).catch(function (err) {
18767 return console.warn('refresh captcha fail: ' + err.message);
18768 });
18769 };
18770 if (image) {
18771 this.__image = image;
18772 image.src = this.url;
18773 image.addEventListener('click', this.__refresh);
18774 }
18775
18776 this.__verify = function () {
18777 var code = textInput.value;
18778 _this3.verify(code).catch(function (err) {
18779 _this3.__refresh();
18780 throw err;
18781 }).then(success, error).catch(function (err) {
18782 return console.warn('verify captcha fail: ' + err.message);
18783 });
18784 };
18785 if (textInput && verifyButton) {
18786 this.__verifyButton = verifyButton;
18787 verifyButton.addEventListener('click', this.__verify);
18788 }
18789 };
18790
18791 /**
18792 * unbind the captcha from HTMLElements. <b>ONLY AVAILABLE in browsers</b>.
18793 */
18794 AV.Captcha.prototype.unbind = function unbind() {
18795 if (this.__image) this.__image.removeEventListener('click', this.__refresh);
18796 if (this.__verifyButton) this.__verifyButton.removeEventListener('click', this.__verify);
18797 };
18798 }
18799
18800 /**
18801 * Request a captcha
18802 * @param [options]
18803 * @param {Number} [options.width] width(px) of the captcha, ranged 60-200
18804 * @param {Number} [options.height] height(px) of the captcha, ranged 30-100
18805 * @param {Number} [options.size=4] length of the captcha, ranged 3-6. MasterKey required.
18806 * @param {Number} [options.ttl=60] time to live(s), ranged 10-180. MasterKey required.
18807 * @return {Promise.<AV.Captcha>}
18808 */
18809 AV.Captcha.request = function (options, authOptions) {
18810 var captcha = new AV.Captcha(options, authOptions);
18811 return captcha.refresh().then(function () {
18812 return captcha;
18813 });
18814 };
18815};
18816
18817/***/ }),
18818/* 358 */
18819/***/ (function(module, exports, __webpack_require__) {
18820
18821"use strict";
18822
18823
18824var _promise = __webpack_require__(3);
18825
18826var _promise2 = _interopRequireDefault(_promise);
18827
18828function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18829
18830var _ = __webpack_require__(0);
18831
18832var _require = __webpack_require__(14),
18833 _request = _require._request,
18834 request = _require.request;
18835
18836module.exports = function (AV) {
18837 /**
18838 * Contains functions for calling and declaring
18839 * <p><strong><em>
18840 * Some functions are only available from Cloud Code.
18841 * </em></strong></p>
18842 *
18843 * @namespace
18844 * @borrows AV.Captcha.request as requestCaptcha
18845 */
18846 AV.Cloud = AV.Cloud || {};
18847
18848 _.extend(AV.Cloud,
18849 /** @lends AV.Cloud */{
18850 /**
18851 * Makes a call to a cloud function.
18852 * @param {String} name The function name.
18853 * @param {Object} [data] The parameters to send to the cloud function.
18854 * @param {AuthOptions} [options]
18855 * @return {Promise} A promise that will be resolved with the result
18856 * of the function.
18857 */
18858 run: function run(name, data, options) {
18859 return request({
18860 service: 'engine',
18861 method: 'POST',
18862 path: '/functions/' + name,
18863 data: AV._encode(data, null, true),
18864 authOptions: options
18865 }).then(function (resp) {
18866 return AV._decode(resp).result;
18867 });
18868 },
18869
18870
18871 /**
18872 * Makes a call to a cloud function, you can send {AV.Object} as param or a field of param; the response
18873 * from server will also be parsed as an {AV.Object}, array of {AV.Object}, or object includes {AV.Object}
18874 * @param {String} name The function name.
18875 * @param {Object} [data] The parameters to send to the cloud function.
18876 * @param {AuthOptions} [options]
18877 * @return {Promise} A promise that will be resolved with the result of the function.
18878 */
18879 rpc: function rpc(name, data, options) {
18880 if (_.isArray(data)) {
18881 return _promise2.default.reject(new Error("Can't pass Array as the param of rpc function in JavaScript SDK."));
18882 }
18883
18884 return request({
18885 service: 'engine',
18886 method: 'POST',
18887 path: '/call/' + name,
18888 data: AV._encodeObjectOrArray(data),
18889 authOptions: options
18890 }).then(function (resp) {
18891 return AV._decode(resp).result;
18892 });
18893 },
18894
18895
18896 /**
18897 * Make a call to request server date time.
18898 * @return {Promise.<Date>} A promise that will be resolved with the result
18899 * of the function.
18900 * @since 0.5.9
18901 */
18902 getServerDate: function getServerDate() {
18903 return _request('date', null, null, 'GET').then(function (resp) {
18904 return AV._decode(resp);
18905 });
18906 },
18907
18908
18909 /**
18910 * Makes a call to request an sms code for operation verification.
18911 * @param {String|Object} data The mobile phone number string or a JSON
18912 * object that contains mobilePhoneNumber,template,sign,op,ttl,name etc.
18913 * @param {String} data.mobilePhoneNumber
18914 * @param {String} [data.template] sms template name
18915 * @param {String} [data.sign] sms signature name
18916 * @param {String} [data.smsType] sending code by `sms` (default) or `voice` call
18917 * @param {SMSAuthOptions} [options]
18918 * @return {Promise} A promise that will be resolved if the request succeed
18919 */
18920 requestSmsCode: function requestSmsCode(data) {
18921 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
18922
18923 if (_.isString(data)) {
18924 data = { mobilePhoneNumber: data };
18925 }
18926 if (!data.mobilePhoneNumber) {
18927 throw new Error('Missing mobilePhoneNumber.');
18928 }
18929 if (options.validateToken) {
18930 data = _.extend({}, data, {
18931 validate_token: options.validateToken
18932 });
18933 }
18934 return _request('requestSmsCode', null, null, 'POST', data, options);
18935 },
18936
18937
18938 /**
18939 * Makes a call to verify sms code that sent by AV.Cloud.requestSmsCode
18940 * @param {String} code The sms code sent by AV.Cloud.requestSmsCode
18941 * @param {phone} phone The mobile phoner number.
18942 * @return {Promise} A promise that will be resolved with the result
18943 * of the function.
18944 */
18945 verifySmsCode: function verifySmsCode(code, phone) {
18946 if (!code) throw new Error('Missing sms code.');
18947 var params = {};
18948 if (_.isString(phone)) {
18949 params['mobilePhoneNumber'] = phone;
18950 }
18951
18952 return _request('verifySmsCode', code, null, 'POST', params);
18953 },
18954 _requestCaptcha: function _requestCaptcha(options, authOptions) {
18955 return _request('requestCaptcha', null, null, 'GET', options, authOptions).then(function (_ref) {
18956 var url = _ref.captcha_url,
18957 captchaToken = _ref.captcha_token;
18958 return {
18959 captchaToken: captchaToken,
18960 url: url
18961 };
18962 });
18963 },
18964
18965
18966 /**
18967 * Request a captcha.
18968 */
18969 requestCaptcha: AV.Captcha.request,
18970
18971 /**
18972 * Verify captcha code. This is the low-level API for captcha.
18973 * Checkout {@link AV.Captcha} for high abstract APIs.
18974 * @param {String} code the code from user input
18975 * @param {String} captchaToken captchaToken returned by {@link AV.Cloud.requestCaptcha}
18976 * @return {Promise.<String>} validateToken if the code is valid
18977 */
18978 verifyCaptcha: function verifyCaptcha(code, captchaToken) {
18979 return _request('verifyCaptcha', null, null, 'POST', {
18980 captcha_code: code,
18981 captcha_token: captchaToken
18982 }).then(function (_ref2) {
18983 var validateToken = _ref2.validate_token;
18984 return validateToken;
18985 });
18986 }
18987 });
18988};
18989
18990/***/ }),
18991/* 359 */
18992/***/ (function(module, exports, __webpack_require__) {
18993
18994"use strict";
18995
18996
18997var request = __webpack_require__(14).request;
18998
18999module.exports = function (AV) {
19000 AV.Installation = AV.Object.extend('_Installation');
19001
19002 /**
19003 * @namespace
19004 */
19005 AV.Push = AV.Push || {};
19006
19007 /**
19008 * Sends a push notification.
19009 * @param {Object} data The data of the push notification.
19010 * @param {String[]} [data.channels] An Array of channels to push to.
19011 * @param {Date} [data.push_time] A Date object for when to send the push.
19012 * @param {Date} [data.expiration_time] A Date object for when to expire
19013 * the push.
19014 * @param {Number} [data.expiration_interval] The seconds from now to expire the push.
19015 * @param {Number} [data.flow_control] The clients to notify per second
19016 * @param {AV.Query} [data.where] An AV.Query over AV.Installation that is used to match
19017 * a set of installations to push to.
19018 * @param {String} [data.cql] A CQL statement over AV.Installation that is used to match
19019 * a set of installations to push to.
19020 * @param {Object} data.data The data to send as part of the push.
19021 More details: https://url.leanapp.cn/pushData
19022 * @param {AuthOptions} [options]
19023 * @return {Promise}
19024 */
19025 AV.Push.send = function (data, options) {
19026 if (data.where) {
19027 data.where = data.where._getParams().where;
19028 }
19029
19030 if (data.where && data.cql) {
19031 throw new Error("Both where and cql can't be set");
19032 }
19033
19034 if (data.push_time) {
19035 data.push_time = data.push_time.toJSON();
19036 }
19037
19038 if (data.expiration_time) {
19039 data.expiration_time = data.expiration_time.toJSON();
19040 }
19041
19042 if (data.expiration_time && data.expiration_interval) {
19043 throw new Error("Both expiration_time and expiration_interval can't be set");
19044 }
19045
19046 return request({
19047 service: 'push',
19048 method: 'POST',
19049 path: '/push',
19050 data: data,
19051 authOptions: options
19052 });
19053 };
19054};
19055
19056/***/ }),
19057/* 360 */
19058/***/ (function(module, exports, __webpack_require__) {
19059
19060"use strict";
19061
19062
19063var _promise = __webpack_require__(3);
19064
19065var _promise2 = _interopRequireDefault(_promise);
19066
19067var _typeof2 = __webpack_require__(23);
19068
19069var _typeof3 = _interopRequireDefault(_typeof2);
19070
19071function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19072
19073var _ = __webpack_require__(0);
19074var AVRequest = __webpack_require__(14)._request;
19075
19076var _require = __webpack_require__(19),
19077 getSessionToken = _require.getSessionToken;
19078
19079module.exports = function (AV) {
19080 var getUser = function getUser() {
19081 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
19082
19083 var sessionToken = getSessionToken(options);
19084 if (sessionToken) {
19085 return AV.User._fetchUserBySessionToken(getSessionToken(options));
19086 }
19087 return AV.User.currentAsync();
19088 };
19089
19090 var getUserPointer = function getUserPointer(options) {
19091 return getUser(options).then(function (currUser) {
19092 return AV.Object.createWithoutData('_User', currUser.id)._toPointer();
19093 });
19094 };
19095
19096 /**
19097 * Contains functions to deal with Status in LeanCloud.
19098 * @class
19099 */
19100 AV.Status = function (imageUrl, message) {
19101 this.data = {};
19102 this.inboxType = 'default';
19103 this.query = null;
19104 if (imageUrl && (typeof imageUrl === 'undefined' ? 'undefined' : (0, _typeof3.default)(imageUrl)) === 'object') {
19105 this.data = imageUrl;
19106 } else {
19107 if (imageUrl) {
19108 this.data.image = imageUrl;
19109 }
19110 if (message) {
19111 this.data.message = message;
19112 }
19113 }
19114 return this;
19115 };
19116
19117 _.extend(AV.Status.prototype,
19118 /** @lends AV.Status.prototype */{
19119 /**
19120 * Gets the value of an attribute in status data.
19121 * @param {String} attr The string name of an attribute.
19122 */
19123 get: function get(attr) {
19124 return this.data[attr];
19125 },
19126 /**
19127 * Sets a hash of model attributes on the status data.
19128 * @param {String} key The key to set.
19129 * @param {} value The value to give it.
19130 */
19131 set: function set(key, value) {
19132 this.data[key] = value;
19133 return this;
19134 },
19135 /**
19136 * Destroy this status,then it will not be avaiable in other user's inboxes.
19137 * @param {AuthOptions} options
19138 * @return {Promise} A promise that is fulfilled when the destroy
19139 * completes.
19140 */
19141 destroy: function destroy(options) {
19142 if (!this.id) return _promise2.default.reject(new Error('The status id is not exists.'));
19143 var request = AVRequest('statuses', null, this.id, 'DELETE', options);
19144 return request;
19145 },
19146 /**
19147 * Cast the AV.Status object to an AV.Object pointer.
19148 * @return {AV.Object} A AV.Object pointer.
19149 */
19150 toObject: function toObject() {
19151 if (!this.id) return null;
19152 return AV.Object.createWithoutData('_Status', this.id);
19153 },
19154 _getDataJSON: function _getDataJSON() {
19155 var json = _.clone(this.data);
19156 return AV._encode(json);
19157 },
19158 /**
19159 * Send a status by a AV.Query object.
19160 * @since 0.3.0
19161 * @param {AuthOptions} options
19162 * @return {Promise} A promise that is fulfilled when the send
19163 * completes.
19164 * @example
19165 * // send a status to male users
19166 * var status = new AVStatus('image url', 'a message');
19167 * status.query = new AV.Query('_User');
19168 * status.query.equalTo('gender', 'male');
19169 * status.send().then(function(){
19170 * //send status successfully.
19171 * }, function(err){
19172 * //an error threw.
19173 * console.dir(err);
19174 * });
19175 */
19176 send: function send() {
19177 var _this = this;
19178
19179 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
19180
19181 if (!getSessionToken(options) && !AV.User.current()) {
19182 throw new Error('Please signin an user.');
19183 }
19184 if (!this.query) {
19185 return AV.Status.sendStatusToFollowers(this, options);
19186 }
19187
19188 return getUserPointer(options).then(function (currUser) {
19189 var query = _this.query._getParams();
19190 query.className = _this.query.className;
19191 var data = {};
19192 data.query = query;
19193 _this.data = _this.data || {};
19194 _this.data.source = _this.data.source || currUser;
19195 data.data = _this._getDataJSON();
19196 data.inboxType = _this.inboxType || 'default';
19197
19198 return AVRequest('statuses', null, null, 'POST', data, options);
19199 }).then(function (response) {
19200 _this.id = response.objectId;
19201 _this.createdAt = AV._parseDate(response.createdAt);
19202 return _this;
19203 });
19204 },
19205
19206 _finishFetch: function _finishFetch(serverData) {
19207 this.id = serverData.objectId;
19208 this.createdAt = AV._parseDate(serverData.createdAt);
19209 this.updatedAt = AV._parseDate(serverData.updatedAt);
19210 this.messageId = serverData.messageId;
19211 delete serverData.messageId;
19212 delete serverData.objectId;
19213 delete serverData.createdAt;
19214 delete serverData.updatedAt;
19215 this.data = AV._decode(serverData);
19216 }
19217 });
19218
19219 /**
19220 * Send a status to current signined user's followers.
19221 * @since 0.3.0
19222 * @param {AV.Status} status A status object to be send to followers.
19223 * @param {AuthOptions} options
19224 * @return {Promise} A promise that is fulfilled when the send
19225 * completes.
19226 * @example
19227 * var status = new AVStatus('image url', 'a message');
19228 * AV.Status.sendStatusToFollowers(status).then(function(){
19229 * //send status successfully.
19230 * }, function(err){
19231 * //an error threw.
19232 * console.dir(err);
19233 * });
19234 */
19235 AV.Status.sendStatusToFollowers = function (status) {
19236 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
19237
19238 if (!getSessionToken(options) && !AV.User.current()) {
19239 throw new Error('Please signin an user.');
19240 }
19241 return getUserPointer(options).then(function (currUser) {
19242 var query = {};
19243 query.className = '_Follower';
19244 query.keys = 'follower';
19245 query.where = { user: currUser };
19246 var data = {};
19247 data.query = query;
19248 status.data = status.data || {};
19249 status.data.source = status.data.source || currUser;
19250 data.data = status._getDataJSON();
19251 data.inboxType = status.inboxType || 'default';
19252
19253 var request = AVRequest('statuses', null, null, 'POST', data, options);
19254 return request.then(function (response) {
19255 status.id = response.objectId;
19256 status.createdAt = AV._parseDate(response.createdAt);
19257 return status;
19258 });
19259 });
19260 };
19261
19262 /**
19263 * <p>Send a status from current signined user to other user's private status inbox.</p>
19264 * @since 0.3.0
19265 * @param {AV.Status} status A status object to be send to followers.
19266 * @param {String} target The target user or user's objectId.
19267 * @param {AuthOptions} options
19268 * @return {Promise} A promise that is fulfilled when the send
19269 * completes.
19270 * @example
19271 * // send a private status to user '52e84e47e4b0f8de283b079b'
19272 * var status = new AVStatus('image url', 'a message');
19273 * AV.Status.sendPrivateStatus(status, '52e84e47e4b0f8de283b079b').then(function(){
19274 * //send status successfully.
19275 * }, function(err){
19276 * //an error threw.
19277 * console.dir(err);
19278 * });
19279 */
19280 AV.Status.sendPrivateStatus = function (status, target) {
19281 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
19282
19283 if (!getSessionToken(options) && !AV.User.current()) {
19284 throw new Error('Please signin an user.');
19285 }
19286 if (!target) {
19287 throw new Error('Invalid target user.');
19288 }
19289 var userObjectId = _.isString(target) ? target : target.id;
19290 if (!userObjectId) {
19291 throw new Error('Invalid target user.');
19292 }
19293 return getUserPointer(options).then(function (currUser) {
19294 var query = {};
19295 query.className = '_User';
19296 query.where = { objectId: userObjectId };
19297 var data = {};
19298 data.query = query;
19299 status.data = status.data || {};
19300 status.data.source = status.data.source || currUser;
19301 data.data = status._getDataJSON();
19302 data.inboxType = 'private';
19303 status.inboxType = 'private';
19304
19305 var request = AVRequest('statuses', null, null, 'POST', data, options);
19306 return request.then(function (response) {
19307 status.id = response.objectId;
19308 status.createdAt = AV._parseDate(response.createdAt);
19309 return status;
19310 });
19311 });
19312 };
19313
19314 /**
19315 * Count unread statuses in someone's inbox.
19316 * @since 0.3.0
19317 * @param {AV.User} owner The status owner.
19318 * @param {String} inboxType The inbox type, 'default' by default.
19319 * @param {AuthOptions} options
19320 * @return {Promise} A promise that is fulfilled when the count
19321 * completes.
19322 * @example
19323 * AV.Status.countUnreadStatuses(AV.User.current()).then(function(response){
19324 * console.log(response.unread); //unread statuses number.
19325 * console.log(response.total); //total statuses number.
19326 * });
19327 */
19328 AV.Status.countUnreadStatuses = function (owner) {
19329 var inboxType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default';
19330 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
19331
19332 if (!_.isString(inboxType)) options = inboxType;
19333 if (!getSessionToken(options) && owner == null && !AV.User.current()) {
19334 throw new Error('Please signin an user or pass the owner objectId.');
19335 }
19336 return _promise2.default.resolve(owner || getUser(options)).then(function (owner) {
19337 var params = {};
19338 params.inboxType = AV._encode(inboxType);
19339 params.owner = AV._encode(owner);
19340 return AVRequest('subscribe/statuses/count', null, null, 'GET', params, options);
19341 });
19342 };
19343
19344 /**
19345 * reset unread statuses count in someone's inbox.
19346 * @since 2.1.0
19347 * @param {AV.User} owner The status owner.
19348 * @param {String} inboxType The inbox type, 'default' by default.
19349 * @param {AuthOptions} options
19350 * @return {Promise} A promise that is fulfilled when the reset
19351 * completes.
19352 * @example
19353 * AV.Status.resetUnreadCount(AV.User.current()).then(function(response){
19354 * console.log(response.unread); //unread statuses number.
19355 * console.log(response.total); //total statuses number.
19356 * });
19357 */
19358 AV.Status.resetUnreadCount = function (owner) {
19359 var inboxType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default';
19360 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
19361
19362 if (!_.isString(inboxType)) options = inboxType;
19363 if (!getSessionToken(options) && owner == null && !AV.User.current()) {
19364 throw new Error('Please signin an user or pass the owner objectId.');
19365 }
19366 return _promise2.default.resolve(owner || getUser(options)).then(function (owner) {
19367 var params = {};
19368 params.inboxType = AV._encode(inboxType);
19369 params.owner = AV._encode(owner);
19370 return AVRequest('subscribe/statuses/resetUnreadCount', null, null, 'POST', params, options);
19371 });
19372 };
19373
19374 /**
19375 * Create a status query to find someone's published statuses.
19376 * @since 0.3.0
19377 * @param {AV.User} source The status source, typically the publisher.
19378 * @return {AV.Query} The query object for status.
19379 * @example
19380 * //Find current user's published statuses.
19381 * var query = AV.Status.statusQuery(AV.User.current());
19382 * query.find().then(function(statuses){
19383 * //process statuses
19384 * });
19385 */
19386 AV.Status.statusQuery = function (source) {
19387 var query = new AV.Query('_Status');
19388 if (source) {
19389 query.equalTo('source', source);
19390 }
19391 return query;
19392 };
19393
19394 /**
19395 * <p>AV.InboxQuery defines a query that is used to fetch somebody's inbox statuses.</p>
19396 * @class
19397 */
19398 AV.InboxQuery = AV.Query._extend(
19399 /** @lends AV.InboxQuery.prototype */{
19400 _objectClass: AV.Status,
19401 _sinceId: 0,
19402 _maxId: 0,
19403 _inboxType: 'default',
19404 _owner: null,
19405 _newObject: function _newObject() {
19406 return new AV.Status();
19407 },
19408 _createRequest: function _createRequest(params, options) {
19409 return AV.InboxQuery.__super__._createRequest.call(this, params, options, '/subscribe/statuses');
19410 },
19411
19412 /**
19413 * Sets the messageId of results to skip before returning any results.
19414 * This is useful for pagination.
19415 * Default is zero.
19416 * @param {Number} n the mesage id.
19417 * @return {AV.InboxQuery} Returns the query, so you can chain this call.
19418 */
19419 sinceId: function sinceId(id) {
19420 this._sinceId = id;
19421 return this;
19422 },
19423 /**
19424 * Sets the maximal messageId of results。
19425 * This is useful for pagination.
19426 * Default is zero that is no limition.
19427 * @param {Number} n the mesage id.
19428 * @return {AV.InboxQuery} Returns the query, so you can chain this call.
19429 */
19430 maxId: function maxId(id) {
19431 this._maxId = id;
19432 return this;
19433 },
19434 /**
19435 * Sets the owner of the querying inbox.
19436 * @param {AV.User} owner The inbox owner.
19437 * @return {AV.InboxQuery} Returns the query, so you can chain this call.
19438 */
19439 owner: function owner(_owner) {
19440 this._owner = _owner;
19441 return this;
19442 },
19443 /**
19444 * Sets the querying inbox type.default is 'default'.
19445 * @param {Object} type The inbox type.
19446 * @return {AV.InboxQuery} Returns the query, so you can chain this call.
19447 */
19448 inboxType: function inboxType(type) {
19449 this._inboxType = type;
19450 return this;
19451 },
19452 _getParams: function _getParams() {
19453 var params = AV.InboxQuery.__super__._getParams.call(this);
19454 params.owner = AV._encode(this._owner);
19455 params.inboxType = AV._encode(this._inboxType);
19456 params.sinceId = AV._encode(this._sinceId);
19457 params.maxId = AV._encode(this._maxId);
19458 return params;
19459 }
19460 });
19461
19462 /**
19463 * Create a inbox status query to find someone's inbox statuses.
19464 * @since 0.3.0
19465 * @param {AV.User} owner The inbox's owner
19466 * @param {String} inboxType The inbox type,'default' by default.
19467 * @return {AV.InboxQuery} The inbox query object.
19468 * @see AV.InboxQuery
19469 * @example
19470 * //Find current user's default inbox statuses.
19471 * var query = AV.Status.inboxQuery(AV.User.current());
19472 * //find the statuses after the last message id
19473 * query.sinceId(lastMessageId);
19474 * query.find().then(function(statuses){
19475 * //process statuses
19476 * });
19477 */
19478 AV.Status.inboxQuery = function (owner, inboxType) {
19479 var query = new AV.InboxQuery(AV.Status);
19480 if (owner) {
19481 query._owner = owner;
19482 }
19483 if (inboxType) {
19484 query._inboxType = inboxType;
19485 }
19486 return query;
19487 };
19488};
19489
19490/***/ }),
19491/* 361 */
19492/***/ (function(module, exports, __webpack_require__) {
19493
19494"use strict";
19495
19496
19497var _stringify = __webpack_require__(21);
19498
19499var _stringify2 = _interopRequireDefault(_stringify);
19500
19501function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19502
19503var _ = __webpack_require__(0);
19504var AVRequest = __webpack_require__(14)._request;
19505
19506module.exports = function (AV) {
19507 /**
19508 * A builder to generate sort string for app searching.For example:
19509 * @class
19510 * @since 0.5.1
19511 * @example
19512 * var builder = new AV.SearchSortBuilder();
19513 * builder.ascending('key1').descending('key2','max');
19514 * var query = new AV.SearchQuery('Player');
19515 * query.sortBy(builder);
19516 * query.find().then();
19517 */
19518 AV.SearchSortBuilder = function () {
19519 this._sortFields = [];
19520 };
19521
19522 _.extend(AV.SearchSortBuilder.prototype,
19523 /** @lends AV.SearchSortBuilder.prototype */{
19524 _addField: function _addField(key, order, mode, missing) {
19525 var field = {};
19526 field[key] = {
19527 order: order || 'asc',
19528 mode: mode || 'avg',
19529 missing: '_' + (missing || 'last')
19530 };
19531 this._sortFields.push(field);
19532 return this;
19533 },
19534
19535 /**
19536 * Sorts the results in ascending order by the given key and options.
19537 *
19538 * @param {String} key The key to order by.
19539 * @param {String} mode The sort mode, default is 'avg', you can choose
19540 * 'max' or 'min' too.
19541 * @param {String} missing The missing key behaviour, default is 'last',
19542 * you can choose 'first' too.
19543 * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.
19544 */
19545 ascending: function ascending(key, mode, missing) {
19546 return this._addField(key, 'asc', mode, missing);
19547 },
19548
19549 /**
19550 * Sorts the results in descending order by the given key and options.
19551 *
19552 * @param {String} key The key to order by.
19553 * @param {String} mode The sort mode, default is 'avg', you can choose
19554 * 'max' or 'min' too.
19555 * @param {String} missing The missing key behaviour, default is 'last',
19556 * you can choose 'first' too.
19557 * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.
19558 */
19559 descending: function descending(key, mode, missing) {
19560 return this._addField(key, 'desc', mode, missing);
19561 },
19562
19563 /**
19564 * Add a proximity based constraint for finding objects with key point
19565 * values near the point given.
19566 * @param {String} key The key that the AV.GeoPoint is stored in.
19567 * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.
19568 * @param {Object} options The other options such as mode,order, unit etc.
19569 * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.
19570 */
19571 whereNear: function whereNear(key, point, options) {
19572 options = options || {};
19573 var field = {};
19574 var geo = {
19575 lat: point.latitude,
19576 lon: point.longitude
19577 };
19578 var m = {
19579 order: options.order || 'asc',
19580 mode: options.mode || 'avg',
19581 unit: options.unit || 'km'
19582 };
19583 m[key] = geo;
19584 field['_geo_distance'] = m;
19585
19586 this._sortFields.push(field);
19587 return this;
19588 },
19589
19590 /**
19591 * Build a sort string by configuration.
19592 * @return {String} the sort string.
19593 */
19594 build: function build() {
19595 return (0, _stringify2.default)(AV._encode(this._sortFields));
19596 }
19597 });
19598
19599 /**
19600 * App searching query.Use just like AV.Query:
19601 *
19602 * Visit <a href='https://leancloud.cn/docs/app_search_guide.html'>App Searching Guide</a>
19603 * for more details.
19604 * @class
19605 * @since 0.5.1
19606 * @example
19607 * var query = new AV.SearchQuery('Player');
19608 * query.queryString('*');
19609 * query.find().then(function(results) {
19610 * console.log('Found %d objects', query.hits());
19611 * //Process results
19612 * });
19613 */
19614 AV.SearchQuery = AV.Query._extend(
19615 /** @lends AV.SearchQuery.prototype */{
19616 _sid: null,
19617 _hits: 0,
19618 _queryString: null,
19619 _highlights: null,
19620 _sortBuilder: null,
19621 _clazz: null,
19622
19623 constructor: function constructor(className) {
19624 if (className) {
19625 this._clazz = className;
19626 } else {
19627 className = '__INVALID_CLASS';
19628 }
19629 AV.Query.call(this, className);
19630 },
19631
19632 _createRequest: function _createRequest(params, options) {
19633 return AVRequest('search/select', null, null, 'GET', params || this._getParams(), options);
19634 },
19635
19636 /**
19637 * Sets the sid of app searching query.Default is null.
19638 * @param {String} sid Scroll id for searching.
19639 * @return {AV.SearchQuery} Returns the query, so you can chain this call.
19640 */
19641 sid: function sid(_sid) {
19642 this._sid = _sid;
19643 return this;
19644 },
19645
19646 /**
19647 * Sets the query string of app searching.
19648 * @param {String} q The query string.
19649 * @return {AV.SearchQuery} Returns the query, so you can chain this call.
19650 */
19651 queryString: function queryString(q) {
19652 this._queryString = q;
19653 return this;
19654 },
19655
19656 /**
19657 * Sets the highlight fields. Such as
19658 * <pre><code>
19659 * query.highlights('title');
19660 * //or pass an array.
19661 * query.highlights(['title', 'content'])
19662 * </code></pre>
19663 * @param {String|String[]} highlights a list of fields.
19664 * @return {AV.SearchQuery} Returns the query, so you can chain this call.
19665 */
19666 highlights: function highlights(_highlights) {
19667 var objects;
19668 if (_highlights && _.isString(_highlights)) {
19669 objects = _.toArray(arguments);
19670 } else {
19671 objects = _highlights;
19672 }
19673 this._highlights = objects;
19674 return this;
19675 },
19676
19677 /**
19678 * Sets the sort builder for this query.
19679 * @see AV.SearchSortBuilder
19680 * @param { AV.SearchSortBuilder} builder The sort builder.
19681 * @return {AV.SearchQuery} Returns the query, so you can chain this call.
19682 *
19683 */
19684 sortBy: function sortBy(builder) {
19685 this._sortBuilder = builder;
19686 return this;
19687 },
19688
19689 /**
19690 * Returns the number of objects that match this query.
19691 * @return {Number}
19692 */
19693 hits: function hits() {
19694 if (!this._hits) {
19695 this._hits = 0;
19696 }
19697 return this._hits;
19698 },
19699
19700 _processResult: function _processResult(json) {
19701 delete json['className'];
19702 delete json['_app_url'];
19703 delete json['_deeplink'];
19704 return json;
19705 },
19706
19707 /**
19708 * Returns true when there are more documents can be retrieved by this
19709 * query instance, you can call find function to get more results.
19710 * @see AV.SearchQuery#find
19711 * @return {Boolean}
19712 */
19713 hasMore: function hasMore() {
19714 return !this._hitEnd;
19715 },
19716
19717 /**
19718 * Reset current query instance state(such as sid, hits etc) except params
19719 * for a new searching. After resetting, hasMore() will return true.
19720 */
19721 reset: function reset() {
19722 this._hitEnd = false;
19723 this._sid = null;
19724 this._hits = 0;
19725 },
19726
19727 /**
19728 * Retrieves a list of AVObjects that satisfy this query.
19729 * Either options.success or options.error is called when the find
19730 * completes.
19731 *
19732 * @see AV.Query#find
19733 * @param {AuthOptions} options
19734 * @return {Promise} A promise that is resolved with the results when
19735 * the query completes.
19736 */
19737 find: function find(options) {
19738 var self = this;
19739
19740 var request = this._createRequest(undefined, options);
19741
19742 return request.then(function (response) {
19743 //update sid for next querying.
19744 if (response.sid) {
19745 self._oldSid = self._sid;
19746 self._sid = response.sid;
19747 } else {
19748 self._sid = null;
19749 self._hitEnd = true;
19750 }
19751 self._hits = response.hits || 0;
19752
19753 return _.map(response.results, function (json) {
19754 if (json.className) {
19755 response.className = json.className;
19756 }
19757 var obj = self._newObject(response);
19758 obj.appURL = json['_app_url'];
19759 obj._finishFetch(self._processResult(json), true);
19760 return obj;
19761 });
19762 });
19763 },
19764
19765 _getParams: function _getParams() {
19766 var params = AV.SearchQuery.__super__._getParams.call(this);
19767 delete params.where;
19768 if (this._clazz) {
19769 params.clazz = this.className;
19770 }
19771 if (this._sid) {
19772 params.sid = this._sid;
19773 }
19774 if (!this._queryString) {
19775 throw new Error('Please set query string.');
19776 } else {
19777 params.q = this._queryString;
19778 }
19779 if (this._highlights) {
19780 params.highlights = this._highlights.join(',');
19781 }
19782 if (this._sortBuilder && params.order) {
19783 throw new Error('sort and order can not be set at same time.');
19784 }
19785 if (this._sortBuilder) {
19786 params.sort = this._sortBuilder.build();
19787 }
19788
19789 return params;
19790 }
19791 });
19792};
19793
19794/**
19795 * Sorts the results in ascending order by the given key.
19796 *
19797 * @method AV.SearchQuery#ascending
19798 * @param {String} key The key to order by.
19799 * @return {AV.SearchQuery} Returns the query, so you can chain this call.
19800 */
19801/**
19802 * Also sorts the results in ascending order by the given key. The previous sort keys have
19803 * precedence over this key.
19804 *
19805 * @method AV.SearchQuery#addAscending
19806 * @param {String} key The key to order by
19807 * @return {AV.SearchQuery} Returns the query so you can chain this call.
19808 */
19809/**
19810 * Sorts the results in descending order by the given key.
19811 *
19812 * @method AV.SearchQuery#descending
19813 * @param {String} key The key to order by.
19814 * @return {AV.SearchQuery} Returns the query, so you can chain this call.
19815 */
19816/**
19817 * Also sorts the results in descending order by the given key. The previous sort keys have
19818 * precedence over this key.
19819 *
19820 * @method AV.SearchQuery#addDescending
19821 * @param {String} key The key to order by
19822 * @return {AV.SearchQuery} Returns the query so you can chain this call.
19823 */
19824/**
19825 * Include nested AV.Objects for the provided key. You can use dot
19826 * notation to specify which fields in the included object are also fetch.
19827 * @method AV.SearchQuery#include
19828 * @param {String[]} keys The name of the key to include.
19829 * @return {AV.SearchQuery} Returns the query, so you can chain this call.
19830 */
19831/**
19832 * Sets the number of results to skip before returning any results.
19833 * This is useful for pagination.
19834 * Default is to skip zero results.
19835 * @method AV.SearchQuery#skip
19836 * @param {Number} n the number of results to skip.
19837 * @return {AV.SearchQuery} Returns the query, so you can chain this call.
19838 */
19839/**
19840 * Sets the limit of the number of results to return. The default limit is
19841 * 100, with a maximum of 1000 results being returned at a time.
19842 * @method AV.SearchQuery#limit
19843 * @param {Number} n the number of results to limit to.
19844 * @return {AV.SearchQuery} Returns the query, so you can chain this call.
19845 */
19846
19847/***/ }),
19848/* 362 */
19849/***/ (function(module, exports, __webpack_require__) {
19850
19851"use strict";
19852
19853
19854var _promise = __webpack_require__(3);
19855
19856var _promise2 = _interopRequireDefault(_promise);
19857
19858function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19859
19860var _ = __webpack_require__(0);
19861var AVError = __webpack_require__(34);
19862
19863var _require = __webpack_require__(14),
19864 request = _require.request;
19865
19866module.exports = function (AV) {
19867 /**
19868 * 包含了使用了 LeanCloud
19869 * <a href='/docs/leaninsight_guide.html'>离线数据分析功能</a>的函数。
19870 * <p><strong><em>
19871 * 仅在云引擎运行环境下有效。
19872 * </em></strong></p>
19873 * @namespace
19874 */
19875 AV.Insight = AV.Insight || {};
19876
19877 _.extend(AV.Insight,
19878 /** @lends AV.Insight */{
19879 /**
19880 * 开始一个 Insight 任务。结果里将返回 Job id,你可以拿得到的 id 使用
19881 * AV.Insight.JobQuery 查询任务状态和结果。
19882 * @param {Object} jobConfig 任务配置的 JSON 对象,例如:<code><pre>
19883 * { "sql" : "select count(*) as c,gender from _User group by gender",
19884 * "saveAs": {
19885 * "className" : "UserGender",
19886 * "limit": 1
19887 * }
19888 * }
19889 * </pre></code>
19890 * sql 指定任务执行的 SQL 语句, saveAs(可选) 指定将结果保存在哪张表里,limit 最大 1000。
19891 * @param {AuthOptions} [options]
19892 * @return {Promise} A promise that will be resolved with the result
19893 * of the function.
19894 */
19895 startJob: function startJob(jobConfig, options) {
19896 if (!jobConfig || !jobConfig.sql) {
19897 throw new Error('Please provide the sql to run the job.');
19898 }
19899 var data = {
19900 jobConfig: jobConfig,
19901 appId: AV.applicationId
19902 };
19903 return request({
19904 path: '/bigquery/jobs',
19905 method: 'POST',
19906 data: AV._encode(data, null, true),
19907 authOptions: options,
19908 signKey: false
19909 }).then(function (resp) {
19910 return AV._decode(resp).id;
19911 });
19912 },
19913
19914 /**
19915 * 监听 Insight 任务事件(未来推出独立部署的离线分析服务后开放)
19916 * <p><strong><em>
19917 * 仅在云引擎运行环境下有效。
19918 * </em></strong></p>
19919 * @param {String} event 监听的事件,目前尚不支持。
19920 * @param {Function} 监听回调函数,接收 (err, id) 两个参数,err 表示错误信息,
19921 * id 表示任务 id。接下来你可以拿这个 id 使用AV.Insight.JobQuery 查询任务状态和结果。
19922 *
19923 */
19924 on: function on(event, cb) {}
19925 });
19926
19927 /**
19928 * 创建一个对象,用于查询 Insight 任务状态和结果。
19929 * @class
19930 * @param {String} id 任务 id
19931 * @since 0.5.5
19932 */
19933 AV.Insight.JobQuery = function (id, className) {
19934 if (!id) {
19935 throw new Error('Please provide the job id.');
19936 }
19937 this.id = id;
19938 this.className = className;
19939 this._skip = 0;
19940 this._limit = 100;
19941 };
19942
19943 _.extend(AV.Insight.JobQuery.prototype,
19944 /** @lends AV.Insight.JobQuery.prototype */{
19945 /**
19946 * Sets the number of results to skip before returning any results.
19947 * This is useful for pagination.
19948 * Default is to skip zero results.
19949 * @param {Number} n the number of results to skip.
19950 * @return {AV.Query} Returns the query, so you can chain this call.
19951 */
19952 skip: function skip(n) {
19953 this._skip = n;
19954 return this;
19955 },
19956
19957 /**
19958 * Sets the limit of the number of results to return. The default limit is
19959 * 100, with a maximum of 1000 results being returned at a time.
19960 * @param {Number} n the number of results to limit to.
19961 * @return {AV.Query} Returns the query, so you can chain this call.
19962 */
19963 limit: function limit(n) {
19964 this._limit = n;
19965 return this;
19966 },
19967
19968 /**
19969 * 查询任务状态和结果,任务结果为一个 JSON 对象,包括 status 表示任务状态, totalCount 表示总数,
19970 * results 数组表示任务结果数组,previewCount 表示可以返回的结果总数,任务的开始和截止时间
19971 * startTime、endTime 等信息。
19972 *
19973 * @param {AuthOptions} [options]
19974 * @return {Promise} A promise that will be resolved with the result
19975 * of the function.
19976 *
19977 */
19978 find: function find(options) {
19979 var params = {
19980 skip: this._skip,
19981 limit: this._limit
19982 };
19983
19984 return request({
19985 path: '/bigquery/jobs/' + this.id,
19986 method: 'GET',
19987 query: params,
19988 authOptions: options,
19989 signKey: false
19990 }).then(function (response) {
19991 if (response.error) {
19992 return _promise2.default.reject(new AVError(response.code, response.error));
19993 }
19994 return _promise2.default.resolve(response);
19995 });
19996 }
19997 });
19998};
19999
20000/***/ }),
20001/* 363 */
20002/***/ (function(module, exports, __webpack_require__) {
20003
20004"use strict";
20005
20006
20007var _ = __webpack_require__(0);
20008
20009var _require = __webpack_require__(14),
20010 LCRequest = _require.request;
20011
20012var _require2 = __webpack_require__(19),
20013 getSessionToken = _require2.getSessionToken;
20014
20015module.exports = function (AV) {
20016 /**
20017 * Contains functions to deal with Friendship in LeanCloud.
20018 * @class
20019 */
20020 AV.Friendship = {
20021 /**
20022 * Request friendship.
20023 * @since 4.8.0
20024 * @param {String | AV.User | Object} options if an AV.User or string is given, it will be used as the friend.
20025 * @param {AV.User | string} options.friend The friend (or friend's objectId) to follow.
20026 * @param {Object} [options.attributes] key-value attributes dictionary to be used as conditions of followeeQuery.
20027 * @param {*} [authOptions]
20028 * @return {Promise<void>}
20029 */
20030 request: function request(options, authOptions) {
20031 if (!AV.User.current()) {
20032 throw new Error('Please signin an user.');
20033 }
20034 var friend = void 0;
20035 var attributes = void 0;
20036 if (options.friend) {
20037 friend = options.friend;
20038 attributes = options.attributes;
20039 } else {
20040 friend = options;
20041 }
20042 var friendObject = _.isString(friend) ? AV.Object.createWithoutData('_User', friend) : friend;
20043 return LCRequest({
20044 method: 'POST',
20045 path: '/users/friendshipRequests',
20046 data: AV._encode({
20047 user: AV.User.current(),
20048 friend: friendObject,
20049 friendship: attributes
20050 }),
20051 authOptions: authOptions
20052 });
20053 },
20054
20055 /**
20056 * Accept a friendship request.
20057 * @since 4.8.0
20058 * @param {AV.Object | string | Object} options if an AV.Object or string is given, it will be used as the request in _FriendshipRequest.
20059 * @param {AV.Object} options.request The request (or it's objectId) to be accepted.
20060 * @param {Object} [options.attributes] key-value attributes dictionary to be used as conditions of {@link AV#followeeQuery}.
20061 * @param {AuthOptions} [authOptions]
20062 * @return {Promise<void>}
20063 */
20064 acceptRequest: function acceptRequest(options) {
20065 var authOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
20066
20067 if (!getSessionToken(authOptions) && !AV.User.current()) {
20068 throw new Error('Please signin an user.');
20069 }
20070 var request = void 0;
20071 var attributes = void 0;
20072 if (options.request) {
20073 request = options.request;
20074 attributes = options.attributes;
20075 } else {
20076 request = options;
20077 }
20078 var requestId = _.isString(request) ? request : request.id;
20079 return LCRequest({
20080 method: 'PUT',
20081 path: '/users/friendshipRequests/' + requestId + '/accept',
20082 data: {
20083 friendship: AV._encode(attributes)
20084 },
20085 authOptions: authOptions
20086 });
20087 },
20088
20089 /**
20090 * Decline a friendship request.
20091 * @param {AV.Object | string} request The request (or it's objectId) to be declined.
20092 * @param {AuthOptions} [authOptions]
20093 * @return {Promise<void>}
20094 */
20095 declineRequest: function declineRequest(request) {
20096 var authOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
20097
20098 if (!getSessionToken(authOptions) && !AV.User.current()) {
20099 throw new Error('Please signin an user.');
20100 }
20101 var requestId = _.isString(request) ? request : request.id;
20102 return LCRequest({
20103 method: 'PUT',
20104 path: '/users/friendshipRequests/' + requestId + '/decline',
20105 authOptions: authOptions
20106 });
20107 }
20108 };
20109};
20110
20111/***/ }),
20112/* 364 */
20113/***/ (function(module, exports, __webpack_require__) {
20114
20115"use strict";
20116
20117
20118var _stringify = __webpack_require__(21);
20119
20120var _stringify2 = _interopRequireDefault(_stringify);
20121
20122function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20123
20124var _ = __webpack_require__(0);
20125
20126var _require = __webpack_require__(14),
20127 _request = _require._request;
20128
20129var AV = __webpack_require__(42);
20130
20131var serializeMessage = function serializeMessage(message) {
20132 if (typeof message === 'string') {
20133 return message;
20134 }
20135 if (typeof message.getPayload === 'function') {
20136 return (0, _stringify2.default)(message.getPayload());
20137 }
20138 return (0, _stringify2.default)(message);
20139};
20140
20141/**
20142 * <p>An AV.Conversation is a local representation of a LeanCloud realtime's
20143 * conversation. This class is a subclass of AV.Object, and retains the
20144 * same functionality of an AV.Object, but also extends it with various
20145 * conversation specific methods, like get members, creators of this conversation.
20146 * </p>
20147 *
20148 * @class AV.Conversation
20149 * @param {String} name The name of the Role to create.
20150 * @param {Object} [options]
20151 * @param {Boolean} [options.isSystem] Set this conversation as system conversation.
20152 * @param {Boolean} [options.isTransient] Set this conversation as transient conversation.
20153 */
20154module.exports = AV.Object.extend('_Conversation',
20155/** @lends AV.Conversation.prototype */{
20156 constructor: function constructor(name) {
20157 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
20158
20159 AV.Object.prototype.constructor.call(this, null, null);
20160 this.set('name', name);
20161 if (options.isSystem !== undefined) {
20162 this.set('sys', options.isSystem ? true : false);
20163 }
20164 if (options.isTransient !== undefined) {
20165 this.set('tr', options.isTransient ? true : false);
20166 }
20167 },
20168
20169 /**
20170 * Get current conversation's creator.
20171 *
20172 * @return {String}
20173 */
20174 getCreator: function getCreator() {
20175 return this.get('c');
20176 },
20177
20178
20179 /**
20180 * Get the last message's time.
20181 *
20182 * @return {Date}
20183 */
20184 getLastMessageAt: function getLastMessageAt() {
20185 return this.get('lm');
20186 },
20187
20188
20189 /**
20190 * Get this conversation's members
20191 *
20192 * @return {String[]}
20193 */
20194 getMembers: function getMembers() {
20195 return this.get('m');
20196 },
20197
20198
20199 /**
20200 * Add a member to this conversation
20201 *
20202 * @param {String} member
20203 */
20204 addMember: function addMember(member) {
20205 return this.add('m', member);
20206 },
20207
20208
20209 /**
20210 * Get this conversation's members who set this conversation as muted.
20211 *
20212 * @return {String[]}
20213 */
20214 getMutedMembers: function getMutedMembers() {
20215 return this.get('mu');
20216 },
20217
20218
20219 /**
20220 * Get this conversation's name field.
20221 *
20222 * @return String
20223 */
20224 getName: function getName() {
20225 return this.get('name');
20226 },
20227
20228
20229 /**
20230 * Returns true if this conversation is transient conversation.
20231 *
20232 * @return {Boolean}
20233 */
20234 isTransient: function isTransient() {
20235 return this.get('tr');
20236 },
20237
20238
20239 /**
20240 * Returns true if this conversation is system conversation.
20241 *
20242 * @return {Boolean}
20243 */
20244 isSystem: function isSystem() {
20245 return this.get('sys');
20246 },
20247
20248
20249 /**
20250 * Send realtime message to this conversation, using HTTP request.
20251 *
20252 * @param {String} fromClient Sender's client id.
20253 * @param {String|Object} message The message which will send to conversation.
20254 * It could be a raw string, or an object with a `toJSON` method, like a
20255 * realtime SDK's Message object. See more: {@link https://leancloud.cn/docs/realtime_guide-js.html#消息}
20256 * @param {Object} [options]
20257 * @param {Boolean} [options.transient] Whether send this message as transient message or not.
20258 * @param {String[]} [options.toClients] Ids of clients to send to. This option can be used only in system conversation.
20259 * @param {Object} [options.pushData] Push data to this message. See more: {@link https://url.leanapp.cn/pushData 推送消息内容}
20260 * @param {AuthOptions} [authOptions]
20261 * @return {Promise}
20262 */
20263 send: function send(fromClient, message) {
20264 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
20265 var authOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
20266
20267 var data = {
20268 from_peer: fromClient,
20269 conv_id: this.id,
20270 transient: false,
20271 message: serializeMessage(message)
20272 };
20273 if (options.toClients !== undefined) {
20274 data.to_peers = options.toClients;
20275 }
20276 if (options.transient !== undefined) {
20277 data.transient = options.transient ? true : false;
20278 }
20279 if (options.pushData !== undefined) {
20280 data.push_data = options.pushData;
20281 }
20282 return _request('rtm', 'messages', null, 'POST', data, authOptions);
20283 },
20284
20285
20286 /**
20287 * Send realtime broadcast message to all clients, via this conversation, using HTTP request.
20288 *
20289 * @param {String} fromClient Sender's client id.
20290 * @param {String|Object} message The message which will send to conversation.
20291 * It could be a raw string, or an object with a `toJSON` method, like a
20292 * realtime SDK's Message object. See more: {@link https://leancloud.cn/docs/realtime_guide-js.html#消息}.
20293 * @param {Object} [options]
20294 * @param {Object} [options.pushData] Push data to this message. See more: {@link https://url.leanapp.cn/pushData 推送消息内容}.
20295 * @param {Object} [options.validTill] The message will valid till this time.
20296 * @param {AuthOptions} [authOptions]
20297 * @return {Promise}
20298 */
20299 broadcast: function broadcast(fromClient, message) {
20300 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
20301 var authOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
20302
20303 var data = {
20304 from_peer: fromClient,
20305 conv_id: this.id,
20306 message: serializeMessage(message)
20307 };
20308 if (options.pushData !== undefined) {
20309 data.push = options.pushData;
20310 }
20311 if (options.validTill !== undefined) {
20312 var ts = options.validTill;
20313 if (_.isDate(ts)) {
20314 ts = ts.getTime();
20315 }
20316 options.valid_till = ts;
20317 }
20318 return _request('rtm', 'broadcast', null, 'POST', data, authOptions);
20319 }
20320});
20321
20322/***/ }),
20323/* 365 */
20324/***/ (function(module, exports, __webpack_require__) {
20325
20326"use strict";
20327
20328
20329var _promise = __webpack_require__(3);
20330
20331var _promise2 = _interopRequireDefault(_promise);
20332
20333function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20334
20335var _ = __webpack_require__(0);
20336
20337var _require = __webpack_require__(14),
20338 request = _require.request;
20339
20340var _require2 = __webpack_require__(19),
20341 ensureArray = _require2.ensureArray,
20342 parseDate = _require2.parseDate;
20343
20344var AV = __webpack_require__(42);
20345
20346/**
20347 * The version change interval for Leaderboard
20348 * @enum
20349 */
20350AV.LeaderboardVersionChangeInterval = {
20351 NEVER: 'never',
20352 DAY: 'day',
20353 WEEK: 'week',
20354 MONTH: 'month'
20355};
20356
20357/**
20358 * The order of the leaderboard results
20359 * @enum
20360 */
20361AV.LeaderboardOrder = {
20362 ASCENDING: 'ascending',
20363 DESCENDING: 'descending'
20364};
20365
20366/**
20367 * The update strategy for Leaderboard
20368 * @enum
20369 */
20370AV.LeaderboardUpdateStrategy = {
20371 /** Only keep the best statistic. If the leaderboard is in descending order, the best statistic is the highest one. */
20372 BETTER: 'better',
20373 /** Keep the last updated statistic */
20374 LAST: 'last',
20375 /** Keep the sum of all updated statistics */
20376 SUM: 'sum'
20377};
20378
20379/**
20380 * @typedef {Object} Ranking
20381 * @property {number} rank Starts at 0
20382 * @property {number} value the statistic value of this ranking
20383 * @property {AV.User} user The user of this ranking
20384 * @property {Statistic[]} [includedStatistics] Other statistics of the user, specified by the `includeStatistic` option of `AV.Leaderboard.getResults()`
20385 */
20386
20387/**
20388 * @typedef {Object} LeaderboardArchive
20389 * @property {string} statisticName
20390 * @property {number} version version of the leaderboard
20391 * @property {string} status
20392 * @property {string} url URL for the downloadable archive
20393 * @property {Date} activatedAt time when this version became active
20394 * @property {Date} deactivatedAt time when this version was deactivated by a version incrementing
20395 */
20396
20397/**
20398 * @class
20399 */
20400function Statistic(_ref) {
20401 var name = _ref.name,
20402 value = _ref.value,
20403 version = _ref.version;
20404
20405 /**
20406 * @type {string}
20407 */
20408 this.name = name;
20409 /**
20410 * @type {number}
20411 */
20412 this.value = value;
20413 /**
20414 * @type {number?}
20415 */
20416 this.version = version;
20417}
20418
20419var parseStatisticData = function parseStatisticData(statisticData) {
20420 var _AV$_decode = AV._decode(statisticData),
20421 name = _AV$_decode.statisticName,
20422 value = _AV$_decode.statisticValue,
20423 version = _AV$_decode.version;
20424
20425 return new Statistic({ name: name, value: value, version: version });
20426};
20427
20428/**
20429 * @class
20430 */
20431AV.Leaderboard = function Leaderboard(statisticName) {
20432 /**
20433 * @type {string}
20434 */
20435 this.statisticName = statisticName;
20436 /**
20437 * @type {AV.LeaderboardOrder}
20438 */
20439 this.order = undefined;
20440 /**
20441 * @type {AV.LeaderboardUpdateStrategy}
20442 */
20443 this.updateStrategy = undefined;
20444 /**
20445 * @type {AV.LeaderboardVersionChangeInterval}
20446 */
20447 this.versionChangeInterval = undefined;
20448 /**
20449 * @type {number}
20450 */
20451 this.version = undefined;
20452 /**
20453 * @type {Date?}
20454 */
20455 this.nextResetAt = undefined;
20456 /**
20457 * @type {Date?}
20458 */
20459 this.createdAt = undefined;
20460};
20461var Leaderboard = AV.Leaderboard;
20462
20463/**
20464 * Create an instance of Leaderboard for the give statistic name.
20465 * @param {string} statisticName
20466 * @return {AV.Leaderboard}
20467 */
20468AV.Leaderboard.createWithoutData = function (statisticName) {
20469 return new Leaderboard(statisticName);
20470};
20471/**
20472 * (masterKey required) Create a new Leaderboard.
20473 * @param {Object} options
20474 * @param {string} options.statisticName
20475 * @param {AV.LeaderboardOrder} options.order
20476 * @param {AV.LeaderboardVersionChangeInterval} [options.versionChangeInterval] default to WEEK
20477 * @param {AV.LeaderboardUpdateStrategy} [options.updateStrategy] default to BETTER
20478 * @param {AuthOptions} [authOptions]
20479 * @return {Promise<AV.Leaderboard>}
20480 */
20481AV.Leaderboard.createLeaderboard = function (_ref2, authOptions) {
20482 var statisticName = _ref2.statisticName,
20483 order = _ref2.order,
20484 versionChangeInterval = _ref2.versionChangeInterval,
20485 updateStrategy = _ref2.updateStrategy;
20486 return request({
20487 method: 'POST',
20488 path: '/leaderboard/leaderboards',
20489 data: {
20490 statisticName: statisticName,
20491 order: order,
20492 versionChangeInterval: versionChangeInterval,
20493 updateStrategy: updateStrategy
20494 },
20495 authOptions: authOptions
20496 }).then(function (data) {
20497 var leaderboard = new Leaderboard(statisticName);
20498 return leaderboard._finishFetch(data);
20499 });
20500};
20501/**
20502 * Get the Leaderboard with the specified statistic name.
20503 * @param {string} statisticName
20504 * @param {AuthOptions} [authOptions]
20505 * @return {Promise<AV.Leaderboard>}
20506 */
20507AV.Leaderboard.getLeaderboard = function (statisticName, authOptions) {
20508 return Leaderboard.createWithoutData(statisticName).fetch(authOptions);
20509};
20510/**
20511 * Get Statistics for the specified user.
20512 * @param {AV.User} user The specified AV.User pointer.
20513 * @param {Object} [options]
20514 * @param {string[]} [options.statisticNames] Specify the statisticNames. If not set, all statistics of the user will be fetched.
20515 * @param {AuthOptions} [authOptions]
20516 * @return {Promise<Statistic[]>}
20517 */
20518AV.Leaderboard.getStatistics = function (user) {
20519 var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
20520 statisticNames = _ref3.statisticNames;
20521
20522 var authOptions = arguments[2];
20523 return _promise2.default.resolve().then(function () {
20524 if (!(user && user.id)) throw new Error('user must be an AV.User');
20525 return request({
20526 method: 'GET',
20527 path: '/leaderboard/users/' + user.id + '/statistics',
20528 query: {
20529 statistics: statisticNames ? ensureArray(statisticNames).join(',') : undefined
20530 },
20531 authOptions: authOptions
20532 }).then(function (_ref4) {
20533 var results = _ref4.results;
20534 return results.map(parseStatisticData);
20535 });
20536 });
20537};
20538
20539/**
20540 * Update Statistics for the specified user.
20541 * @param {AV.User} user The specified AV.User pointer.
20542 * @param {Object} statistics A name-value pair representing the statistics to update.
20543 * @param {AuthOptions} [options] AuthOptions plus:
20544 * @param {boolean} [options.overwrite] Wethere to overwrite these statistics disregarding the updateStrategy of there leaderboards
20545 * @return {Promise<Statistic[]>}
20546 */
20547AV.Leaderboard.updateStatistics = function (user, statistics) {
20548 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
20549 return _promise2.default.resolve().then(function () {
20550 if (!(user && user.id)) throw new Error('user must be an AV.User');
20551 var data = _.map(statistics, function (value, key) {
20552 return {
20553 statisticName: key,
20554 statisticValue: value
20555 };
20556 });
20557 var overwrite = options.overwrite;
20558
20559 return request({
20560 method: 'POST',
20561 path: '/leaderboard/users/' + user.id + '/statistics',
20562 query: {
20563 overwrite: overwrite ? 1 : undefined
20564 },
20565 data: data,
20566 authOptions: options
20567 }).then(function (_ref5) {
20568 var results = _ref5.results;
20569 return results.map(parseStatisticData);
20570 });
20571 });
20572};
20573
20574/**
20575 * Delete Statistics for the specified user.
20576 * @param {AV.User} user The specified AV.User pointer.
20577 * @param {Object} statistics A name-value pair representing the statistics to delete.
20578 * @param {AuthOptions} [options]
20579 * @return {Promise<void>}
20580 */
20581AV.Leaderboard.deleteStatistics = function (user, statisticNames, authOptions) {
20582 return _promise2.default.resolve().then(function () {
20583 if (!(user && user.id)) throw new Error('user must be an AV.User');
20584 return request({
20585 method: 'DELETE',
20586 path: '/leaderboard/users/' + user.id + '/statistics',
20587 query: {
20588 statistics: ensureArray(statisticNames).join(',')
20589 },
20590 authOptions: authOptions
20591 }).then(function () {
20592 return undefined;
20593 });
20594 });
20595};
20596
20597_.extend(Leaderboard.prototype,
20598/** @lends AV.Leaderboard.prototype */{
20599 _finishFetch: function _finishFetch(data) {
20600 var _this = this;
20601
20602 _.forEach(data, function (value, key) {
20603 if (key === 'updatedAt' || key === 'objectId') return;
20604 if (key === 'expiredAt') {
20605 key = 'nextResetAt';
20606 }
20607 if (key === 'createdAt') {
20608 value = parseDate(value);
20609 }
20610 if (value && value.__type === 'Date') {
20611 value = parseDate(value.iso);
20612 }
20613 _this[key] = value;
20614 });
20615 return this;
20616 },
20617
20618 /**
20619 * Fetch data from the srever.
20620 * @param {AuthOptions} [authOptions]
20621 * @return {Promise<AV.Leaderboard>}
20622 */
20623 fetch: function fetch(authOptions) {
20624 var _this2 = this;
20625
20626 return request({
20627 method: 'GET',
20628 path: '/leaderboard/leaderboards/' + this.statisticName,
20629 authOptions: authOptions
20630 }).then(function (data) {
20631 return _this2._finishFetch(data);
20632 });
20633 },
20634
20635 /**
20636 * Counts the number of users participated in this leaderboard
20637 * @param {Object} [options]
20638 * @param {number} [options.version] Specify the version of the leaderboard
20639 * @param {AuthOptions} [authOptions]
20640 * @return {Promise<number>}
20641 */
20642 count: function count() {
20643 var _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
20644 version = _ref6.version;
20645
20646 var authOptions = arguments[1];
20647
20648 return request({
20649 method: 'GET',
20650 path: '/leaderboard/leaderboards/' + this.statisticName + '/ranks',
20651 query: {
20652 count: 1,
20653 limit: 0,
20654 version: version
20655 },
20656 authOptions: authOptions
20657 }).then(function (_ref7) {
20658 var count = _ref7.count;
20659 return count;
20660 });
20661 },
20662 _getResults: function _getResults(_ref8, authOptions, userId) {
20663 var skip = _ref8.skip,
20664 limit = _ref8.limit,
20665 selectUserKeys = _ref8.selectUserKeys,
20666 includeUserKeys = _ref8.includeUserKeys,
20667 includeStatistics = _ref8.includeStatistics,
20668 version = _ref8.version;
20669
20670 return request({
20671 method: 'GET',
20672 path: '/leaderboard/leaderboards/' + this.statisticName + '/ranks' + (userId ? '/' + userId : ''),
20673 query: {
20674 skip: skip,
20675 limit: limit,
20676 selectUserKeys: _.union(ensureArray(selectUserKeys), ensureArray(includeUserKeys)).join(',') || undefined,
20677 includeUser: includeUserKeys ? ensureArray(includeUserKeys).join(',') : undefined,
20678 includeStatistics: includeStatistics ? ensureArray(includeStatistics).join(',') : undefined,
20679 version: version
20680 },
20681 authOptions: authOptions
20682 }).then(function (_ref9) {
20683 var rankings = _ref9.results;
20684 return rankings.map(function (rankingData) {
20685 var _AV$_decode2 = AV._decode(rankingData),
20686 user = _AV$_decode2.user,
20687 value = _AV$_decode2.statisticValue,
20688 rank = _AV$_decode2.rank,
20689 _AV$_decode2$statisti = _AV$_decode2.statistics,
20690 statistics = _AV$_decode2$statisti === undefined ? [] : _AV$_decode2$statisti;
20691
20692 return {
20693 user: user,
20694 value: value,
20695 rank: rank,
20696 includedStatistics: statistics.map(parseStatisticData)
20697 };
20698 });
20699 });
20700 },
20701
20702 /**
20703 * Retrieve a list of ranked users for this Leaderboard.
20704 * @param {Object} [options]
20705 * @param {number} [options.skip] The number of results to skip. This is useful for pagination.
20706 * @param {number} [options.limit] The limit of the number of results.
20707 * @param {string[]} [options.selectUserKeys] Specify keys of the users to include in the Rankings
20708 * @param {string[]} [options.includeUserKeys] If the value of a selected user keys is a Pointer, use this options to include its value.
20709 * @param {string[]} [options.includeStatistics] Specify other statistics to include in the Rankings
20710 * @param {number} [options.version] Specify the version of the leaderboard
20711 * @param {AuthOptions} [authOptions]
20712 * @return {Promise<Ranking[]>}
20713 */
20714 getResults: function getResults() {
20715 var _ref10 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
20716 skip = _ref10.skip,
20717 limit = _ref10.limit,
20718 selectUserKeys = _ref10.selectUserKeys,
20719 includeUserKeys = _ref10.includeUserKeys,
20720 includeStatistics = _ref10.includeStatistics,
20721 version = _ref10.version;
20722
20723 var authOptions = arguments[1];
20724
20725 return this._getResults({
20726 skip: skip,
20727 limit: limit,
20728 selectUserKeys: selectUserKeys,
20729 includeUserKeys: includeUserKeys,
20730 includeStatistics: includeStatistics,
20731 version: version
20732 }, authOptions);
20733 },
20734
20735 /**
20736 * Retrieve a list of ranked users for this Leaderboard, centered on the specified user.
20737 * @param {AV.User} user The specified AV.User pointer.
20738 * @param {Object} [options]
20739 * @param {number} [options.limit] The limit of the number of results.
20740 * @param {string[]} [options.selectUserKeys] Specify keys of the users to include in the Rankings
20741 * @param {string[]} [options.includeUserKeys] If the value of a selected user keys is a Pointer, use this options to include its value.
20742 * @param {string[]} [options.includeStatistics] Specify other statistics to include in the Rankings
20743 * @param {number} [options.version] Specify the version of the leaderboard
20744 * @param {AuthOptions} [authOptions]
20745 * @return {Promise<Ranking[]>}
20746 */
20747 getResultsAroundUser: function getResultsAroundUser(user) {
20748 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
20749 var authOptions = arguments[2];
20750
20751 // getResultsAroundUser(options, authOptions)
20752 if (user && typeof user.id !== 'string') {
20753 return this.getResultsAroundUser(undefined, user, options);
20754 }
20755 var limit = options.limit,
20756 selectUserKeys = options.selectUserKeys,
20757 includeUserKeys = options.includeUserKeys,
20758 includeStatistics = options.includeStatistics,
20759 version = options.version;
20760
20761 return this._getResults({ limit: limit, selectUserKeys: selectUserKeys, includeUserKeys: includeUserKeys, includeStatistics: includeStatistics, version: version }, authOptions, user ? user.id : 'self');
20762 },
20763 _update: function _update(data, authOptions) {
20764 var _this3 = this;
20765
20766 return request({
20767 method: 'PUT',
20768 path: '/leaderboard/leaderboards/' + this.statisticName,
20769 data: data,
20770 authOptions: authOptions
20771 }).then(function (result) {
20772 return _this3._finishFetch(result);
20773 });
20774 },
20775
20776 /**
20777 * (masterKey required) Update the version change interval of the Leaderboard.
20778 * @param {AV.LeaderboardVersionChangeInterval} versionChangeInterval
20779 * @param {AuthOptions} [authOptions]
20780 * @return {Promise<AV.Leaderboard>}
20781 */
20782 updateVersionChangeInterval: function updateVersionChangeInterval(versionChangeInterval, authOptions) {
20783 return this._update({ versionChangeInterval: versionChangeInterval }, authOptions);
20784 },
20785
20786 /**
20787 * (masterKey required) Update the version change interval of the Leaderboard.
20788 * @param {AV.LeaderboardUpdateStrategy} updateStrategy
20789 * @param {AuthOptions} [authOptions]
20790 * @return {Promise<AV.Leaderboard>}
20791 */
20792 updateUpdateStrategy: function updateUpdateStrategy(updateStrategy, authOptions) {
20793 return this._update({ updateStrategy: updateStrategy }, authOptions);
20794 },
20795
20796 /**
20797 * (masterKey required) Reset the Leaderboard. The version of the Leaderboard will be incremented by 1.
20798 * @param {AuthOptions} [authOptions]
20799 * @return {Promise<AV.Leaderboard>}
20800 */
20801 reset: function reset(authOptions) {
20802 var _this4 = this;
20803
20804 return request({
20805 method: 'PUT',
20806 path: '/leaderboard/leaderboards/' + this.statisticName + '/incrementVersion',
20807 authOptions: authOptions
20808 }).then(function (data) {
20809 return _this4._finishFetch(data);
20810 });
20811 },
20812
20813 /**
20814 * (masterKey required) Delete the Leaderboard and its all archived versions.
20815 * @param {AuthOptions} [authOptions]
20816 * @return {void}
20817 */
20818 destroy: function destroy(authOptions) {
20819 return AV.request({
20820 method: 'DELETE',
20821 path: '/leaderboard/leaderboards/' + this.statisticName,
20822 authOptions: authOptions
20823 }).then(function () {
20824 return undefined;
20825 });
20826 },
20827
20828 /**
20829 * (masterKey required) Get archived versions.
20830 * @param {Object} [options]
20831 * @param {number} [options.skip] The number of results to skip. This is useful for pagination.
20832 * @param {number} [options.limit] The limit of the number of results.
20833 * @param {AuthOptions} [authOptions]
20834 * @return {Promise<LeaderboardArchive[]>}
20835 */
20836 getArchives: function getArchives() {
20837 var _this5 = this;
20838
20839 var _ref11 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
20840 skip = _ref11.skip,
20841 limit = _ref11.limit;
20842
20843 var authOptions = arguments[1];
20844
20845 return request({
20846 method: 'GET',
20847 path: '/leaderboard/leaderboards/' + this.statisticName + '/archives',
20848 query: {
20849 skip: skip,
20850 limit: limit
20851 },
20852 authOptions: authOptions
20853 }).then(function (_ref12) {
20854 var results = _ref12.results;
20855 return results.map(function (_ref13) {
20856 var version = _ref13.version,
20857 status = _ref13.status,
20858 url = _ref13.url,
20859 activatedAt = _ref13.activatedAt,
20860 deactivatedAt = _ref13.deactivatedAt;
20861 return {
20862 statisticName: _this5.statisticName,
20863 version: version,
20864 status: status,
20865 url: url,
20866 activatedAt: parseDate(activatedAt.iso),
20867 deactivatedAt: parseDate(deactivatedAt.iso)
20868 };
20869 });
20870 });
20871 }
20872});
20873
20874/***/ }),
20875/* 366 */
20876/***/ (function(module, exports, __webpack_require__) {
20877
20878"use strict";
20879
20880
20881Object.defineProperty(exports, "__esModule", {
20882 value: true
20883});
20884
20885var _adaptersSuperagent = __webpack_require__(367);
20886
20887Object.defineProperty(exports, "request", {
20888 enumerable: true,
20889 get: function get() {
20890 return _adaptersSuperagent.request;
20891 }
20892});
20893Object.defineProperty(exports, "upload", {
20894 enumerable: true,
20895 get: function get() {
20896 return _adaptersSuperagent.upload;
20897 }
20898});
20899
20900
20901var storage = window.localStorage;
20902var WebSocket = window.WebSocket;
20903var platformInfo = {
20904 name: "Browser"
20905};
20906
20907exports.WebSocket = WebSocket;
20908exports.platformInfo = platformInfo;
20909exports.storage = storage;
20910//# sourceMappingURL=index.es.js.map
20911
20912/***/ }),
20913/* 367 */
20914/***/ (function(module, exports, __webpack_require__) {
20915
20916"use strict";
20917
20918Object.defineProperty(exports, "__esModule", { value: true });
20919exports.upload = exports.request = void 0;
20920var adapter_utils_1 = __webpack_require__(368);
20921var superagent = __webpack_require__(369);
20922function convertResponse(res) {
20923 return {
20924 ok: res.ok,
20925 status: res.status,
20926 headers: res.header,
20927 data: res.body,
20928 };
20929}
20930exports.request = function (url, options) {
20931 if (options === void 0) { options = {}; }
20932 var _a = options.method, method = _a === void 0 ? "GET" : _a, data = options.data, headers = options.headers, onprogress = options.onprogress, signal = options.signal;
20933 if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
20934 return Promise.reject(new adapter_utils_1.AbortError("Request aborted"));
20935 }
20936 var req = superagent(method, url);
20937 if (headers) {
20938 req.set(headers);
20939 }
20940 if (onprogress) {
20941 req.on("progress", onprogress);
20942 }
20943 return new Promise(function (resolve, reject) {
20944 var abortListener = function () {
20945 reject(new adapter_utils_1.AbortError("Request aborted"));
20946 req.abort();
20947 };
20948 signal === null || signal === void 0 ? void 0 : signal.addEventListener("abort", abortListener);
20949 req
20950 .send(data)
20951 .then(function (res) { return resolve(convertResponse(res)); })
20952 .catch(function (err) {
20953 if (err.response) {
20954 resolve(convertResponse(err.response));
20955 }
20956 else {
20957 reject(err);
20958 }
20959 })
20960 .finally(function () { return signal === null || signal === void 0 ? void 0 : signal.removeEventListener("abort", abortListener); });
20961 });
20962};
20963exports.upload = function (url, file, options) {
20964 if (options === void 0) { options = {}; }
20965 var _a = options.method, method = _a === void 0 ? "POST" : _a, data = options.data, headers = options.headers, onprogress = options.onprogress, signal = options.signal;
20966 if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
20967 return Promise.reject(new adapter_utils_1.AbortError("Request aborted"));
20968 }
20969 var req = superagent(method, url).attach(file.field, file.data, file.name);
20970 if (data) {
20971 req.field(data);
20972 }
20973 if (headers) {
20974 req.set(headers);
20975 }
20976 if (onprogress) {
20977 req.on("progress", onprogress);
20978 }
20979 return new Promise(function (resolve, reject) {
20980 var abortListener = function () {
20981 reject(new adapter_utils_1.AbortError("Request aborted"));
20982 req.abort();
20983 };
20984 signal === null || signal === void 0 ? void 0 : signal.addEventListener("abort", abortListener);
20985 req
20986 .then(function (res) { return resolve(convertResponse(res)); })
20987 .catch(function (err) {
20988 if (err.response) {
20989 resolve(convertResponse(err.response));
20990 }
20991 else {
20992 reject(err);
20993 }
20994 })
20995 .finally(function () { return signal === null || signal === void 0 ? void 0 : signal.removeEventListener("abort", abortListener); });
20996 });
20997};
20998//# sourceMappingURL=index.js.map
20999
21000/***/ }),
21001/* 368 */
21002/***/ (function(module, __webpack_exports__, __webpack_require__) {
21003
21004"use strict";
21005Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
21006/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AbortError", function() { return AbortError; });
21007/*! *****************************************************************************
21008Copyright (c) Microsoft Corporation.
21009
21010Permission to use, copy, modify, and/or distribute this software for any
21011purpose with or without fee is hereby granted.
21012
21013THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
21014REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
21015AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
21016INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
21017LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
21018OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21019PERFORMANCE OF THIS SOFTWARE.
21020***************************************************************************** */
21021/* global Reflect, Promise */
21022
21023var extendStatics = function(d, b) {
21024 extendStatics = Object.setPrototypeOf ||
21025 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21026 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
21027 return extendStatics(d, b);
21028};
21029
21030function __extends(d, b) {
21031 extendStatics(d, b);
21032 function __() { this.constructor = d; }
21033 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21034}
21035
21036var AbortError = /** @class */ (function (_super) {
21037 __extends(AbortError, _super);
21038 function AbortError() {
21039 var _this = _super !== null && _super.apply(this, arguments) || this;
21040 _this.name = "AbortError";
21041 return _this;
21042 }
21043 return AbortError;
21044}(Error));
21045
21046
21047//# sourceMappingURL=index.es.js.map
21048
21049
21050/***/ }),
21051/* 369 */
21052/***/ (function(module, exports, __webpack_require__) {
21053
21054"use strict";
21055
21056
21057var _iterator = __webpack_require__(73);
21058
21059var _iterator2 = _interopRequireDefault(_iterator);
21060
21061var _typeof3 = __webpack_require__(23);
21062
21063var _typeof4 = _interopRequireDefault(_typeof3);
21064
21065var _symbol = __webpack_require__(44);
21066
21067var _symbol2 = _interopRequireDefault(_symbol);
21068
21069function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
21070
21071function _typeof(obj) {
21072 "@babel/helpers - typeof";
21073 if (typeof _symbol2.default === "function" && (0, _typeof4.default)(_iterator2.default) === "symbol") {
21074 _typeof = function _typeof(obj) {
21075 return typeof obj === "undefined" ? "undefined" : (0, _typeof4.default)(obj);
21076 };
21077 } else {
21078 _typeof = function _typeof(obj) {
21079 return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : (0, _typeof4.default)(obj);
21080 };
21081 }return _typeof(obj);
21082}
21083
21084/**
21085 * Root reference for iframes.
21086 */
21087var root;
21088
21089if (typeof window !== 'undefined') {
21090 // Browser window
21091 root = window;
21092} else if (typeof self === 'undefined') {
21093 // Other environments
21094 console.warn('Using browser-only version of superagent in non-browser environment');
21095 root = void 0;
21096} else {
21097 // Web Worker
21098 root = self;
21099}
21100
21101var Emitter = __webpack_require__(370);
21102
21103var safeStringify = __webpack_require__(371);
21104
21105var RequestBase = __webpack_require__(372);
21106
21107var isObject = __webpack_require__(190);
21108
21109var ResponseBase = __webpack_require__(373);
21110
21111var Agent = __webpack_require__(375);
21112/**
21113 * Noop.
21114 */
21115
21116function noop() {}
21117/**
21118 * Expose `request`.
21119 */
21120
21121module.exports = function (method, url) {
21122 // callback
21123 if (typeof url === 'function') {
21124 return new exports.Request('GET', method).end(url);
21125 } // url first
21126
21127
21128 if (arguments.length === 1) {
21129 return new exports.Request('GET', method);
21130 }
21131
21132 return new exports.Request(method, url);
21133};
21134
21135exports = module.exports;
21136var request = exports;
21137exports.Request = Request;
21138/**
21139 * Determine XHR.
21140 */
21141
21142request.getXHR = function () {
21143 if (root.XMLHttpRequest && (!root.location || root.location.protocol !== 'file:' || !root.ActiveXObject)) {
21144 return new XMLHttpRequest();
21145 }
21146
21147 try {
21148 return new ActiveXObject('Microsoft.XMLHTTP');
21149 } catch (_unused) {}
21150
21151 try {
21152 return new ActiveXObject('Msxml2.XMLHTTP.6.0');
21153 } catch (_unused2) {}
21154
21155 try {
21156 return new ActiveXObject('Msxml2.XMLHTTP.3.0');
21157 } catch (_unused3) {}
21158
21159 try {
21160 return new ActiveXObject('Msxml2.XMLHTTP');
21161 } catch (_unused4) {}
21162
21163 throw new Error('Browser-only version of superagent could not find XHR');
21164};
21165/**
21166 * Removes leading and trailing whitespace, added to support IE.
21167 *
21168 * @param {String} s
21169 * @return {String}
21170 * @api private
21171 */
21172
21173var trim = ''.trim ? function (s) {
21174 return s.trim();
21175} : function (s) {
21176 return s.replace(/(^\s*|\s*$)/g, '');
21177};
21178/**
21179 * Serialize the given `obj`.
21180 *
21181 * @param {Object} obj
21182 * @return {String}
21183 * @api private
21184 */
21185
21186function serialize(obj) {
21187 if (!isObject(obj)) return obj;
21188 var pairs = [];
21189
21190 for (var key in obj) {
21191 if (Object.prototype.hasOwnProperty.call(obj, key)) pushEncodedKeyValuePair(pairs, key, obj[key]);
21192 }
21193
21194 return pairs.join('&');
21195}
21196/**
21197 * Helps 'serialize' with serializing arrays.
21198 * Mutates the pairs array.
21199 *
21200 * @param {Array} pairs
21201 * @param {String} key
21202 * @param {Mixed} val
21203 */
21204
21205function pushEncodedKeyValuePair(pairs, key, val) {
21206 if (val === undefined) return;
21207
21208 if (val === null) {
21209 pairs.push(encodeURI(key));
21210 return;
21211 }
21212
21213 if (Array.isArray(val)) {
21214 val.forEach(function (v) {
21215 pushEncodedKeyValuePair(pairs, key, v);
21216 });
21217 } else if (isObject(val)) {
21218 for (var subkey in val) {
21219 if (Object.prototype.hasOwnProperty.call(val, subkey)) pushEncodedKeyValuePair(pairs, "".concat(key, "[").concat(subkey, "]"), val[subkey]);
21220 }
21221 } else {
21222 pairs.push(encodeURI(key) + '=' + encodeURIComponent(val));
21223 }
21224}
21225/**
21226 * Expose serialization method.
21227 */
21228
21229request.serializeObject = serialize;
21230/**
21231 * Parse the given x-www-form-urlencoded `str`.
21232 *
21233 * @param {String} str
21234 * @return {Object}
21235 * @api private
21236 */
21237
21238function parseString(str) {
21239 var obj = {};
21240 var pairs = str.split('&');
21241 var pair;
21242 var pos;
21243
21244 for (var i = 0, len = pairs.length; i < len; ++i) {
21245 pair = pairs[i];
21246 pos = pair.indexOf('=');
21247
21248 if (pos === -1) {
21249 obj[decodeURIComponent(pair)] = '';
21250 } else {
21251 obj[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1));
21252 }
21253 }
21254
21255 return obj;
21256}
21257/**
21258 * Expose parser.
21259 */
21260
21261request.parseString = parseString;
21262/**
21263 * Default MIME type map.
21264 *
21265 * superagent.types.xml = 'application/xml';
21266 *
21267 */
21268
21269request.types = {
21270 html: 'text/html',
21271 json: 'application/json',
21272 xml: 'text/xml',
21273 urlencoded: 'application/x-www-form-urlencoded',
21274 form: 'application/x-www-form-urlencoded',
21275 'form-data': 'application/x-www-form-urlencoded'
21276};
21277/**
21278 * Default serialization map.
21279 *
21280 * superagent.serialize['application/xml'] = function(obj){
21281 * return 'generated xml here';
21282 * };
21283 *
21284 */
21285
21286request.serialize = {
21287 'application/x-www-form-urlencoded': serialize,
21288 'application/json': safeStringify
21289};
21290/**
21291 * Default parsers.
21292 *
21293 * superagent.parse['application/xml'] = function(str){
21294 * return { object parsed from str };
21295 * };
21296 *
21297 */
21298
21299request.parse = {
21300 'application/x-www-form-urlencoded': parseString,
21301 'application/json': JSON.parse
21302};
21303/**
21304 * Parse the given header `str` into
21305 * an object containing the mapped fields.
21306 *
21307 * @param {String} str
21308 * @return {Object}
21309 * @api private
21310 */
21311
21312function parseHeader(str) {
21313 var lines = str.split(/\r?\n/);
21314 var fields = {};
21315 var index;
21316 var line;
21317 var field;
21318 var val;
21319
21320 for (var i = 0, len = lines.length; i < len; ++i) {
21321 line = lines[i];
21322 index = line.indexOf(':');
21323
21324 if (index === -1) {
21325 // could be empty line, just skip it
21326 continue;
21327 }
21328
21329 field = line.slice(0, index).toLowerCase();
21330 val = trim(line.slice(index + 1));
21331 fields[field] = val;
21332 }
21333
21334 return fields;
21335}
21336/**
21337 * Check if `mime` is json or has +json structured syntax suffix.
21338 *
21339 * @param {String} mime
21340 * @return {Boolean}
21341 * @api private
21342 */
21343
21344function isJSON(mime) {
21345 // should match /json or +json
21346 // but not /json-seq
21347 return (/[/+]json($|[^-\w])/.test(mime)
21348 );
21349}
21350/**
21351 * Initialize a new `Response` with the given `xhr`.
21352 *
21353 * - set flags (.ok, .error, etc)
21354 * - parse header
21355 *
21356 * Examples:
21357 *
21358 * Aliasing `superagent` as `request` is nice:
21359 *
21360 * request = superagent;
21361 *
21362 * We can use the promise-like API, or pass callbacks:
21363 *
21364 * request.get('/').end(function(res){});
21365 * request.get('/', function(res){});
21366 *
21367 * Sending data can be chained:
21368 *
21369 * request
21370 * .post('/user')
21371 * .send({ name: 'tj' })
21372 * .end(function(res){});
21373 *
21374 * Or passed to `.send()`:
21375 *
21376 * request
21377 * .post('/user')
21378 * .send({ name: 'tj' }, function(res){});
21379 *
21380 * Or passed to `.post()`:
21381 *
21382 * request
21383 * .post('/user', { name: 'tj' })
21384 * .end(function(res){});
21385 *
21386 * Or further reduced to a single call for simple cases:
21387 *
21388 * request
21389 * .post('/user', { name: 'tj' }, function(res){});
21390 *
21391 * @param {XMLHTTPRequest} xhr
21392 * @param {Object} options
21393 * @api private
21394 */
21395
21396function Response(req) {
21397 this.req = req;
21398 this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers
21399
21400 this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null;
21401 this.statusText = this.req.xhr.statusText;
21402 var status = this.xhr.status; // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
21403
21404 if (status === 1223) {
21405 status = 204;
21406 }
21407
21408 this._setStatusProperties(status);
21409
21410 this.headers = parseHeader(this.xhr.getAllResponseHeaders());
21411 this.header = this.headers; // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
21412 // getResponseHeader still works. so we get content-type even if getting
21413 // other headers fails.
21414
21415 this.header['content-type'] = this.xhr.getResponseHeader('content-type');
21416
21417 this._setHeaderProperties(this.header);
21418
21419 if (this.text === null && req._responseType) {
21420 this.body = this.xhr.response;
21421 } else {
21422 this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response);
21423 }
21424} // eslint-disable-next-line new-cap
21425
21426
21427ResponseBase(Response.prototype);
21428/**
21429 * Parse the given body `str`.
21430 *
21431 * Used for auto-parsing of bodies. Parsers
21432 * are defined on the `superagent.parse` object.
21433 *
21434 * @param {String} str
21435 * @return {Mixed}
21436 * @api private
21437 */
21438
21439Response.prototype._parseBody = function (str) {
21440 var parse = request.parse[this.type];
21441
21442 if (this.req._parser) {
21443 return this.req._parser(this, str);
21444 }
21445
21446 if (!parse && isJSON(this.type)) {
21447 parse = request.parse['application/json'];
21448 }
21449
21450 return parse && str && (str.length > 0 || str instanceof Object) ? parse(str) : null;
21451};
21452/**
21453 * Return an `Error` representative of this response.
21454 *
21455 * @return {Error}
21456 * @api public
21457 */
21458
21459Response.prototype.toError = function () {
21460 var req = this.req;
21461 var method = req.method;
21462 var url = req.url;
21463 var msg = "cannot ".concat(method, " ").concat(url, " (").concat(this.status, ")");
21464 var err = new Error(msg);
21465 err.status = this.status;
21466 err.method = method;
21467 err.url = url;
21468 return err;
21469};
21470/**
21471 * Expose `Response`.
21472 */
21473
21474request.Response = Response;
21475/**
21476 * Initialize a new `Request` with the given `method` and `url`.
21477 *
21478 * @param {String} method
21479 * @param {String} url
21480 * @api public
21481 */
21482
21483function Request(method, url) {
21484 var self = this;
21485 this._query = this._query || [];
21486 this.method = method;
21487 this.url = url;
21488 this.header = {}; // preserves header name case
21489
21490 this._header = {}; // coerces header names to lowercase
21491
21492 this.on('end', function () {
21493 var err = null;
21494 var res = null;
21495
21496 try {
21497 res = new Response(self);
21498 } catch (err_) {
21499 err = new Error('Parser is unable to parse the response');
21500 err.parse = true;
21501 err.original = err_; // issue #675: return the raw response if the response parsing fails
21502
21503 if (self.xhr) {
21504 // ie9 doesn't have 'response' property
21505 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
21506
21507 err.status = self.xhr.status ? self.xhr.status : null;
21508 err.statusCode = err.status; // backwards-compat only
21509 } else {
21510 err.rawResponse = null;
21511 err.status = null;
21512 }
21513
21514 return self.callback(err);
21515 }
21516
21517 self.emit('response', res);
21518 var new_err;
21519
21520 try {
21521 if (!self._isResponseOK(res)) {
21522 new_err = new Error(res.statusText || res.text || 'Unsuccessful HTTP response');
21523 }
21524 } catch (err_) {
21525 new_err = err_; // ok() callback can throw
21526 } // #1000 don't catch errors from the callback to avoid double calling it
21527
21528
21529 if (new_err) {
21530 new_err.original = err;
21531 new_err.response = res;
21532 new_err.status = res.status;
21533 self.callback(new_err, res);
21534 } else {
21535 self.callback(null, res);
21536 }
21537 });
21538}
21539/**
21540 * Mixin `Emitter` and `RequestBase`.
21541 */
21542// eslint-disable-next-line new-cap
21543
21544
21545Emitter(Request.prototype); // eslint-disable-next-line new-cap
21546
21547RequestBase(Request.prototype);
21548/**
21549 * Set Content-Type to `type`, mapping values from `request.types`.
21550 *
21551 * Examples:
21552 *
21553 * superagent.types.xml = 'application/xml';
21554 *
21555 * request.post('/')
21556 * .type('xml')
21557 * .send(xmlstring)
21558 * .end(callback);
21559 *
21560 * request.post('/')
21561 * .type('application/xml')
21562 * .send(xmlstring)
21563 * .end(callback);
21564 *
21565 * @param {String} type
21566 * @return {Request} for chaining
21567 * @api public
21568 */
21569
21570Request.prototype.type = function (type) {
21571 this.set('Content-Type', request.types[type] || type);
21572 return this;
21573};
21574/**
21575 * Set Accept to `type`, mapping values from `request.types`.
21576 *
21577 * Examples:
21578 *
21579 * superagent.types.json = 'application/json';
21580 *
21581 * request.get('/agent')
21582 * .accept('json')
21583 * .end(callback);
21584 *
21585 * request.get('/agent')
21586 * .accept('application/json')
21587 * .end(callback);
21588 *
21589 * @param {String} accept
21590 * @return {Request} for chaining
21591 * @api public
21592 */
21593
21594Request.prototype.accept = function (type) {
21595 this.set('Accept', request.types[type] || type);
21596 return this;
21597};
21598/**
21599 * Set Authorization field value with `user` and `pass`.
21600 *
21601 * @param {String} user
21602 * @param {String} [pass] optional in case of using 'bearer' as type
21603 * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')
21604 * @return {Request} for chaining
21605 * @api public
21606 */
21607
21608Request.prototype.auth = function (user, pass, options) {
21609 if (arguments.length === 1) pass = '';
21610
21611 if (_typeof(pass) === 'object' && pass !== null) {
21612 // pass is optional and can be replaced with options
21613 options = pass;
21614 pass = '';
21615 }
21616
21617 if (!options) {
21618 options = {
21619 type: typeof btoa === 'function' ? 'basic' : 'auto'
21620 };
21621 }
21622
21623 var encoder = function encoder(string) {
21624 if (typeof btoa === 'function') {
21625 return btoa(string);
21626 }
21627
21628 throw new Error('Cannot use basic auth, btoa is not a function');
21629 };
21630
21631 return this._auth(user, pass, options, encoder);
21632};
21633/**
21634 * Add query-string `val`.
21635 *
21636 * Examples:
21637 *
21638 * request.get('/shoes')
21639 * .query('size=10')
21640 * .query({ color: 'blue' })
21641 *
21642 * @param {Object|String} val
21643 * @return {Request} for chaining
21644 * @api public
21645 */
21646
21647Request.prototype.query = function (val) {
21648 if (typeof val !== 'string') val = serialize(val);
21649 if (val) this._query.push(val);
21650 return this;
21651};
21652/**
21653 * Queue the given `file` as an attachment to the specified `field`,
21654 * with optional `options` (or filename).
21655 *
21656 * ``` js
21657 * request.post('/upload')
21658 * .attach('content', new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
21659 * .end(callback);
21660 * ```
21661 *
21662 * @param {String} field
21663 * @param {Blob|File} file
21664 * @param {String|Object} options
21665 * @return {Request} for chaining
21666 * @api public
21667 */
21668
21669Request.prototype.attach = function (field, file, options) {
21670 if (file) {
21671 if (this._data) {
21672 throw new Error("superagent can't mix .send() and .attach()");
21673 }
21674
21675 this._getFormData().append(field, file, options || file.name);
21676 }
21677
21678 return this;
21679};
21680
21681Request.prototype._getFormData = function () {
21682 if (!this._formData) {
21683 this._formData = new root.FormData();
21684 }
21685
21686 return this._formData;
21687};
21688/**
21689 * Invoke the callback with `err` and `res`
21690 * and handle arity check.
21691 *
21692 * @param {Error} err
21693 * @param {Response} res
21694 * @api private
21695 */
21696
21697Request.prototype.callback = function (err, res) {
21698 if (this._shouldRetry(err, res)) {
21699 return this._retry();
21700 }
21701
21702 var fn = this._callback;
21703 this.clearTimeout();
21704
21705 if (err) {
21706 if (this._maxRetries) err.retries = this._retries - 1;
21707 this.emit('error', err);
21708 }
21709
21710 fn(err, res);
21711};
21712/**
21713 * Invoke callback with x-domain error.
21714 *
21715 * @api private
21716 */
21717
21718Request.prototype.crossDomainError = function () {
21719 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.');
21720 err.crossDomain = true;
21721 err.status = this.status;
21722 err.method = this.method;
21723 err.url = this.url;
21724 this.callback(err);
21725}; // This only warns, because the request is still likely to work
21726
21727
21728Request.prototype.agent = function () {
21729 console.warn('This is not supported in browser version of superagent');
21730 return this;
21731};
21732
21733Request.prototype.ca = Request.prototype.agent;
21734Request.prototype.buffer = Request.prototype.ca; // This throws, because it can't send/receive data as expected
21735
21736Request.prototype.write = function () {
21737 throw new Error('Streaming is not supported in browser version of superagent');
21738};
21739
21740Request.prototype.pipe = Request.prototype.write;
21741/**
21742 * Check if `obj` is a host object,
21743 * we don't want to serialize these :)
21744 *
21745 * @param {Object} obj host object
21746 * @return {Boolean} is a host object
21747 * @api private
21748 */
21749
21750Request.prototype._isHost = function (obj) {
21751 // Native objects stringify to [object File], [object Blob], [object FormData], etc.
21752 return obj && _typeof(obj) === 'object' && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';
21753};
21754/**
21755 * Initiate request, invoking callback `fn(res)`
21756 * with an instanceof `Response`.
21757 *
21758 * @param {Function} fn
21759 * @return {Request} for chaining
21760 * @api public
21761 */
21762
21763Request.prototype.end = function (fn) {
21764 if (this._endCalled) {
21765 console.warn('Warning: .end() was called twice. This is not supported in superagent');
21766 }
21767
21768 this._endCalled = true; // store callback
21769
21770 this._callback = fn || noop; // querystring
21771
21772 this._finalizeQueryString();
21773
21774 this._end();
21775};
21776
21777Request.prototype._setUploadTimeout = function () {
21778 var self = this; // upload timeout it's wokrs only if deadline timeout is off
21779
21780 if (this._uploadTimeout && !this._uploadTimeoutTimer) {
21781 this._uploadTimeoutTimer = setTimeout(function () {
21782 self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT');
21783 }, this._uploadTimeout);
21784 }
21785}; // eslint-disable-next-line complexity
21786
21787
21788Request.prototype._end = function () {
21789 if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called'));
21790 var self = this;
21791 this.xhr = request.getXHR();
21792 var xhr = this.xhr;
21793 var data = this._formData || this._data;
21794
21795 this._setTimeouts(); // state change
21796
21797
21798 xhr.onreadystatechange = function () {
21799 var readyState = xhr.readyState;
21800
21801 if (readyState >= 2 && self._responseTimeoutTimer) {
21802 clearTimeout(self._responseTimeoutTimer);
21803 }
21804
21805 if (readyState !== 4) {
21806 return;
21807 } // In IE9, reads to any property (e.g. status) off of an aborted XHR will
21808 // result in the error "Could not complete the operation due to error c00c023f"
21809
21810
21811 var status;
21812
21813 try {
21814 status = xhr.status;
21815 } catch (_unused5) {
21816 status = 0;
21817 }
21818
21819 if (!status) {
21820 if (self.timedout || self._aborted) return;
21821 return self.crossDomainError();
21822 }
21823
21824 self.emit('end');
21825 }; // progress
21826
21827
21828 var handleProgress = function handleProgress(direction, e) {
21829 if (e.total > 0) {
21830 e.percent = e.loaded / e.total * 100;
21831
21832 if (e.percent === 100) {
21833 clearTimeout(self._uploadTimeoutTimer);
21834 }
21835 }
21836
21837 e.direction = direction;
21838 self.emit('progress', e);
21839 };
21840
21841 if (this.hasListeners('progress')) {
21842 try {
21843 xhr.addEventListener('progress', handleProgress.bind(null, 'download'));
21844
21845 if (xhr.upload) {
21846 xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload'));
21847 }
21848 } catch (_unused6) {// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.
21849 // Reported here:
21850 // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context
21851 }
21852 }
21853
21854 if (xhr.upload) {
21855 this._setUploadTimeout();
21856 } // initiate request
21857
21858
21859 try {
21860 if (this.username && this.password) {
21861 xhr.open(this.method, this.url, true, this.username, this.password);
21862 } else {
21863 xhr.open(this.method, this.url, true);
21864 }
21865 } catch (err) {
21866 // see #1149
21867 return this.callback(err);
21868 } // CORS
21869
21870
21871 if (this._withCredentials) xhr.withCredentials = true; // body
21872
21873 if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) {
21874 // serialize stuff
21875 var contentType = this._header['content-type'];
21876
21877 var _serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];
21878
21879 if (!_serialize && isJSON(contentType)) {
21880 _serialize = request.serialize['application/json'];
21881 }
21882
21883 if (_serialize) data = _serialize(data);
21884 } // set header fields
21885
21886
21887 for (var field in this.header) {
21888 if (this.header[field] === null) continue;
21889 if (Object.prototype.hasOwnProperty.call(this.header, field)) xhr.setRequestHeader(field, this.header[field]);
21890 }
21891
21892 if (this._responseType) {
21893 xhr.responseType = this._responseType;
21894 } // send stuff
21895
21896
21897 this.emit('request', this); // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)
21898 // We need null here if data is undefined
21899
21900 xhr.send(typeof data === 'undefined' ? null : data);
21901};
21902
21903request.agent = function () {
21904 return new Agent();
21905};
21906
21907['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE'].forEach(function (method) {
21908 Agent.prototype[method.toLowerCase()] = function (url, fn) {
21909 var req = new request.Request(method, url);
21910
21911 this._setDefaults(req);
21912
21913 if (fn) {
21914 req.end(fn);
21915 }
21916
21917 return req;
21918 };
21919});
21920Agent.prototype.del = Agent.prototype.delete;
21921/**
21922 * GET `url` with optional callback `fn(res)`.
21923 *
21924 * @param {String} url
21925 * @param {Mixed|Function} [data] or fn
21926 * @param {Function} [fn]
21927 * @return {Request}
21928 * @api public
21929 */
21930
21931request.get = function (url, data, fn) {
21932 var req = request('GET', url);
21933
21934 if (typeof data === 'function') {
21935 fn = data;
21936 data = null;
21937 }
21938
21939 if (data) req.query(data);
21940 if (fn) req.end(fn);
21941 return req;
21942};
21943/**
21944 * HEAD `url` with optional callback `fn(res)`.
21945 *
21946 * @param {String} url
21947 * @param {Mixed|Function} [data] or fn
21948 * @param {Function} [fn]
21949 * @return {Request}
21950 * @api public
21951 */
21952
21953request.head = function (url, data, fn) {
21954 var req = request('HEAD', url);
21955
21956 if (typeof data === 'function') {
21957 fn = data;
21958 data = null;
21959 }
21960
21961 if (data) req.query(data);
21962 if (fn) req.end(fn);
21963 return req;
21964};
21965/**
21966 * OPTIONS query to `url` with optional callback `fn(res)`.
21967 *
21968 * @param {String} url
21969 * @param {Mixed|Function} [data] or fn
21970 * @param {Function} [fn]
21971 * @return {Request}
21972 * @api public
21973 */
21974
21975request.options = function (url, data, fn) {
21976 var req = request('OPTIONS', url);
21977
21978 if (typeof data === 'function') {
21979 fn = data;
21980 data = null;
21981 }
21982
21983 if (data) req.send(data);
21984 if (fn) req.end(fn);
21985 return req;
21986};
21987/**
21988 * DELETE `url` with optional `data` and callback `fn(res)`.
21989 *
21990 * @param {String} url
21991 * @param {Mixed} [data]
21992 * @param {Function} [fn]
21993 * @return {Request}
21994 * @api public
21995 */
21996
21997function del(url, data, fn) {
21998 var req = request('DELETE', url);
21999
22000 if (typeof data === 'function') {
22001 fn = data;
22002 data = null;
22003 }
22004
22005 if (data) req.send(data);
22006 if (fn) req.end(fn);
22007 return req;
22008}
22009
22010request.del = del;
22011request.delete = del;
22012/**
22013 * PATCH `url` with optional `data` and callback `fn(res)`.
22014 *
22015 * @param {String} url
22016 * @param {Mixed} [data]
22017 * @param {Function} [fn]
22018 * @return {Request}
22019 * @api public
22020 */
22021
22022request.patch = function (url, data, fn) {
22023 var req = request('PATCH', url);
22024
22025 if (typeof data === 'function') {
22026 fn = data;
22027 data = null;
22028 }
22029
22030 if (data) req.send(data);
22031 if (fn) req.end(fn);
22032 return req;
22033};
22034/**
22035 * POST `url` with optional `data` and callback `fn(res)`.
22036 *
22037 * @param {String} url
22038 * @param {Mixed} [data]
22039 * @param {Function} [fn]
22040 * @return {Request}
22041 * @api public
22042 */
22043
22044request.post = function (url, data, fn) {
22045 var req = request('POST', url);
22046
22047 if (typeof data === 'function') {
22048 fn = data;
22049 data = null;
22050 }
22051
22052 if (data) req.send(data);
22053 if (fn) req.end(fn);
22054 return req;
22055};
22056/**
22057 * PUT `url` with optional `data` and callback `fn(res)`.
22058 *
22059 * @param {String} url
22060 * @param {Mixed|Function} [data] or fn
22061 * @param {Function} [fn]
22062 * @return {Request}
22063 * @api public
22064 */
22065
22066request.put = function (url, data, fn) {
22067 var req = request('PUT', url);
22068
22069 if (typeof data === 'function') {
22070 fn = data;
22071 data = null;
22072 }
22073
22074 if (data) req.send(data);
22075 if (fn) req.end(fn);
22076 return req;
22077};
22078
22079/***/ }),
22080/* 370 */
22081/***/ (function(module, exports, __webpack_require__) {
22082
22083
22084/**
22085 * Expose `Emitter`.
22086 */
22087
22088if (true) {
22089 module.exports = Emitter;
22090}
22091
22092/**
22093 * Initialize a new `Emitter`.
22094 *
22095 * @api public
22096 */
22097
22098function Emitter(obj) {
22099 if (obj) return mixin(obj);
22100};
22101
22102/**
22103 * Mixin the emitter properties.
22104 *
22105 * @param {Object} obj
22106 * @return {Object}
22107 * @api private
22108 */
22109
22110function mixin(obj) {
22111 for (var key in Emitter.prototype) {
22112 obj[key] = Emitter.prototype[key];
22113 }
22114 return obj;
22115}
22116
22117/**
22118 * Listen on the given `event` with `fn`.
22119 *
22120 * @param {String} event
22121 * @param {Function} fn
22122 * @return {Emitter}
22123 * @api public
22124 */
22125
22126Emitter.prototype.on =
22127Emitter.prototype.addEventListener = function(event, fn){
22128 this._callbacks = this._callbacks || {};
22129 (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
22130 .push(fn);
22131 return this;
22132};
22133
22134/**
22135 * Adds an `event` listener that will be invoked a single
22136 * time then automatically removed.
22137 *
22138 * @param {String} event
22139 * @param {Function} fn
22140 * @return {Emitter}
22141 * @api public
22142 */
22143
22144Emitter.prototype.once = function(event, fn){
22145 function on() {
22146 this.off(event, on);
22147 fn.apply(this, arguments);
22148 }
22149
22150 on.fn = fn;
22151 this.on(event, on);
22152 return this;
22153};
22154
22155/**
22156 * Remove the given callback for `event` or all
22157 * registered callbacks.
22158 *
22159 * @param {String} event
22160 * @param {Function} fn
22161 * @return {Emitter}
22162 * @api public
22163 */
22164
22165Emitter.prototype.off =
22166Emitter.prototype.removeListener =
22167Emitter.prototype.removeAllListeners =
22168Emitter.prototype.removeEventListener = function(event, fn){
22169 this._callbacks = this._callbacks || {};
22170
22171 // all
22172 if (0 == arguments.length) {
22173 this._callbacks = {};
22174 return this;
22175 }
22176
22177 // specific event
22178 var callbacks = this._callbacks['$' + event];
22179 if (!callbacks) return this;
22180
22181 // remove all handlers
22182 if (1 == arguments.length) {
22183 delete this._callbacks['$' + event];
22184 return this;
22185 }
22186
22187 // remove specific handler
22188 var cb;
22189 for (var i = 0; i < callbacks.length; i++) {
22190 cb = callbacks[i];
22191 if (cb === fn || cb.fn === fn) {
22192 callbacks.splice(i, 1);
22193 break;
22194 }
22195 }
22196
22197 // Remove event specific arrays for event types that no
22198 // one is subscribed for to avoid memory leak.
22199 if (callbacks.length === 0) {
22200 delete this._callbacks['$' + event];
22201 }
22202
22203 return this;
22204};
22205
22206/**
22207 * Emit `event` with the given args.
22208 *
22209 * @param {String} event
22210 * @param {Mixed} ...
22211 * @return {Emitter}
22212 */
22213
22214Emitter.prototype.emit = function(event){
22215 this._callbacks = this._callbacks || {};
22216
22217 var args = new Array(arguments.length - 1)
22218 , callbacks = this._callbacks['$' + event];
22219
22220 for (var i = 1; i < arguments.length; i++) {
22221 args[i - 1] = arguments[i];
22222 }
22223
22224 if (callbacks) {
22225 callbacks = callbacks.slice(0);
22226 for (var i = 0, len = callbacks.length; i < len; ++i) {
22227 callbacks[i].apply(this, args);
22228 }
22229 }
22230
22231 return this;
22232};
22233
22234/**
22235 * Return array of callbacks for `event`.
22236 *
22237 * @param {String} event
22238 * @return {Array}
22239 * @api public
22240 */
22241
22242Emitter.prototype.listeners = function(event){
22243 this._callbacks = this._callbacks || {};
22244 return this._callbacks['$' + event] || [];
22245};
22246
22247/**
22248 * Check if this emitter has `event` handlers.
22249 *
22250 * @param {String} event
22251 * @return {Boolean}
22252 * @api public
22253 */
22254
22255Emitter.prototype.hasListeners = function(event){
22256 return !! this.listeners(event).length;
22257};
22258
22259
22260/***/ }),
22261/* 371 */
22262/***/ (function(module, exports) {
22263
22264module.exports = stringify
22265stringify.default = stringify
22266stringify.stable = deterministicStringify
22267stringify.stableStringify = deterministicStringify
22268
22269var arr = []
22270var replacerStack = []
22271
22272// Regular stringify
22273function stringify (obj, replacer, spacer) {
22274 decirc(obj, '', [], undefined)
22275 var res
22276 if (replacerStack.length === 0) {
22277 res = JSON.stringify(obj, replacer, spacer)
22278 } else {
22279 res = JSON.stringify(obj, replaceGetterValues(replacer), spacer)
22280 }
22281 while (arr.length !== 0) {
22282 var part = arr.pop()
22283 if (part.length === 4) {
22284 Object.defineProperty(part[0], part[1], part[3])
22285 } else {
22286 part[0][part[1]] = part[2]
22287 }
22288 }
22289 return res
22290}
22291function decirc (val, k, stack, parent) {
22292 var i
22293 if (typeof val === 'object' && val !== null) {
22294 for (i = 0; i < stack.length; i++) {
22295 if (stack[i] === val) {
22296 var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)
22297 if (propertyDescriptor.get !== undefined) {
22298 if (propertyDescriptor.configurable) {
22299 Object.defineProperty(parent, k, { value: '[Circular]' })
22300 arr.push([parent, k, val, propertyDescriptor])
22301 } else {
22302 replacerStack.push([val, k])
22303 }
22304 } else {
22305 parent[k] = '[Circular]'
22306 arr.push([parent, k, val])
22307 }
22308 return
22309 }
22310 }
22311 stack.push(val)
22312 // Optimize for Arrays. Big arrays could kill the performance otherwise!
22313 if (Array.isArray(val)) {
22314 for (i = 0; i < val.length; i++) {
22315 decirc(val[i], i, stack, val)
22316 }
22317 } else {
22318 var keys = Object.keys(val)
22319 for (i = 0; i < keys.length; i++) {
22320 var key = keys[i]
22321 decirc(val[key], key, stack, val)
22322 }
22323 }
22324 stack.pop()
22325 }
22326}
22327
22328// Stable-stringify
22329function compareFunction (a, b) {
22330 if (a < b) {
22331 return -1
22332 }
22333 if (a > b) {
22334 return 1
22335 }
22336 return 0
22337}
22338
22339function deterministicStringify (obj, replacer, spacer) {
22340 var tmp = deterministicDecirc(obj, '', [], undefined) || obj
22341 var res
22342 if (replacerStack.length === 0) {
22343 res = JSON.stringify(tmp, replacer, spacer)
22344 } else {
22345 res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer)
22346 }
22347 while (arr.length !== 0) {
22348 var part = arr.pop()
22349 if (part.length === 4) {
22350 Object.defineProperty(part[0], part[1], part[3])
22351 } else {
22352 part[0][part[1]] = part[2]
22353 }
22354 }
22355 return res
22356}
22357
22358function deterministicDecirc (val, k, stack, parent) {
22359 var i
22360 if (typeof val === 'object' && val !== null) {
22361 for (i = 0; i < stack.length; i++) {
22362 if (stack[i] === val) {
22363 var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)
22364 if (propertyDescriptor.get !== undefined) {
22365 if (propertyDescriptor.configurable) {
22366 Object.defineProperty(parent, k, { value: '[Circular]' })
22367 arr.push([parent, k, val, propertyDescriptor])
22368 } else {
22369 replacerStack.push([val, k])
22370 }
22371 } else {
22372 parent[k] = '[Circular]'
22373 arr.push([parent, k, val])
22374 }
22375 return
22376 }
22377 }
22378 if (typeof val.toJSON === 'function') {
22379 return
22380 }
22381 stack.push(val)
22382 // Optimize for Arrays. Big arrays could kill the performance otherwise!
22383 if (Array.isArray(val)) {
22384 for (i = 0; i < val.length; i++) {
22385 deterministicDecirc(val[i], i, stack, val)
22386 }
22387 } else {
22388 // Create a temporary object in the required way
22389 var tmp = {}
22390 var keys = Object.keys(val).sort(compareFunction)
22391 for (i = 0; i < keys.length; i++) {
22392 var key = keys[i]
22393 deterministicDecirc(val[key], key, stack, val)
22394 tmp[key] = val[key]
22395 }
22396 if (parent !== undefined) {
22397 arr.push([parent, k, val])
22398 parent[k] = tmp
22399 } else {
22400 return tmp
22401 }
22402 }
22403 stack.pop()
22404 }
22405}
22406
22407// wraps replacer function to handle values we couldn't replace
22408// and mark them as [Circular]
22409function replaceGetterValues (replacer) {
22410 replacer = replacer !== undefined ? replacer : function (k, v) { return v }
22411 return function (key, val) {
22412 if (replacerStack.length > 0) {
22413 for (var i = 0; i < replacerStack.length; i++) {
22414 var part = replacerStack[i]
22415 if (part[1] === key && part[0] === val) {
22416 val = '[Circular]'
22417 replacerStack.splice(i, 1)
22418 break
22419 }
22420 }
22421 }
22422 return replacer.call(this, key, val)
22423 }
22424}
22425
22426
22427/***/ }),
22428/* 372 */
22429/***/ (function(module, exports, __webpack_require__) {
22430
22431"use strict";
22432
22433
22434var _promise = __webpack_require__(3);
22435
22436var _promise2 = _interopRequireDefault(_promise);
22437
22438var _iterator = __webpack_require__(73);
22439
22440var _iterator2 = _interopRequireDefault(_iterator);
22441
22442var _typeof3 = __webpack_require__(23);
22443
22444var _typeof4 = _interopRequireDefault(_typeof3);
22445
22446var _symbol = __webpack_require__(44);
22447
22448var _symbol2 = _interopRequireDefault(_symbol);
22449
22450function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
22451
22452function _typeof(obj) {
22453 "@babel/helpers - typeof";
22454 if (typeof _symbol2.default === "function" && (0, _typeof4.default)(_iterator2.default) === "symbol") {
22455 _typeof = function _typeof(obj) {
22456 return typeof obj === "undefined" ? "undefined" : (0, _typeof4.default)(obj);
22457 };
22458 } else {
22459 _typeof = function _typeof(obj) {
22460 return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : (0, _typeof4.default)(obj);
22461 };
22462 }return _typeof(obj);
22463}
22464
22465/**
22466 * Module of mixed-in functions shared between node and client code
22467 */
22468var isObject = __webpack_require__(190);
22469/**
22470 * Expose `RequestBase`.
22471 */
22472
22473module.exports = RequestBase;
22474/**
22475 * Initialize a new `RequestBase`.
22476 *
22477 * @api public
22478 */
22479
22480function RequestBase(obj) {
22481 if (obj) return mixin(obj);
22482}
22483/**
22484 * Mixin the prototype properties.
22485 *
22486 * @param {Object} obj
22487 * @return {Object}
22488 * @api private
22489 */
22490
22491function mixin(obj) {
22492 for (var key in RequestBase.prototype) {
22493 if (Object.prototype.hasOwnProperty.call(RequestBase.prototype, key)) obj[key] = RequestBase.prototype[key];
22494 }
22495
22496 return obj;
22497}
22498/**
22499 * Clear previous timeout.
22500 *
22501 * @return {Request} for chaining
22502 * @api public
22503 */
22504
22505RequestBase.prototype.clearTimeout = function () {
22506 clearTimeout(this._timer);
22507 clearTimeout(this._responseTimeoutTimer);
22508 clearTimeout(this._uploadTimeoutTimer);
22509 delete this._timer;
22510 delete this._responseTimeoutTimer;
22511 delete this._uploadTimeoutTimer;
22512 return this;
22513};
22514/**
22515 * Override default response body parser
22516 *
22517 * This function will be called to convert incoming data into request.body
22518 *
22519 * @param {Function}
22520 * @api public
22521 */
22522
22523RequestBase.prototype.parse = function (fn) {
22524 this._parser = fn;
22525 return this;
22526};
22527/**
22528 * Set format of binary response body.
22529 * In browser valid formats are 'blob' and 'arraybuffer',
22530 * which return Blob and ArrayBuffer, respectively.
22531 *
22532 * In Node all values result in Buffer.
22533 *
22534 * Examples:
22535 *
22536 * req.get('/')
22537 * .responseType('blob')
22538 * .end(callback);
22539 *
22540 * @param {String} val
22541 * @return {Request} for chaining
22542 * @api public
22543 */
22544
22545RequestBase.prototype.responseType = function (val) {
22546 this._responseType = val;
22547 return this;
22548};
22549/**
22550 * Override default request body serializer
22551 *
22552 * This function will be called to convert data set via .send or .attach into payload to send
22553 *
22554 * @param {Function}
22555 * @api public
22556 */
22557
22558RequestBase.prototype.serialize = function (fn) {
22559 this._serializer = fn;
22560 return this;
22561};
22562/**
22563 * Set timeouts.
22564 *
22565 * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.
22566 * - 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.
22567 * - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off
22568 *
22569 * Value of 0 or false means no timeout.
22570 *
22571 * @param {Number|Object} ms or {response, deadline}
22572 * @return {Request} for chaining
22573 * @api public
22574 */
22575
22576RequestBase.prototype.timeout = function (options) {
22577 if (!options || _typeof(options) !== 'object') {
22578 this._timeout = options;
22579 this._responseTimeout = 0;
22580 this._uploadTimeout = 0;
22581 return this;
22582 }
22583
22584 for (var option in options) {
22585 if (Object.prototype.hasOwnProperty.call(options, option)) {
22586 switch (option) {
22587 case 'deadline':
22588 this._timeout = options.deadline;
22589 break;
22590
22591 case 'response':
22592 this._responseTimeout = options.response;
22593 break;
22594
22595 case 'upload':
22596 this._uploadTimeout = options.upload;
22597 break;
22598
22599 default:
22600 console.warn('Unknown timeout option', option);
22601 }
22602 }
22603 }
22604
22605 return this;
22606};
22607/**
22608 * Set number of retry attempts on error.
22609 *
22610 * Failed requests will be retried 'count' times if timeout or err.code >= 500.
22611 *
22612 * @param {Number} count
22613 * @param {Function} [fn]
22614 * @return {Request} for chaining
22615 * @api public
22616 */
22617
22618RequestBase.prototype.retry = function (count, fn) {
22619 // Default to 1 if no count passed or true
22620 if (arguments.length === 0 || count === true) count = 1;
22621 if (count <= 0) count = 0;
22622 this._maxRetries = count;
22623 this._retries = 0;
22624 this._retryCallback = fn;
22625 return this;
22626};
22627
22628var ERROR_CODES = ['ECONNRESET', 'ETIMEDOUT', 'EADDRINFO', 'ESOCKETTIMEDOUT'];
22629/**
22630 * Determine if a request should be retried.
22631 * (Borrowed from segmentio/superagent-retry)
22632 *
22633 * @param {Error} err an error
22634 * @param {Response} [res] response
22635 * @returns {Boolean} if segment should be retried
22636 */
22637
22638RequestBase.prototype._shouldRetry = function (err, res) {
22639 if (!this._maxRetries || this._retries++ >= this._maxRetries) {
22640 return false;
22641 }
22642
22643 if (this._retryCallback) {
22644 try {
22645 var override = this._retryCallback(err, res);
22646
22647 if (override === true) return true;
22648 if (override === false) return false; // undefined falls back to defaults
22649 } catch (err_) {
22650 console.error(err_);
22651 }
22652 }
22653
22654 if (res && res.status && res.status >= 500 && res.status !== 501) return true;
22655
22656 if (err) {
22657 if (err.code && ERROR_CODES.includes(err.code)) return true; // Superagent timeout
22658
22659 if (err.timeout && err.code === 'ECONNABORTED') return true;
22660 if (err.crossDomain) return true;
22661 }
22662
22663 return false;
22664};
22665/**
22666 * Retry request
22667 *
22668 * @return {Request} for chaining
22669 * @api private
22670 */
22671
22672RequestBase.prototype._retry = function () {
22673 this.clearTimeout(); // node
22674
22675 if (this.req) {
22676 this.req = null;
22677 this.req = this.request();
22678 }
22679
22680 this._aborted = false;
22681 this.timedout = false;
22682 this.timedoutError = null;
22683 return this._end();
22684};
22685/**
22686 * Promise support
22687 *
22688 * @param {Function} resolve
22689 * @param {Function} [reject]
22690 * @return {Request}
22691 */
22692
22693RequestBase.prototype.then = function (resolve, reject) {
22694 var _this = this;
22695
22696 if (!this._fullfilledPromise) {
22697 var self = this;
22698
22699 if (this._endCalled) {
22700 console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises');
22701 }
22702
22703 this._fullfilledPromise = new _promise2.default(function (resolve, reject) {
22704 self.on('abort', function () {
22705 if (_this._maxRetries && _this._maxRetries > _this._retries) {
22706 return;
22707 }
22708
22709 if (_this.timedout && _this.timedoutError) {
22710 reject(_this.timedoutError);
22711 return;
22712 }
22713
22714 var err = new Error('Aborted');
22715 err.code = 'ABORTED';
22716 err.status = _this.status;
22717 err.method = _this.method;
22718 err.url = _this.url;
22719 reject(err);
22720 });
22721 self.end(function (err, res) {
22722 if (err) reject(err);else resolve(res);
22723 });
22724 });
22725 }
22726
22727 return this._fullfilledPromise.then(resolve, reject);
22728};
22729
22730RequestBase.prototype.catch = function (cb) {
22731 return this.then(undefined, cb);
22732};
22733/**
22734 * Allow for extension
22735 */
22736
22737RequestBase.prototype.use = function (fn) {
22738 fn(this);
22739 return this;
22740};
22741
22742RequestBase.prototype.ok = function (cb) {
22743 if (typeof cb !== 'function') throw new Error('Callback required');
22744 this._okCallback = cb;
22745 return this;
22746};
22747
22748RequestBase.prototype._isResponseOK = function (res) {
22749 if (!res) {
22750 return false;
22751 }
22752
22753 if (this._okCallback) {
22754 return this._okCallback(res);
22755 }
22756
22757 return res.status >= 200 && res.status < 300;
22758};
22759/**
22760 * Get request header `field`.
22761 * Case-insensitive.
22762 *
22763 * @param {String} field
22764 * @return {String}
22765 * @api public
22766 */
22767
22768RequestBase.prototype.get = function (field) {
22769 return this._header[field.toLowerCase()];
22770};
22771/**
22772 * Get case-insensitive header `field` value.
22773 * This is a deprecated internal API. Use `.get(field)` instead.
22774 *
22775 * (getHeader is no longer used internally by the superagent code base)
22776 *
22777 * @param {String} field
22778 * @return {String}
22779 * @api private
22780 * @deprecated
22781 */
22782
22783RequestBase.prototype.getHeader = RequestBase.prototype.get;
22784/**
22785 * Set header `field` to `val`, or multiple fields with one object.
22786 * Case-insensitive.
22787 *
22788 * Examples:
22789 *
22790 * req.get('/')
22791 * .set('Accept', 'application/json')
22792 * .set('X-API-Key', 'foobar')
22793 * .end(callback);
22794 *
22795 * req.get('/')
22796 * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
22797 * .end(callback);
22798 *
22799 * @param {String|Object} field
22800 * @param {String} val
22801 * @return {Request} for chaining
22802 * @api public
22803 */
22804
22805RequestBase.prototype.set = function (field, val) {
22806 if (isObject(field)) {
22807 for (var key in field) {
22808 if (Object.prototype.hasOwnProperty.call(field, key)) this.set(key, field[key]);
22809 }
22810
22811 return this;
22812 }
22813
22814 this._header[field.toLowerCase()] = val;
22815 this.header[field] = val;
22816 return this;
22817};
22818/**
22819 * Remove header `field`.
22820 * Case-insensitive.
22821 *
22822 * Example:
22823 *
22824 * req.get('/')
22825 * .unset('User-Agent')
22826 * .end(callback);
22827 *
22828 * @param {String} field field name
22829 */
22830
22831RequestBase.prototype.unset = function (field) {
22832 delete this._header[field.toLowerCase()];
22833 delete this.header[field];
22834 return this;
22835};
22836/**
22837 * Write the field `name` and `val`, or multiple fields with one object
22838 * for "multipart/form-data" request bodies.
22839 *
22840 * ``` js
22841 * request.post('/upload')
22842 * .field('foo', 'bar')
22843 * .end(callback);
22844 *
22845 * request.post('/upload')
22846 * .field({ foo: 'bar', baz: 'qux' })
22847 * .end(callback);
22848 * ```
22849 *
22850 * @param {String|Object} name name of field
22851 * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field
22852 * @return {Request} for chaining
22853 * @api public
22854 */
22855
22856RequestBase.prototype.field = function (name, val) {
22857 // name should be either a string or an object.
22858 if (name === null || undefined === name) {
22859 throw new Error('.field(name, val) name can not be empty');
22860 }
22861
22862 if (this._data) {
22863 throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");
22864 }
22865
22866 if (isObject(name)) {
22867 for (var key in name) {
22868 if (Object.prototype.hasOwnProperty.call(name, key)) this.field(key, name[key]);
22869 }
22870
22871 return this;
22872 }
22873
22874 if (Array.isArray(val)) {
22875 for (var i in val) {
22876 if (Object.prototype.hasOwnProperty.call(val, i)) this.field(name, val[i]);
22877 }
22878
22879 return this;
22880 } // val should be defined now
22881
22882
22883 if (val === null || undefined === val) {
22884 throw new Error('.field(name, val) val can not be empty');
22885 }
22886
22887 if (typeof val === 'boolean') {
22888 val = String(val);
22889 }
22890
22891 this._getFormData().append(name, val);
22892
22893 return this;
22894};
22895/**
22896 * Abort the request, and clear potential timeout.
22897 *
22898 * @return {Request} request
22899 * @api public
22900 */
22901
22902RequestBase.prototype.abort = function () {
22903 if (this._aborted) {
22904 return this;
22905 }
22906
22907 this._aborted = true;
22908 if (this.xhr) this.xhr.abort(); // browser
22909
22910 if (this.req) this.req.abort(); // node
22911
22912 this.clearTimeout();
22913 this.emit('abort');
22914 return this;
22915};
22916
22917RequestBase.prototype._auth = function (user, pass, options, base64Encoder) {
22918 switch (options.type) {
22919 case 'basic':
22920 this.set('Authorization', "Basic ".concat(base64Encoder("".concat(user, ":").concat(pass))));
22921 break;
22922
22923 case 'auto':
22924 this.username = user;
22925 this.password = pass;
22926 break;
22927
22928 case 'bearer':
22929 // usage would be .auth(accessToken, { type: 'bearer' })
22930 this.set('Authorization', "Bearer ".concat(user));
22931 break;
22932
22933 default:
22934 break;
22935 }
22936
22937 return this;
22938};
22939/**
22940 * Enable transmission of cookies with x-domain requests.
22941 *
22942 * Note that for this to work the origin must not be
22943 * using "Access-Control-Allow-Origin" with a wildcard,
22944 * and also must set "Access-Control-Allow-Credentials"
22945 * to "true".
22946 *
22947 * @api public
22948 */
22949
22950RequestBase.prototype.withCredentials = function (on) {
22951 // This is browser-only functionality. Node side is no-op.
22952 if (on === undefined) on = true;
22953 this._withCredentials = on;
22954 return this;
22955};
22956/**
22957 * Set the max redirects to `n`. Does nothing in browser XHR implementation.
22958 *
22959 * @param {Number} n
22960 * @return {Request} for chaining
22961 * @api public
22962 */
22963
22964RequestBase.prototype.redirects = function (n) {
22965 this._maxRedirects = n;
22966 return this;
22967};
22968/**
22969 * Maximum size of buffered response body, in bytes. Counts uncompressed size.
22970 * Default 200MB.
22971 *
22972 * @param {Number} n number of bytes
22973 * @return {Request} for chaining
22974 */
22975
22976RequestBase.prototype.maxResponseSize = function (n) {
22977 if (typeof n !== 'number') {
22978 throw new TypeError('Invalid argument');
22979 }
22980
22981 this._maxResponseSize = n;
22982 return this;
22983};
22984/**
22985 * Convert to a plain javascript object (not JSON string) of scalar properties.
22986 * Note as this method is designed to return a useful non-this value,
22987 * it cannot be chained.
22988 *
22989 * @return {Object} describing method, url, and data of this request
22990 * @api public
22991 */
22992
22993RequestBase.prototype.toJSON = function () {
22994 return {
22995 method: this.method,
22996 url: this.url,
22997 data: this._data,
22998 headers: this._header
22999 };
23000};
23001/**
23002 * Send `data` as the request body, defaulting the `.type()` to "json" when
23003 * an object is given.
23004 *
23005 * Examples:
23006 *
23007 * // manual json
23008 * request.post('/user')
23009 * .type('json')
23010 * .send('{"name":"tj"}')
23011 * .end(callback)
23012 *
23013 * // auto json
23014 * request.post('/user')
23015 * .send({ name: 'tj' })
23016 * .end(callback)
23017 *
23018 * // manual x-www-form-urlencoded
23019 * request.post('/user')
23020 * .type('form')
23021 * .send('name=tj')
23022 * .end(callback)
23023 *
23024 * // auto x-www-form-urlencoded
23025 * request.post('/user')
23026 * .type('form')
23027 * .send({ name: 'tj' })
23028 * .end(callback)
23029 *
23030 * // defaults to x-www-form-urlencoded
23031 * request.post('/user')
23032 * .send('name=tobi')
23033 * .send('species=ferret')
23034 * .end(callback)
23035 *
23036 * @param {String|Object} data
23037 * @return {Request} for chaining
23038 * @api public
23039 */
23040// eslint-disable-next-line complexity
23041
23042
23043RequestBase.prototype.send = function (data) {
23044 var isObj = isObject(data);
23045 var type = this._header['content-type'];
23046
23047 if (this._formData) {
23048 throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");
23049 }
23050
23051 if (isObj && !this._data) {
23052 if (Array.isArray(data)) {
23053 this._data = [];
23054 } else if (!this._isHost(data)) {
23055 this._data = {};
23056 }
23057 } else if (data && this._data && this._isHost(this._data)) {
23058 throw new Error("Can't merge these send calls");
23059 } // merge
23060
23061
23062 if (isObj && isObject(this._data)) {
23063 for (var key in data) {
23064 if (Object.prototype.hasOwnProperty.call(data, key)) this._data[key] = data[key];
23065 }
23066 } else if (typeof data === 'string') {
23067 // default to x-www-form-urlencoded
23068 if (!type) this.type('form');
23069 type = this._header['content-type'];
23070
23071 if (type === 'application/x-www-form-urlencoded') {
23072 this._data = this._data ? "".concat(this._data, "&").concat(data) : data;
23073 } else {
23074 this._data = (this._data || '') + data;
23075 }
23076 } else {
23077 this._data = data;
23078 }
23079
23080 if (!isObj || this._isHost(data)) {
23081 return this;
23082 } // default to json
23083
23084
23085 if (!type) this.type('json');
23086 return this;
23087};
23088/**
23089 * Sort `querystring` by the sort function
23090 *
23091 *
23092 * Examples:
23093 *
23094 * // default order
23095 * request.get('/user')
23096 * .query('name=Nick')
23097 * .query('search=Manny')
23098 * .sortQuery()
23099 * .end(callback)
23100 *
23101 * // customized sort function
23102 * request.get('/user')
23103 * .query('name=Nick')
23104 * .query('search=Manny')
23105 * .sortQuery(function(a, b){
23106 * return a.length - b.length;
23107 * })
23108 * .end(callback)
23109 *
23110 *
23111 * @param {Function} sort
23112 * @return {Request} for chaining
23113 * @api public
23114 */
23115
23116RequestBase.prototype.sortQuery = function (sort) {
23117 // _sort default to true but otherwise can be a function or boolean
23118 this._sort = typeof sort === 'undefined' ? true : sort;
23119 return this;
23120};
23121/**
23122 * Compose querystring to append to req.url
23123 *
23124 * @api private
23125 */
23126
23127RequestBase.prototype._finalizeQueryString = function () {
23128 var query = this._query.join('&');
23129
23130 if (query) {
23131 this.url += (this.url.includes('?') ? '&' : '?') + query;
23132 }
23133
23134 this._query.length = 0; // Makes the call idempotent
23135
23136 if (this._sort) {
23137 var index = this.url.indexOf('?');
23138
23139 if (index >= 0) {
23140 var queryArr = this.url.slice(index + 1).split('&');
23141
23142 if (typeof this._sort === 'function') {
23143 queryArr.sort(this._sort);
23144 } else {
23145 queryArr.sort();
23146 }
23147
23148 this.url = this.url.slice(0, index) + '?' + queryArr.join('&');
23149 }
23150 }
23151}; // For backwards compat only
23152
23153
23154RequestBase.prototype._appendQueryString = function () {
23155 console.warn('Unsupported');
23156};
23157/**
23158 * Invoke callback with timeout error.
23159 *
23160 * @api private
23161 */
23162
23163RequestBase.prototype._timeoutError = function (reason, timeout, errno) {
23164 if (this._aborted) {
23165 return;
23166 }
23167
23168 var err = new Error("".concat(reason + timeout, "ms exceeded"));
23169 err.timeout = timeout;
23170 err.code = 'ECONNABORTED';
23171 err.errno = errno;
23172 this.timedout = true;
23173 this.timedoutError = err;
23174 this.abort();
23175 this.callback(err);
23176};
23177
23178RequestBase.prototype._setTimeouts = function () {
23179 var self = this; // deadline
23180
23181 if (this._timeout && !this._timer) {
23182 this._timer = setTimeout(function () {
23183 self._timeoutError('Timeout of ', self._timeout, 'ETIME');
23184 }, this._timeout);
23185 } // response timeout
23186
23187
23188 if (this._responseTimeout && !this._responseTimeoutTimer) {
23189 this._responseTimeoutTimer = setTimeout(function () {
23190 self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');
23191 }, this._responseTimeout);
23192 }
23193};
23194
23195/***/ }),
23196/* 373 */
23197/***/ (function(module, exports, __webpack_require__) {
23198
23199"use strict";
23200
23201
23202/**
23203 * Module dependencies.
23204 */
23205
23206var utils = __webpack_require__(374);
23207/**
23208 * Expose `ResponseBase`.
23209 */
23210
23211module.exports = ResponseBase;
23212/**
23213 * Initialize a new `ResponseBase`.
23214 *
23215 * @api public
23216 */
23217
23218function ResponseBase(obj) {
23219 if (obj) return mixin(obj);
23220}
23221/**
23222 * Mixin the prototype properties.
23223 *
23224 * @param {Object} obj
23225 * @return {Object}
23226 * @api private
23227 */
23228
23229function mixin(obj) {
23230 for (var key in ResponseBase.prototype) {
23231 if (Object.prototype.hasOwnProperty.call(ResponseBase.prototype, key)) obj[key] = ResponseBase.prototype[key];
23232 }
23233
23234 return obj;
23235}
23236/**
23237 * Get case-insensitive `field` value.
23238 *
23239 * @param {String} field
23240 * @return {String}
23241 * @api public
23242 */
23243
23244ResponseBase.prototype.get = function (field) {
23245 return this.header[field.toLowerCase()];
23246};
23247/**
23248 * Set header related properties:
23249 *
23250 * - `.type` the content type without params
23251 *
23252 * A response of "Content-Type: text/plain; charset=utf-8"
23253 * will provide you with a `.type` of "text/plain".
23254 *
23255 * @param {Object} header
23256 * @api private
23257 */
23258
23259ResponseBase.prototype._setHeaderProperties = function (header) {
23260 // TODO: moar!
23261 // TODO: make this a util
23262 // content-type
23263 var ct = header['content-type'] || '';
23264 this.type = utils.type(ct); // params
23265
23266 var params = utils.params(ct);
23267
23268 for (var key in params) {
23269 if (Object.prototype.hasOwnProperty.call(params, key)) this[key] = params[key];
23270 }
23271
23272 this.links = {}; // links
23273
23274 try {
23275 if (header.link) {
23276 this.links = utils.parseLinks(header.link);
23277 }
23278 } catch (_unused) {// ignore
23279 }
23280};
23281/**
23282 * Set flags such as `.ok` based on `status`.
23283 *
23284 * For example a 2xx response will give you a `.ok` of __true__
23285 * whereas 5xx will be __false__ and `.error` will be __true__. The
23286 * `.clientError` and `.serverError` are also available to be more
23287 * specific, and `.statusType` is the class of error ranging from 1..5
23288 * sometimes useful for mapping respond colors etc.
23289 *
23290 * "sugar" properties are also defined for common cases. Currently providing:
23291 *
23292 * - .noContent
23293 * - .badRequest
23294 * - .unauthorized
23295 * - .notAcceptable
23296 * - .notFound
23297 *
23298 * @param {Number} status
23299 * @api private
23300 */
23301
23302ResponseBase.prototype._setStatusProperties = function (status) {
23303 var type = status / 100 | 0; // status / class
23304
23305 this.statusCode = status;
23306 this.status = this.statusCode;
23307 this.statusType = type; // basics
23308
23309 this.info = type === 1;
23310 this.ok = type === 2;
23311 this.redirect = type === 3;
23312 this.clientError = type === 4;
23313 this.serverError = type === 5;
23314 this.error = type === 4 || type === 5 ? this.toError() : false; // sugar
23315
23316 this.created = status === 201;
23317 this.accepted = status === 202;
23318 this.noContent = status === 204;
23319 this.badRequest = status === 400;
23320 this.unauthorized = status === 401;
23321 this.notAcceptable = status === 406;
23322 this.forbidden = status === 403;
23323 this.notFound = status === 404;
23324 this.unprocessableEntity = status === 422;
23325};
23326
23327/***/ }),
23328/* 374 */
23329/***/ (function(module, exports, __webpack_require__) {
23330
23331"use strict";
23332
23333
23334/**
23335 * Return the mime type for the given `str`.
23336 *
23337 * @param {String} str
23338 * @return {String}
23339 * @api private
23340 */
23341
23342exports.type = function (str) {
23343 return str.split(/ *; */).shift();
23344};
23345/**
23346 * Return header field parameters.
23347 *
23348 * @param {String} str
23349 * @return {Object}
23350 * @api private
23351 */
23352
23353exports.params = function (str) {
23354 return str.split(/ *; */).reduce(function (obj, str) {
23355 var parts = str.split(/ *= */);
23356 var key = parts.shift();
23357 var val = parts.shift();
23358 if (key && val) obj[key] = val;
23359 return obj;
23360 }, {});
23361};
23362/**
23363 * Parse Link header fields.
23364 *
23365 * @param {String} str
23366 * @return {Object}
23367 * @api private
23368 */
23369
23370exports.parseLinks = function (str) {
23371 return str.split(/ *, */).reduce(function (obj, str) {
23372 var parts = str.split(/ *; */);
23373 var url = parts[0].slice(1, -1);
23374 var rel = parts[1].split(/ *= */)[1].slice(1, -1);
23375 obj[rel] = url;
23376 return obj;
23377 }, {});
23378};
23379/**
23380 * Strip content related fields from `header`.
23381 *
23382 * @param {Object} header
23383 * @return {Object} header
23384 * @api private
23385 */
23386
23387exports.cleanHeader = function (header, changesOrigin) {
23388 delete header['content-type'];
23389 delete header['content-length'];
23390 delete header['transfer-encoding'];
23391 delete header.host; // secuirty
23392
23393 if (changesOrigin) {
23394 delete header.authorization;
23395 delete header.cookie;
23396 }
23397
23398 return header;
23399};
23400
23401/***/ }),
23402/* 375 */
23403/***/ (function(module, exports, __webpack_require__) {
23404
23405"use strict";
23406
23407
23408var _isIterable2 = __webpack_require__(112);
23409
23410var _isIterable3 = _interopRequireDefault(_isIterable2);
23411
23412var _symbol = __webpack_require__(44);
23413
23414var _symbol2 = _interopRequireDefault(_symbol);
23415
23416var _from = __webpack_require__(191);
23417
23418var _from2 = _interopRequireDefault(_from);
23419
23420function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
23421
23422function _toConsumableArray(arr) {
23423 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
23424}
23425
23426function _nonIterableSpread() {
23427 throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
23428}
23429
23430function _unsupportedIterableToArray(o, minLen) {
23431 if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return (0, _from2.default)(o);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
23432}
23433
23434function _iterableToArray(iter) {
23435 if (typeof _symbol2.default !== "undefined" && (0, _isIterable3.default)(Object(iter))) return (0, _from2.default)(iter);
23436}
23437
23438function _arrayWithoutHoles(arr) {
23439 if (Array.isArray(arr)) return _arrayLikeToArray(arr);
23440}
23441
23442function _arrayLikeToArray(arr, len) {
23443 if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {
23444 arr2[i] = arr[i];
23445 }return arr2;
23446}
23447
23448function Agent() {
23449 this._defaults = [];
23450}
23451
23452['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts'].forEach(function (fn) {
23453 // Default setting for all requests from this agent
23454 Agent.prototype[fn] = function () {
23455 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
23456 args[_key] = arguments[_key];
23457 }
23458
23459 this._defaults.push({
23460 fn: fn,
23461 args: args
23462 });
23463
23464 return this;
23465 };
23466});
23467
23468Agent.prototype._setDefaults = function (req) {
23469 this._defaults.forEach(function (def) {
23470 req[def.fn].apply(req, _toConsumableArray(def.args));
23471 });
23472};
23473
23474module.exports = Agent;
23475
23476/***/ }),
23477/* 376 */
23478/***/ (function(module, exports, __webpack_require__) {
23479
23480__webpack_require__(35);
23481__webpack_require__(377);
23482module.exports = __webpack_require__(1).Array.from;
23483
23484
23485/***/ }),
23486/* 377 */
23487/***/ (function(module, exports, __webpack_require__) {
23488
23489"use strict";
23490
23491var ctx = __webpack_require__(22);
23492var $export = __webpack_require__(4);
23493var toObject = __webpack_require__(29);
23494var call = __webpack_require__(121);
23495var isArrayIter = __webpack_require__(122);
23496var toLength = __webpack_require__(61);
23497var createProperty = __webpack_require__(192);
23498var getIterFn = __webpack_require__(90);
23499
23500$export($export.S + $export.F * !__webpack_require__(128)(function (iter) { Array.from(iter); }), 'Array', {
23501 // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
23502 from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
23503 var O = toObject(arrayLike);
23504 var C = typeof this == 'function' ? this : Array;
23505 var aLen = arguments.length;
23506 var mapfn = aLen > 1 ? arguments[1] : undefined;
23507 var mapping = mapfn !== undefined;
23508 var index = 0;
23509 var iterFn = getIterFn(O);
23510 var length, result, step, iterator;
23511 if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
23512 // if object isn't iterable or it's array with default iterator - use simple case
23513 if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {
23514 for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
23515 createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
23516 }
23517 } else {
23518 length = toLength(O.length);
23519 for (result = new C(length); length > index; index++) {
23520 createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
23521 }
23522 }
23523 result.length = index;
23524 return result;
23525 }
23526});
23527
23528
23529/***/ }),
23530/* 378 */
23531/***/ (function(module, exports, __webpack_require__) {
23532
23533"use strict";
23534
23535
23536var _require = __webpack_require__(113),
23537 Realtime = _require.Realtime,
23538 setRTMAdapters = _require.setAdapters;
23539
23540var _require2 = __webpack_require__(461),
23541 LiveQueryPlugin = _require2.LiveQueryPlugin;
23542
23543Realtime.__preRegisteredPlugins = [LiveQueryPlugin];
23544
23545module.exports = function (AV) {
23546 AV._sharedConfig.liveQueryRealtime = Realtime;
23547
23548 var setAdapters = AV.setAdapters;
23549
23550 AV.setAdapters = function (adapters) {
23551 setAdapters(adapters);
23552 setRTMAdapters(adapters);
23553 };
23554
23555 return AV;
23556};
23557
23558/***/ }),
23559/* 379 */
23560/***/ (function(module, exports, __webpack_require__) {
23561
23562"use strict";
23563/* WEBPACK VAR INJECTION */(function(global) {
23564
23565var _set = __webpack_require__(193);
23566
23567var _set2 = _interopRequireDefault(_set);
23568
23569var _stringify = __webpack_require__(21);
23570
23571var _stringify2 = _interopRequireDefault(_stringify);
23572
23573var _weakMap = __webpack_require__(390);
23574
23575var _weakMap2 = _interopRequireDefault(_weakMap);
23576
23577var _promise = __webpack_require__(3);
23578
23579var _promise2 = _interopRequireDefault(_promise);
23580
23581var _defineProperty2 = __webpack_require__(71);
23582
23583var _defineProperty3 = _interopRequireDefault(_defineProperty2);
23584
23585var _defineProperties = __webpack_require__(396);
23586
23587var _defineProperties2 = _interopRequireDefault(_defineProperties);
23588
23589var _getOwnPropertyDescriptors = __webpack_require__(399);
23590
23591var _getOwnPropertyDescriptors2 = _interopRequireDefault(_getOwnPropertyDescriptors);
23592
23593var _getOwnPropertyDescriptor = __webpack_require__(188);
23594
23595var _getOwnPropertyDescriptor2 = _interopRequireDefault(_getOwnPropertyDescriptor);
23596
23597var _getOwnPropertySymbols = __webpack_require__(198);
23598
23599var _getOwnPropertySymbols2 = _interopRequireDefault(_getOwnPropertySymbols);
23600
23601var _keys = __webpack_require__(107);
23602
23603var _keys2 = _interopRequireDefault(_keys);
23604
23605var _symbol = __webpack_require__(44);
23606
23607var _symbol2 = _interopRequireDefault(_symbol);
23608
23609var _assign = __webpack_require__(199);
23610
23611var _assign2 = _interopRequireDefault(_assign);
23612
23613var _freeze = __webpack_require__(406);
23614
23615var _freeze2 = _interopRequireDefault(_freeze);
23616
23617var _typeof3 = __webpack_require__(23);
23618
23619var _typeof4 = _interopRequireDefault(_typeof3);
23620
23621function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
23622
23623Object.defineProperty(exports, '__esModule', { value: true });
23624
23625function _interopDefault(ex) {
23626 return ex && (typeof ex === 'undefined' ? 'undefined' : (0, _typeof4.default)(ex)) === 'object' && 'default' in ex ? ex['default'] : ex;
23627}
23628
23629var protobufLight = _interopDefault(__webpack_require__(409));
23630var EventEmitter = _interopDefault(__webpack_require__(413));
23631var _regeneratorRuntime = _interopDefault(__webpack_require__(414));
23632var _asyncToGenerator = _interopDefault(__webpack_require__(416));
23633var _toConsumableArray = _interopDefault(__webpack_require__(417));
23634var _defineProperty = _interopDefault(__webpack_require__(420));
23635var _objectWithoutProperties = _interopDefault(__webpack_require__(421));
23636var _assertThisInitialized = _interopDefault(__webpack_require__(423));
23637var _inheritsLoose = _interopDefault(__webpack_require__(424));
23638var d = _interopDefault(__webpack_require__(33));
23639var shuffle = _interopDefault(__webpack_require__(425));
23640var values = _interopDefault(__webpack_require__(204));
23641var _toArray = _interopDefault(__webpack_require__(452));
23642var _createClass = _interopDefault(__webpack_require__(455));
23643var _applyDecoratedDescriptor = _interopDefault(__webpack_require__(456));
23644var StateMachine = _interopDefault(__webpack_require__(457));
23645var _typeof = _interopDefault(__webpack_require__(458));
23646var isPlainObject = _interopDefault(__webpack_require__(459));
23647var promiseTimeout = __webpack_require__(185);
23648
23649var messageCompiled = protobufLight.newBuilder({})['import']({
23650 "package": 'push_server.messages2',
23651 syntax: 'proto2',
23652 options: {
23653 objc_class_prefix: 'AVIM'
23654 },
23655 messages: [{
23656 name: 'JsonObjectMessage',
23657 syntax: 'proto2',
23658 fields: [{
23659 rule: 'required',
23660 type: 'string',
23661 name: 'data',
23662 id: 1
23663 }]
23664 }, {
23665 name: 'UnreadTuple',
23666 syntax: 'proto2',
23667 fields: [{
23668 rule: 'required',
23669 type: 'string',
23670 name: 'cid',
23671 id: 1
23672 }, {
23673 rule: 'required',
23674 type: 'int32',
23675 name: 'unread',
23676 id: 2
23677 }, {
23678 rule: 'optional',
23679 type: 'string',
23680 name: 'mid',
23681 id: 3
23682 }, {
23683 rule: 'optional',
23684 type: 'int64',
23685 name: 'timestamp',
23686 id: 4
23687 }, {
23688 rule: 'optional',
23689 type: 'string',
23690 name: 'from',
23691 id: 5
23692 }, {
23693 rule: 'optional',
23694 type: 'string',
23695 name: 'data',
23696 id: 6
23697 }, {
23698 rule: 'optional',
23699 type: 'int64',
23700 name: 'patchTimestamp',
23701 id: 7
23702 }, {
23703 rule: 'optional',
23704 type: 'bool',
23705 name: 'mentioned',
23706 id: 8
23707 }, {
23708 rule: 'optional',
23709 type: 'bytes',
23710 name: 'binaryMsg',
23711 id: 9
23712 }, {
23713 rule: 'optional',
23714 type: 'int32',
23715 name: 'convType',
23716 id: 10
23717 }]
23718 }, {
23719 name: 'LogItem',
23720 syntax: 'proto2',
23721 fields: [{
23722 rule: 'optional',
23723 type: 'string',
23724 name: 'from',
23725 id: 1
23726 }, {
23727 rule: 'optional',
23728 type: 'string',
23729 name: 'data',
23730 id: 2
23731 }, {
23732 rule: 'optional',
23733 type: 'int64',
23734 name: 'timestamp',
23735 id: 3
23736 }, {
23737 rule: 'optional',
23738 type: 'string',
23739 name: 'msgId',
23740 id: 4
23741 }, {
23742 rule: 'optional',
23743 type: 'int64',
23744 name: 'ackAt',
23745 id: 5
23746 }, {
23747 rule: 'optional',
23748 type: 'int64',
23749 name: 'readAt',
23750 id: 6
23751 }, {
23752 rule: 'optional',
23753 type: 'int64',
23754 name: 'patchTimestamp',
23755 id: 7
23756 }, {
23757 rule: 'optional',
23758 type: 'bool',
23759 name: 'mentionAll',
23760 id: 8
23761 }, {
23762 rule: 'repeated',
23763 type: 'string',
23764 name: 'mentionPids',
23765 id: 9
23766 }, {
23767 rule: 'optional',
23768 type: 'bool',
23769 name: 'bin',
23770 id: 10
23771 }, {
23772 rule: 'optional',
23773 type: 'int32',
23774 name: 'convType',
23775 id: 11
23776 }]
23777 }, {
23778 name: 'ConvMemberInfo',
23779 syntax: 'proto2',
23780 fields: [{
23781 rule: 'optional',
23782 type: 'string',
23783 name: 'pid',
23784 id: 1
23785 }, {
23786 rule: 'optional',
23787 type: 'string',
23788 name: 'role',
23789 id: 2
23790 }, {
23791 rule: 'optional',
23792 type: 'string',
23793 name: 'infoId',
23794 id: 3
23795 }]
23796 }, {
23797 name: 'DataCommand',
23798 syntax: 'proto2',
23799 fields: [{
23800 rule: 'repeated',
23801 type: 'string',
23802 name: 'ids',
23803 id: 1
23804 }, {
23805 rule: 'repeated',
23806 type: 'JsonObjectMessage',
23807 name: 'msg',
23808 id: 2
23809 }, {
23810 rule: 'optional',
23811 type: 'bool',
23812 name: 'offline',
23813 id: 3
23814 }]
23815 }, {
23816 name: 'SessionCommand',
23817 syntax: 'proto2',
23818 fields: [{
23819 rule: 'optional',
23820 type: 'int64',
23821 name: 't',
23822 id: 1
23823 }, {
23824 rule: 'optional',
23825 type: 'string',
23826 name: 'n',
23827 id: 2
23828 }, {
23829 rule: 'optional',
23830 type: 'string',
23831 name: 's',
23832 id: 3
23833 }, {
23834 rule: 'optional',
23835 type: 'string',
23836 name: 'ua',
23837 id: 4
23838 }, {
23839 rule: 'optional',
23840 type: 'bool',
23841 name: 'r',
23842 id: 5
23843 }, {
23844 rule: 'optional',
23845 type: 'string',
23846 name: 'tag',
23847 id: 6
23848 }, {
23849 rule: 'optional',
23850 type: 'string',
23851 name: 'deviceId',
23852 id: 7
23853 }, {
23854 rule: 'repeated',
23855 type: 'string',
23856 name: 'sessionPeerIds',
23857 id: 8
23858 }, {
23859 rule: 'repeated',
23860 type: 'string',
23861 name: 'onlineSessionPeerIds',
23862 id: 9
23863 }, {
23864 rule: 'optional',
23865 type: 'string',
23866 name: 'st',
23867 id: 10
23868 }, {
23869 rule: 'optional',
23870 type: 'int32',
23871 name: 'stTtl',
23872 id: 11
23873 }, {
23874 rule: 'optional',
23875 type: 'int32',
23876 name: 'code',
23877 id: 12
23878 }, {
23879 rule: 'optional',
23880 type: 'string',
23881 name: 'reason',
23882 id: 13
23883 }, {
23884 rule: 'optional',
23885 type: 'string',
23886 name: 'deviceToken',
23887 id: 14
23888 }, {
23889 rule: 'optional',
23890 type: 'bool',
23891 name: 'sp',
23892 id: 15
23893 }, {
23894 rule: 'optional',
23895 type: 'string',
23896 name: 'detail',
23897 id: 16
23898 }, {
23899 rule: 'optional',
23900 type: 'int64',
23901 name: 'lastUnreadNotifTime',
23902 id: 17
23903 }, {
23904 rule: 'optional',
23905 type: 'int64',
23906 name: 'lastPatchTime',
23907 id: 18
23908 }, {
23909 rule: 'optional',
23910 type: 'int64',
23911 name: 'configBitmap',
23912 id: 19
23913 }]
23914 }, {
23915 name: 'ErrorCommand',
23916 syntax: 'proto2',
23917 fields: [{
23918 rule: 'required',
23919 type: 'int32',
23920 name: 'code',
23921 id: 1
23922 }, {
23923 rule: 'required',
23924 type: 'string',
23925 name: 'reason',
23926 id: 2
23927 }, {
23928 rule: 'optional',
23929 type: 'int32',
23930 name: 'appCode',
23931 id: 3
23932 }, {
23933 rule: 'optional',
23934 type: 'string',
23935 name: 'detail',
23936 id: 4
23937 }, {
23938 rule: 'repeated',
23939 type: 'string',
23940 name: 'pids',
23941 id: 5
23942 }, {
23943 rule: 'optional',
23944 type: 'string',
23945 name: 'appMsg',
23946 id: 6
23947 }]
23948 }, {
23949 name: 'DirectCommand',
23950 syntax: 'proto2',
23951 fields: [{
23952 rule: 'optional',
23953 type: 'string',
23954 name: 'msg',
23955 id: 1
23956 }, {
23957 rule: 'optional',
23958 type: 'string',
23959 name: 'uid',
23960 id: 2
23961 }, {
23962 rule: 'optional',
23963 type: 'string',
23964 name: 'fromPeerId',
23965 id: 3
23966 }, {
23967 rule: 'optional',
23968 type: 'int64',
23969 name: 'timestamp',
23970 id: 4
23971 }, {
23972 rule: 'optional',
23973 type: 'bool',
23974 name: 'offline',
23975 id: 5
23976 }, {
23977 rule: 'optional',
23978 type: 'bool',
23979 name: 'hasMore',
23980 id: 6
23981 }, {
23982 rule: 'repeated',
23983 type: 'string',
23984 name: 'toPeerIds',
23985 id: 7
23986 }, {
23987 rule: 'optional',
23988 type: 'bool',
23989 name: 'r',
23990 id: 10
23991 }, {
23992 rule: 'optional',
23993 type: 'string',
23994 name: 'cid',
23995 id: 11
23996 }, {
23997 rule: 'optional',
23998 type: 'string',
23999 name: 'id',
24000 id: 12
24001 }, {
24002 rule: 'optional',
24003 type: 'bool',
24004 name: 'transient',
24005 id: 13
24006 }, {
24007 rule: 'optional',
24008 type: 'string',
24009 name: 'dt',
24010 id: 14
24011 }, {
24012 rule: 'optional',
24013 type: 'string',
24014 name: 'roomId',
24015 id: 15
24016 }, {
24017 rule: 'optional',
24018 type: 'string',
24019 name: 'pushData',
24020 id: 16
24021 }, {
24022 rule: 'optional',
24023 type: 'bool',
24024 name: 'will',
24025 id: 17
24026 }, {
24027 rule: 'optional',
24028 type: 'int64',
24029 name: 'patchTimestamp',
24030 id: 18
24031 }, {
24032 rule: 'optional',
24033 type: 'bytes',
24034 name: 'binaryMsg',
24035 id: 19
24036 }, {
24037 rule: 'repeated',
24038 type: 'string',
24039 name: 'mentionPids',
24040 id: 20
24041 }, {
24042 rule: 'optional',
24043 type: 'bool',
24044 name: 'mentionAll',
24045 id: 21
24046 }, {
24047 rule: 'optional',
24048 type: 'int32',
24049 name: 'convType',
24050 id: 22
24051 }]
24052 }, {
24053 name: 'AckCommand',
24054 syntax: 'proto2',
24055 fields: [{
24056 rule: 'optional',
24057 type: 'int32',
24058 name: 'code',
24059 id: 1
24060 }, {
24061 rule: 'optional',
24062 type: 'string',
24063 name: 'reason',
24064 id: 2
24065 }, {
24066 rule: 'optional',
24067 type: 'string',
24068 name: 'mid',
24069 id: 3
24070 }, {
24071 rule: 'optional',
24072 type: 'string',
24073 name: 'cid',
24074 id: 4
24075 }, {
24076 rule: 'optional',
24077 type: 'int64',
24078 name: 't',
24079 id: 5
24080 }, {
24081 rule: 'optional',
24082 type: 'string',
24083 name: 'uid',
24084 id: 6
24085 }, {
24086 rule: 'optional',
24087 type: 'int64',
24088 name: 'fromts',
24089 id: 7
24090 }, {
24091 rule: 'optional',
24092 type: 'int64',
24093 name: 'tots',
24094 id: 8
24095 }, {
24096 rule: 'optional',
24097 type: 'string',
24098 name: 'type',
24099 id: 9
24100 }, {
24101 rule: 'repeated',
24102 type: 'string',
24103 name: 'ids',
24104 id: 10
24105 }, {
24106 rule: 'optional',
24107 type: 'int32',
24108 name: 'appCode',
24109 id: 11
24110 }, {
24111 rule: 'optional',
24112 type: 'string',
24113 name: 'appMsg',
24114 id: 12
24115 }]
24116 }, {
24117 name: 'UnreadCommand',
24118 syntax: 'proto2',
24119 fields: [{
24120 rule: 'repeated',
24121 type: 'UnreadTuple',
24122 name: 'convs',
24123 id: 1
24124 }, {
24125 rule: 'optional',
24126 type: 'int64',
24127 name: 'notifTime',
24128 id: 2
24129 }]
24130 }, {
24131 name: 'ConvCommand',
24132 syntax: 'proto2',
24133 fields: [{
24134 rule: 'repeated',
24135 type: 'string',
24136 name: 'm',
24137 id: 1
24138 }, {
24139 rule: 'optional',
24140 type: 'bool',
24141 name: 'transient',
24142 id: 2
24143 }, {
24144 rule: 'optional',
24145 type: 'bool',
24146 name: 'unique',
24147 id: 3
24148 }, {
24149 rule: 'optional',
24150 type: 'string',
24151 name: 'cid',
24152 id: 4
24153 }, {
24154 rule: 'optional',
24155 type: 'string',
24156 name: 'cdate',
24157 id: 5
24158 }, {
24159 rule: 'optional',
24160 type: 'string',
24161 name: 'initBy',
24162 id: 6
24163 }, {
24164 rule: 'optional',
24165 type: 'string',
24166 name: 'sort',
24167 id: 7
24168 }, {
24169 rule: 'optional',
24170 type: 'int32',
24171 name: 'limit',
24172 id: 8
24173 }, {
24174 rule: 'optional',
24175 type: 'int32',
24176 name: 'skip',
24177 id: 9
24178 }, {
24179 rule: 'optional',
24180 type: 'int32',
24181 name: 'flag',
24182 id: 10
24183 }, {
24184 rule: 'optional',
24185 type: 'int32',
24186 name: 'count',
24187 id: 11
24188 }, {
24189 rule: 'optional',
24190 type: 'string',
24191 name: 'udate',
24192 id: 12
24193 }, {
24194 rule: 'optional',
24195 type: 'int64',
24196 name: 't',
24197 id: 13
24198 }, {
24199 rule: 'optional',
24200 type: 'string',
24201 name: 'n',
24202 id: 14
24203 }, {
24204 rule: 'optional',
24205 type: 'string',
24206 name: 's',
24207 id: 15
24208 }, {
24209 rule: 'optional',
24210 type: 'bool',
24211 name: 'statusSub',
24212 id: 16
24213 }, {
24214 rule: 'optional',
24215 type: 'bool',
24216 name: 'statusPub',
24217 id: 17
24218 }, {
24219 rule: 'optional',
24220 type: 'int32',
24221 name: 'statusTTL',
24222 id: 18
24223 }, {
24224 rule: 'optional',
24225 type: 'string',
24226 name: 'uniqueId',
24227 id: 19
24228 }, {
24229 rule: 'optional',
24230 type: 'string',
24231 name: 'targetClientId',
24232 id: 20
24233 }, {
24234 rule: 'optional',
24235 type: 'int64',
24236 name: 'maxReadTimestamp',
24237 id: 21
24238 }, {
24239 rule: 'optional',
24240 type: 'int64',
24241 name: 'maxAckTimestamp',
24242 id: 22
24243 }, {
24244 rule: 'optional',
24245 type: 'bool',
24246 name: 'queryAllMembers',
24247 id: 23
24248 }, {
24249 rule: 'repeated',
24250 type: 'MaxReadTuple',
24251 name: 'maxReadTuples',
24252 id: 24
24253 }, {
24254 rule: 'repeated',
24255 type: 'string',
24256 name: 'cids',
24257 id: 25
24258 }, {
24259 rule: 'optional',
24260 type: 'ConvMemberInfo',
24261 name: 'info',
24262 id: 26
24263 }, {
24264 rule: 'optional',
24265 type: 'bool',
24266 name: 'tempConv',
24267 id: 27
24268 }, {
24269 rule: 'optional',
24270 type: 'int32',
24271 name: 'tempConvTTL',
24272 id: 28
24273 }, {
24274 rule: 'repeated',
24275 type: 'string',
24276 name: 'tempConvIds',
24277 id: 29
24278 }, {
24279 rule: 'repeated',
24280 type: 'string',
24281 name: 'allowedPids',
24282 id: 30
24283 }, {
24284 rule: 'repeated',
24285 type: 'ErrorCommand',
24286 name: 'failedPids',
24287 id: 31
24288 }, {
24289 rule: 'optional',
24290 type: 'string',
24291 name: 'next',
24292 id: 40
24293 }, {
24294 rule: 'optional',
24295 type: 'JsonObjectMessage',
24296 name: 'results',
24297 id: 100
24298 }, {
24299 rule: 'optional',
24300 type: 'JsonObjectMessage',
24301 name: 'where',
24302 id: 101
24303 }, {
24304 rule: 'optional',
24305 type: 'JsonObjectMessage',
24306 name: 'attr',
24307 id: 103
24308 }, {
24309 rule: 'optional',
24310 type: 'JsonObjectMessage',
24311 name: 'attrModified',
24312 id: 104
24313 }]
24314 }, {
24315 name: 'RoomCommand',
24316 syntax: 'proto2',
24317 fields: [{
24318 rule: 'optional',
24319 type: 'string',
24320 name: 'roomId',
24321 id: 1
24322 }, {
24323 rule: 'optional',
24324 type: 'string',
24325 name: 's',
24326 id: 2
24327 }, {
24328 rule: 'optional',
24329 type: 'int64',
24330 name: 't',
24331 id: 3
24332 }, {
24333 rule: 'optional',
24334 type: 'string',
24335 name: 'n',
24336 id: 4
24337 }, {
24338 rule: 'optional',
24339 type: 'bool',
24340 name: 'transient',
24341 id: 5
24342 }, {
24343 rule: 'repeated',
24344 type: 'string',
24345 name: 'roomPeerIds',
24346 id: 6
24347 }, {
24348 rule: 'optional',
24349 type: 'string',
24350 name: 'byPeerId',
24351 id: 7
24352 }]
24353 }, {
24354 name: 'LogsCommand',
24355 syntax: 'proto2',
24356 fields: [{
24357 rule: 'optional',
24358 type: 'string',
24359 name: 'cid',
24360 id: 1
24361 }, {
24362 rule: 'optional',
24363 type: 'int32',
24364 name: 'l',
24365 id: 2
24366 }, {
24367 rule: 'optional',
24368 type: 'int32',
24369 name: 'limit',
24370 id: 3
24371 }, {
24372 rule: 'optional',
24373 type: 'int64',
24374 name: 't',
24375 id: 4
24376 }, {
24377 rule: 'optional',
24378 type: 'int64',
24379 name: 'tt',
24380 id: 5
24381 }, {
24382 rule: 'optional',
24383 type: 'string',
24384 name: 'tmid',
24385 id: 6
24386 }, {
24387 rule: 'optional',
24388 type: 'string',
24389 name: 'mid',
24390 id: 7
24391 }, {
24392 rule: 'optional',
24393 type: 'string',
24394 name: 'checksum',
24395 id: 8
24396 }, {
24397 rule: 'optional',
24398 type: 'bool',
24399 name: 'stored',
24400 id: 9
24401 }, {
24402 rule: 'optional',
24403 type: 'QueryDirection',
24404 name: 'direction',
24405 id: 10,
24406 options: {
24407 "default": 'OLD'
24408 }
24409 }, {
24410 rule: 'optional',
24411 type: 'bool',
24412 name: 'tIncluded',
24413 id: 11
24414 }, {
24415 rule: 'optional',
24416 type: 'bool',
24417 name: 'ttIncluded',
24418 id: 12
24419 }, {
24420 rule: 'optional',
24421 type: 'int32',
24422 name: 'lctype',
24423 id: 13
24424 }, {
24425 rule: 'repeated',
24426 type: 'LogItem',
24427 name: 'logs',
24428 id: 105
24429 }],
24430 enums: [{
24431 name: 'QueryDirection',
24432 syntax: 'proto2',
24433 values: [{
24434 name: 'OLD',
24435 id: 1
24436 }, {
24437 name: 'NEW',
24438 id: 2
24439 }]
24440 }]
24441 }, {
24442 name: 'RcpCommand',
24443 syntax: 'proto2',
24444 fields: [{
24445 rule: 'optional',
24446 type: 'string',
24447 name: 'id',
24448 id: 1
24449 }, {
24450 rule: 'optional',
24451 type: 'string',
24452 name: 'cid',
24453 id: 2
24454 }, {
24455 rule: 'optional',
24456 type: 'int64',
24457 name: 't',
24458 id: 3
24459 }, {
24460 rule: 'optional',
24461 type: 'bool',
24462 name: 'read',
24463 id: 4
24464 }, {
24465 rule: 'optional',
24466 type: 'string',
24467 name: 'from',
24468 id: 5
24469 }]
24470 }, {
24471 name: 'ReadTuple',
24472 syntax: 'proto2',
24473 fields: [{
24474 rule: 'required',
24475 type: 'string',
24476 name: 'cid',
24477 id: 1
24478 }, {
24479 rule: 'optional',
24480 type: 'int64',
24481 name: 'timestamp',
24482 id: 2
24483 }, {
24484 rule: 'optional',
24485 type: 'string',
24486 name: 'mid',
24487 id: 3
24488 }]
24489 }, {
24490 name: 'MaxReadTuple',
24491 syntax: 'proto2',
24492 fields: [{
24493 rule: 'optional',
24494 type: 'string',
24495 name: 'pid',
24496 id: 1
24497 }, {
24498 rule: 'optional',
24499 type: 'int64',
24500 name: 'maxAckTimestamp',
24501 id: 2
24502 }, {
24503 rule: 'optional',
24504 type: 'int64',
24505 name: 'maxReadTimestamp',
24506 id: 3
24507 }]
24508 }, {
24509 name: 'ReadCommand',
24510 syntax: 'proto2',
24511 fields: [{
24512 rule: 'optional',
24513 type: 'string',
24514 name: 'cid',
24515 id: 1
24516 }, {
24517 rule: 'repeated',
24518 type: 'string',
24519 name: 'cids',
24520 id: 2
24521 }, {
24522 rule: 'repeated',
24523 type: 'ReadTuple',
24524 name: 'convs',
24525 id: 3
24526 }]
24527 }, {
24528 name: 'PresenceCommand',
24529 syntax: 'proto2',
24530 fields: [{
24531 rule: 'optional',
24532 type: 'StatusType',
24533 name: 'status',
24534 id: 1
24535 }, {
24536 rule: 'repeated',
24537 type: 'string',
24538 name: 'sessionPeerIds',
24539 id: 2
24540 }, {
24541 rule: 'optional',
24542 type: 'string',
24543 name: 'cid',
24544 id: 3
24545 }]
24546 }, {
24547 name: 'ReportCommand',
24548 syntax: 'proto2',
24549 fields: [{
24550 rule: 'optional',
24551 type: 'bool',
24552 name: 'initiative',
24553 id: 1
24554 }, {
24555 rule: 'optional',
24556 type: 'string',
24557 name: 'type',
24558 id: 2
24559 }, {
24560 rule: 'optional',
24561 type: 'string',
24562 name: 'data',
24563 id: 3
24564 }]
24565 }, {
24566 name: 'PatchItem',
24567 syntax: 'proto2',
24568 fields: [{
24569 rule: 'optional',
24570 type: 'string',
24571 name: 'cid',
24572 id: 1
24573 }, {
24574 rule: 'optional',
24575 type: 'string',
24576 name: 'mid',
24577 id: 2
24578 }, {
24579 rule: 'optional',
24580 type: 'int64',
24581 name: 'timestamp',
24582 id: 3
24583 }, {
24584 rule: 'optional',
24585 type: 'bool',
24586 name: 'recall',
24587 id: 4
24588 }, {
24589 rule: 'optional',
24590 type: 'string',
24591 name: 'data',
24592 id: 5
24593 }, {
24594 rule: 'optional',
24595 type: 'int64',
24596 name: 'patchTimestamp',
24597 id: 6
24598 }, {
24599 rule: 'optional',
24600 type: 'string',
24601 name: 'from',
24602 id: 7
24603 }, {
24604 rule: 'optional',
24605 type: 'bytes',
24606 name: 'binaryMsg',
24607 id: 8
24608 }, {
24609 rule: 'optional',
24610 type: 'bool',
24611 name: 'mentionAll',
24612 id: 9
24613 }, {
24614 rule: 'repeated',
24615 type: 'string',
24616 name: 'mentionPids',
24617 id: 10
24618 }, {
24619 rule: 'optional',
24620 type: 'int64',
24621 name: 'patchCode',
24622 id: 11
24623 }, {
24624 rule: 'optional',
24625 type: 'string',
24626 name: 'patchReason',
24627 id: 12
24628 }]
24629 }, {
24630 name: 'PatchCommand',
24631 syntax: 'proto2',
24632 fields: [{
24633 rule: 'repeated',
24634 type: 'PatchItem',
24635 name: 'patches',
24636 id: 1
24637 }, {
24638 rule: 'optional',
24639 type: 'int64',
24640 name: 'lastPatchTime',
24641 id: 2
24642 }]
24643 }, {
24644 name: 'PubsubCommand',
24645 syntax: 'proto2',
24646 fields: [{
24647 rule: 'optional',
24648 type: 'string',
24649 name: 'cid',
24650 id: 1
24651 }, {
24652 rule: 'repeated',
24653 type: 'string',
24654 name: 'cids',
24655 id: 2
24656 }, {
24657 rule: 'optional',
24658 type: 'string',
24659 name: 'topic',
24660 id: 3
24661 }, {
24662 rule: 'optional',
24663 type: 'string',
24664 name: 'subtopic',
24665 id: 4
24666 }, {
24667 rule: 'repeated',
24668 type: 'string',
24669 name: 'topics',
24670 id: 5
24671 }, {
24672 rule: 'repeated',
24673 type: 'string',
24674 name: 'subtopics',
24675 id: 6
24676 }, {
24677 rule: 'optional',
24678 type: 'JsonObjectMessage',
24679 name: 'results',
24680 id: 7
24681 }]
24682 }, {
24683 name: 'BlacklistCommand',
24684 syntax: 'proto2',
24685 fields: [{
24686 rule: 'optional',
24687 type: 'string',
24688 name: 'srcCid',
24689 id: 1
24690 }, {
24691 rule: 'repeated',
24692 type: 'string',
24693 name: 'toPids',
24694 id: 2
24695 }, {
24696 rule: 'optional',
24697 type: 'string',
24698 name: 'srcPid',
24699 id: 3
24700 }, {
24701 rule: 'repeated',
24702 type: 'string',
24703 name: 'toCids',
24704 id: 4
24705 }, {
24706 rule: 'optional',
24707 type: 'int32',
24708 name: 'limit',
24709 id: 5
24710 }, {
24711 rule: 'optional',
24712 type: 'string',
24713 name: 'next',
24714 id: 6
24715 }, {
24716 rule: 'repeated',
24717 type: 'string',
24718 name: 'blockedPids',
24719 id: 8
24720 }, {
24721 rule: 'repeated',
24722 type: 'string',
24723 name: 'blockedCids',
24724 id: 9
24725 }, {
24726 rule: 'repeated',
24727 type: 'string',
24728 name: 'allowedPids',
24729 id: 10
24730 }, {
24731 rule: 'repeated',
24732 type: 'ErrorCommand',
24733 name: 'failedPids',
24734 id: 11
24735 }, {
24736 rule: 'optional',
24737 type: 'int64',
24738 name: 't',
24739 id: 12
24740 }, {
24741 rule: 'optional',
24742 type: 'string',
24743 name: 'n',
24744 id: 13
24745 }, {
24746 rule: 'optional',
24747 type: 'string',
24748 name: 's',
24749 id: 14
24750 }]
24751 }, {
24752 name: 'GenericCommand',
24753 syntax: 'proto2',
24754 fields: [{
24755 rule: 'optional',
24756 type: 'CommandType',
24757 name: 'cmd',
24758 id: 1
24759 }, {
24760 rule: 'optional',
24761 type: 'OpType',
24762 name: 'op',
24763 id: 2
24764 }, {
24765 rule: 'optional',
24766 type: 'string',
24767 name: 'appId',
24768 id: 3
24769 }, {
24770 rule: 'optional',
24771 type: 'string',
24772 name: 'peerId',
24773 id: 4
24774 }, {
24775 rule: 'optional',
24776 type: 'int32',
24777 name: 'i',
24778 id: 5
24779 }, {
24780 rule: 'optional',
24781 type: 'string',
24782 name: 'installationId',
24783 id: 6
24784 }, {
24785 rule: 'optional',
24786 type: 'int32',
24787 name: 'priority',
24788 id: 7
24789 }, {
24790 rule: 'optional',
24791 type: 'int32',
24792 name: 'service',
24793 id: 8
24794 }, {
24795 rule: 'optional',
24796 type: 'int64',
24797 name: 'serverTs',
24798 id: 9
24799 }, {
24800 rule: 'optional',
24801 type: 'int64',
24802 name: 'clientTs',
24803 id: 10
24804 }, {
24805 rule: 'optional',
24806 type: 'int32',
24807 name: 'notificationType',
24808 id: 11
24809 }, {
24810 rule: 'optional',
24811 type: 'DataCommand',
24812 name: 'dataMessage',
24813 id: 101
24814 }, {
24815 rule: 'optional',
24816 type: 'SessionCommand',
24817 name: 'sessionMessage',
24818 id: 102
24819 }, {
24820 rule: 'optional',
24821 type: 'ErrorCommand',
24822 name: 'errorMessage',
24823 id: 103
24824 }, {
24825 rule: 'optional',
24826 type: 'DirectCommand',
24827 name: 'directMessage',
24828 id: 104
24829 }, {
24830 rule: 'optional',
24831 type: 'AckCommand',
24832 name: 'ackMessage',
24833 id: 105
24834 }, {
24835 rule: 'optional',
24836 type: 'UnreadCommand',
24837 name: 'unreadMessage',
24838 id: 106
24839 }, {
24840 rule: 'optional',
24841 type: 'ReadCommand',
24842 name: 'readMessage',
24843 id: 107
24844 }, {
24845 rule: 'optional',
24846 type: 'RcpCommand',
24847 name: 'rcpMessage',
24848 id: 108
24849 }, {
24850 rule: 'optional',
24851 type: 'LogsCommand',
24852 name: 'logsMessage',
24853 id: 109
24854 }, {
24855 rule: 'optional',
24856 type: 'ConvCommand',
24857 name: 'convMessage',
24858 id: 110
24859 }, {
24860 rule: 'optional',
24861 type: 'RoomCommand',
24862 name: 'roomMessage',
24863 id: 111
24864 }, {
24865 rule: 'optional',
24866 type: 'PresenceCommand',
24867 name: 'presenceMessage',
24868 id: 112
24869 }, {
24870 rule: 'optional',
24871 type: 'ReportCommand',
24872 name: 'reportMessage',
24873 id: 113
24874 }, {
24875 rule: 'optional',
24876 type: 'PatchCommand',
24877 name: 'patchMessage',
24878 id: 114
24879 }, {
24880 rule: 'optional',
24881 type: 'PubsubCommand',
24882 name: 'pubsubMessage',
24883 id: 115
24884 }, {
24885 rule: 'optional',
24886 type: 'BlacklistCommand',
24887 name: 'blacklistMessage',
24888 id: 116
24889 }]
24890 }],
24891 enums: [{
24892 name: 'CommandType',
24893 syntax: 'proto2',
24894 values: [{
24895 name: 'session',
24896 id: 0
24897 }, {
24898 name: 'conv',
24899 id: 1
24900 }, {
24901 name: 'direct',
24902 id: 2
24903 }, {
24904 name: 'ack',
24905 id: 3
24906 }, {
24907 name: 'rcp',
24908 id: 4
24909 }, {
24910 name: 'unread',
24911 id: 5
24912 }, {
24913 name: 'logs',
24914 id: 6
24915 }, {
24916 name: 'error',
24917 id: 7
24918 }, {
24919 name: 'login',
24920 id: 8
24921 }, {
24922 name: 'data',
24923 id: 9
24924 }, {
24925 name: 'room',
24926 id: 10
24927 }, {
24928 name: 'read',
24929 id: 11
24930 }, {
24931 name: 'presence',
24932 id: 12
24933 }, {
24934 name: 'report',
24935 id: 13
24936 }, {
24937 name: 'echo',
24938 id: 14
24939 }, {
24940 name: 'loggedin',
24941 id: 15
24942 }, {
24943 name: 'logout',
24944 id: 16
24945 }, {
24946 name: 'loggedout',
24947 id: 17
24948 }, {
24949 name: 'patch',
24950 id: 18
24951 }, {
24952 name: 'pubsub',
24953 id: 19
24954 }, {
24955 name: 'blacklist',
24956 id: 20
24957 }, {
24958 name: 'goaway',
24959 id: 21
24960 }]
24961 }, {
24962 name: 'OpType',
24963 syntax: 'proto2',
24964 values: [{
24965 name: 'open',
24966 id: 1
24967 }, {
24968 name: 'add',
24969 id: 2
24970 }, {
24971 name: 'remove',
24972 id: 3
24973 }, {
24974 name: 'close',
24975 id: 4
24976 }, {
24977 name: 'opened',
24978 id: 5
24979 }, {
24980 name: 'closed',
24981 id: 6
24982 }, {
24983 name: 'query',
24984 id: 7
24985 }, {
24986 name: 'query_result',
24987 id: 8
24988 }, {
24989 name: 'conflict',
24990 id: 9
24991 }, {
24992 name: 'added',
24993 id: 10
24994 }, {
24995 name: 'removed',
24996 id: 11
24997 }, {
24998 name: 'refresh',
24999 id: 12
25000 }, {
25001 name: 'refreshed',
25002 id: 13
25003 }, {
25004 name: 'start',
25005 id: 30
25006 }, {
25007 name: 'started',
25008 id: 31
25009 }, {
25010 name: 'joined',
25011 id: 32
25012 }, {
25013 name: 'members_joined',
25014 id: 33
25015 }, {
25016 name: 'left',
25017 id: 39
25018 }, {
25019 name: 'members_left',
25020 id: 40
25021 }, {
25022 name: 'results',
25023 id: 42
25024 }, {
25025 name: 'count',
25026 id: 43
25027 }, {
25028 name: 'result',
25029 id: 44
25030 }, {
25031 name: 'update',
25032 id: 45
25033 }, {
25034 name: 'updated',
25035 id: 46
25036 }, {
25037 name: 'mute',
25038 id: 47
25039 }, {
25040 name: 'unmute',
25041 id: 48
25042 }, {
25043 name: 'status',
25044 id: 49
25045 }, {
25046 name: 'members',
25047 id: 50
25048 }, {
25049 name: 'max_read',
25050 id: 51
25051 }, {
25052 name: 'is_member',
25053 id: 52
25054 }, {
25055 name: 'member_info_update',
25056 id: 53
25057 }, {
25058 name: 'member_info_updated',
25059 id: 54
25060 }, {
25061 name: 'member_info_changed',
25062 id: 55
25063 }, {
25064 name: 'join',
25065 id: 80
25066 }, {
25067 name: 'invite',
25068 id: 81
25069 }, {
25070 name: 'leave',
25071 id: 82
25072 }, {
25073 name: 'kick',
25074 id: 83
25075 }, {
25076 name: 'reject',
25077 id: 84
25078 }, {
25079 name: 'invited',
25080 id: 85
25081 }, {
25082 name: 'kicked',
25083 id: 86
25084 }, {
25085 name: 'upload',
25086 id: 100
25087 }, {
25088 name: 'uploaded',
25089 id: 101
25090 }, {
25091 name: 'subscribe',
25092 id: 120
25093 }, {
25094 name: 'subscribed',
25095 id: 121
25096 }, {
25097 name: 'unsubscribe',
25098 id: 122
25099 }, {
25100 name: 'unsubscribed',
25101 id: 123
25102 }, {
25103 name: 'is_subscribed',
25104 id: 124
25105 }, {
25106 name: 'modify',
25107 id: 150
25108 }, {
25109 name: 'modified',
25110 id: 151
25111 }, {
25112 name: 'block',
25113 id: 170
25114 }, {
25115 name: 'unblock',
25116 id: 171
25117 }, {
25118 name: 'blocked',
25119 id: 172
25120 }, {
25121 name: 'unblocked',
25122 id: 173
25123 }, {
25124 name: 'members_blocked',
25125 id: 174
25126 }, {
25127 name: 'members_unblocked',
25128 id: 175
25129 }, {
25130 name: 'check_block',
25131 id: 176
25132 }, {
25133 name: 'check_result',
25134 id: 177
25135 }, {
25136 name: 'add_shutup',
25137 id: 180
25138 }, {
25139 name: 'remove_shutup',
25140 id: 181
25141 }, {
25142 name: 'query_shutup',
25143 id: 182
25144 }, {
25145 name: 'shutup_added',
25146 id: 183
25147 }, {
25148 name: 'shutup_removed',
25149 id: 184
25150 }, {
25151 name: 'shutup_result',
25152 id: 185
25153 }, {
25154 name: 'shutuped',
25155 id: 186
25156 }, {
25157 name: 'unshutuped',
25158 id: 187
25159 }, {
25160 name: 'members_shutuped',
25161 id: 188
25162 }, {
25163 name: 'members_unshutuped',
25164 id: 189
25165 }, {
25166 name: 'check_shutup',
25167 id: 190
25168 }]
25169 }, {
25170 name: 'StatusType',
25171 syntax: 'proto2',
25172 values: [{
25173 name: 'on',
25174 id: 1
25175 }, {
25176 name: 'off',
25177 id: 2
25178 }]
25179 }],
25180 isNamespace: true
25181}).build();
25182
25183var _messages$push_server = messageCompiled.push_server.messages2,
25184 JsonObjectMessage = _messages$push_server.JsonObjectMessage,
25185 UnreadTuple = _messages$push_server.UnreadTuple,
25186 LogItem = _messages$push_server.LogItem,
25187 DataCommand = _messages$push_server.DataCommand,
25188 SessionCommand = _messages$push_server.SessionCommand,
25189 ErrorCommand = _messages$push_server.ErrorCommand,
25190 DirectCommand = _messages$push_server.DirectCommand,
25191 AckCommand = _messages$push_server.AckCommand,
25192 UnreadCommand = _messages$push_server.UnreadCommand,
25193 ConvCommand = _messages$push_server.ConvCommand,
25194 RoomCommand = _messages$push_server.RoomCommand,
25195 LogsCommand = _messages$push_server.LogsCommand,
25196 RcpCommand = _messages$push_server.RcpCommand,
25197 ReadTuple = _messages$push_server.ReadTuple,
25198 MaxReadTuple = _messages$push_server.MaxReadTuple,
25199 ReadCommand = _messages$push_server.ReadCommand,
25200 PresenceCommand = _messages$push_server.PresenceCommand,
25201 ReportCommand = _messages$push_server.ReportCommand,
25202 GenericCommand = _messages$push_server.GenericCommand,
25203 BlacklistCommand = _messages$push_server.BlacklistCommand,
25204 PatchCommand = _messages$push_server.PatchCommand,
25205 PatchItem = _messages$push_server.PatchItem,
25206 ConvMemberInfo = _messages$push_server.ConvMemberInfo,
25207 CommandType = _messages$push_server.CommandType,
25208 OpType = _messages$push_server.OpType,
25209 StatusType = _messages$push_server.StatusType;
25210
25211var message = /*#__PURE__*/(0, _freeze2.default)({
25212 __proto__: null,
25213 JsonObjectMessage: JsonObjectMessage,
25214 UnreadTuple: UnreadTuple,
25215 LogItem: LogItem,
25216 DataCommand: DataCommand,
25217 SessionCommand: SessionCommand,
25218 ErrorCommand: ErrorCommand,
25219 DirectCommand: DirectCommand,
25220 AckCommand: AckCommand,
25221 UnreadCommand: UnreadCommand,
25222 ConvCommand: ConvCommand,
25223 RoomCommand: RoomCommand,
25224 LogsCommand: LogsCommand,
25225 RcpCommand: RcpCommand,
25226 ReadTuple: ReadTuple,
25227 MaxReadTuple: MaxReadTuple,
25228 ReadCommand: ReadCommand,
25229 PresenceCommand: PresenceCommand,
25230 ReportCommand: ReportCommand,
25231 GenericCommand: GenericCommand,
25232 BlacklistCommand: BlacklistCommand,
25233 PatchCommand: PatchCommand,
25234 PatchItem: PatchItem,
25235 ConvMemberInfo: ConvMemberInfo,
25236 CommandType: CommandType,
25237 OpType: OpType,
25238 StatusType: StatusType
25239});
25240
25241var adapters = {};
25242
25243var getAdapter = function getAdapter(name) {
25244 var adapter = adapters[name];
25245
25246 if (adapter === undefined) {
25247 throw new Error("".concat(name, " adapter is not configured"));
25248 }
25249
25250 return adapter;
25251};
25252/**
25253 * 指定 Adapters
25254 * @function
25255 * @memberof module:leancloud-realtime
25256 * @param {Adapters} newAdapters Adapters 的类型请参考 {@link https://url.leanapp.cn/adapter-type-definitions @leancloud/adapter-types} 中的定义
25257 */
25258
25259var setAdapters = function setAdapters(newAdapters) {
25260 (0, _assign2.default)(adapters, newAdapters);
25261};
25262
25263/* eslint-disable */
25264var global$1 = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {};
25265
25266var EXPIRED = (0, _symbol2.default)('expired');
25267var debug = d('LC:Expirable');
25268
25269var Expirable = /*#__PURE__*/function () {
25270 function Expirable(value, ttl) {
25271 this.originalValue = value;
25272
25273 if (typeof ttl === 'number') {
25274 this.expiredAt = Date.now() + ttl;
25275 }
25276 }
25277
25278 _createClass(Expirable, [{
25279 key: "value",
25280 get: function get() {
25281 var expired = this.expiredAt && this.expiredAt <= Date.now();
25282 if (expired) debug("expired: ".concat(this.originalValue));
25283 return expired ? EXPIRED : this.originalValue;
25284 }
25285 }]);
25286
25287 return Expirable;
25288}();
25289Expirable.EXPIRED = EXPIRED;
25290
25291var debug$1 = d('LC:Cache');
25292
25293var Cache = /*#__PURE__*/function () {
25294 function Cache() {
25295 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'anonymous';
25296 this.name = name;
25297 this._map = {};
25298 }
25299
25300 var _proto = Cache.prototype;
25301
25302 _proto.get = function get(key) {
25303 var cache = this._map[key];
25304
25305 if (cache) {
25306 var value = cache.value;
25307
25308 if (value !== Expirable.EXPIRED) {
25309 debug$1('[%s] hit: %s', this.name, key);
25310 return value;
25311 }
25312
25313 delete this._map[key];
25314 }
25315
25316 debug$1("[".concat(this.name, "] missed: ").concat(key));
25317 return null;
25318 };
25319
25320 _proto.set = function set(key, value, ttl) {
25321 debug$1('[%s] set: %s %d', this.name, key, ttl);
25322 this._map[key] = new Expirable(value, ttl);
25323 };
25324
25325 return Cache;
25326}();
25327
25328function ownKeys(object, enumerableOnly) {
25329 var keys = (0, _keys2.default)(object);if (_getOwnPropertySymbols2.default) {
25330 var symbols = (0, _getOwnPropertySymbols2.default)(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {
25331 return (0, _getOwnPropertyDescriptor2.default)(object, sym).enumerable;
25332 });keys.push.apply(keys, symbols);
25333 }return keys;
25334}
25335
25336function _objectSpread(target) {
25337 for (var i = 1; i < arguments.length; i++) {
25338 var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {
25339 ownKeys(Object(source), true).forEach(function (key) {
25340 _defineProperty(target, key, source[key]);
25341 });
25342 } else if (_getOwnPropertyDescriptors2.default) {
25343 (0, _defineProperties2.default)(target, (0, _getOwnPropertyDescriptors2.default)(source));
25344 } else {
25345 ownKeys(Object(source)).forEach(function (key) {
25346 (0, _defineProperty3.default)(target, key, (0, _getOwnPropertyDescriptor2.default)(source, key));
25347 });
25348 }
25349 }return target;
25350}
25351/**
25352 * 调试日志控制器
25353 * @const
25354 * @memberof module:leancloud-realtime
25355 * @example
25356 * debug.enable(); // 启用调试日志
25357 * debug.disable(); // 关闭调试日志
25358 */
25359
25360var debug$2 = {
25361 enable: function enable() {
25362 var namespaces = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'LC*';
25363 return d.enable(namespaces);
25364 },
25365 disable: d.disable
25366};
25367var tryAll = function tryAll(promiseConstructors) {
25368 var promise = new _promise2.default(promiseConstructors[0]);
25369
25370 if (promiseConstructors.length === 1) {
25371 return promise;
25372 }
25373
25374 return promise["catch"](function () {
25375 return tryAll(promiseConstructors.slice(1));
25376 });
25377}; // eslint-disable-next-line no-sequences
25378
25379var tap = function tap(interceptor) {
25380 return function (value) {
25381 return interceptor(value), value;
25382 };
25383};
25384var isIE10 = global$1.navigator && global$1.navigator.userAgent && global$1.navigator.userAgent.indexOf('MSIE 10.') !== -1;
25385var map = new _weakMap2.default(); // protected property helper
25386
25387var internal = function internal(object) {
25388 if (!map.has(object)) {
25389 map.set(object, {});
25390 }
25391
25392 return map.get(object);
25393};
25394var compact = function compact(obj, filter) {
25395 if (!isPlainObject(obj)) return obj;
25396
25397 var object = _objectSpread({}, obj);
25398
25399 (0, _keys2.default)(object).forEach(function (prop) {
25400 var value = object[prop];
25401
25402 if (value === filter) {
25403 delete object[prop];
25404 } else {
25405 object[prop] = compact(value, filter);
25406 }
25407 });
25408 return object;
25409}; // debug utility
25410
25411var removeNull = function removeNull(obj) {
25412 return compact(obj, null);
25413};
25414
25415var trim = function trim(message) {
25416 return removeNull(JSON.parse((0, _stringify2.default)(message)));
25417};
25418var ensureArray = function ensureArray(target) {
25419 if (Array.isArray(target)) {
25420 return target;
25421 }
25422
25423 if (target === undefined || target === null) {
25424 return [];
25425 }
25426
25427 return [target];
25428};
25429var isWeapp = // eslint-disable-next-line no-undef
25430(typeof wx === "undefined" ? "undefined" : _typeof(wx)) === 'object' && typeof wx.connectSocket === 'function'; // throttle decorator
25431var isCNApp = function isCNApp(appId) {
25432 return appId.slice(-9) !== '-MdYXbMMI';
25433};
25434var equalBuffer = function equalBuffer(buffer1, buffer2) {
25435 if (!buffer1 || !buffer2) return false;
25436 if (buffer1.byteLength !== buffer2.byteLength) return false;
25437 var a = new Uint8Array(buffer1);
25438 var b = new Uint8Array(buffer2);
25439 return !a.some(function (value, index) {
25440 return value !== b[index];
25441 });
25442};
25443
25444var _class;
25445
25446function ownKeys$1(object, enumerableOnly) {
25447 var keys = (0, _keys2.default)(object);if (_getOwnPropertySymbols2.default) {
25448 var symbols = (0, _getOwnPropertySymbols2.default)(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {
25449 return (0, _getOwnPropertyDescriptor2.default)(object, sym).enumerable;
25450 });keys.push.apply(keys, symbols);
25451 }return keys;
25452}
25453
25454function _objectSpread$1(target) {
25455 for (var i = 1; i < arguments.length; i++) {
25456 var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {
25457 ownKeys$1(Object(source), true).forEach(function (key) {
25458 _defineProperty(target, key, source[key]);
25459 });
25460 } else if (_getOwnPropertyDescriptors2.default) {
25461 (0, _defineProperties2.default)(target, (0, _getOwnPropertyDescriptors2.default)(source));
25462 } else {
25463 ownKeys$1(Object(source)).forEach(function (key) {
25464 (0, _defineProperty3.default)(target, key, (0, _getOwnPropertyDescriptor2.default)(source, key));
25465 });
25466 }
25467 }return target;
25468}
25469var debug$3 = d('LC:WebSocketPlus');
25470var OPEN = 'open';
25471var DISCONNECT = 'disconnect';
25472var RECONNECT = 'reconnect';
25473var RETRY = 'retry';
25474var SCHEDULE = 'schedule';
25475var OFFLINE = 'offline';
25476var ONLINE = 'online';
25477var ERROR = 'error';
25478var MESSAGE = 'message';
25479var HEARTBEAT_TIME = 180000;
25480var TIMEOUT_TIME = 380000;
25481
25482var DEFAULT_RETRY_STRATEGY = function DEFAULT_RETRY_STRATEGY(attempt) {
25483 return Math.min(1000 * Math.pow(2, attempt), 300000);
25484};
25485
25486var requireConnected = function requireConnected(target, name, descriptor) {
25487 return _objectSpread$1(_objectSpread$1({}, descriptor), {}, {
25488 value: function requireConnectedWrapper() {
25489 var _descriptor$value;
25490
25491 this.checkConnectionAvailability(name);
25492
25493 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
25494 args[_key] = arguments[_key];
25495 }
25496
25497 return (_descriptor$value = descriptor.value).call.apply(_descriptor$value, [this].concat(args));
25498 }
25499 });
25500};
25501
25502var WebSocketPlus = (_class = /*#__PURE__*/function (_EventEmitter) {
25503 _inheritsLoose(WebSocketPlus, _EventEmitter);
25504
25505 _createClass(WebSocketPlus, [{
25506 key: "urls",
25507 get: function get() {
25508 return this._urls;
25509 },
25510 set: function set(urls) {
25511 this._urls = ensureArray(urls);
25512 }
25513 }]);
25514
25515 function WebSocketPlus(getUrls, protocol) {
25516 var _this;
25517
25518 _this = _EventEmitter.call(this) || this;
25519
25520 _this.init();
25521
25522 _this._protocol = protocol;
25523 _promise2.default.resolve(typeof getUrls === 'function' ? getUrls() : getUrls).then(ensureArray).then(function (urls) {
25524 _this._urls = urls;
25525 return _this._open();
25526 }).then(function () {
25527 _this.__postponeTimeoutTimer = _this._postponeTimeoutTimer.bind(_assertThisInitialized(_this));
25528
25529 if (global$1.addEventListener) {
25530 _this.__pause = function () {
25531 if (_this.can('pause')) _this.pause();
25532 };
25533
25534 _this.__resume = function () {
25535 if (_this.can('resume')) _this.resume();
25536 };
25537
25538 global$1.addEventListener('offline', _this.__pause);
25539 global$1.addEventListener('online', _this.__resume);
25540 }
25541
25542 _this.open();
25543 })["catch"](_this["throw"].bind(_assertThisInitialized(_this)));
25544 return _this;
25545 }
25546
25547 var _proto = WebSocketPlus.prototype;
25548
25549 _proto._open = function _open() {
25550 var _this2 = this;
25551
25552 return this._createWs(this._urls, this._protocol).then(function (ws) {
25553 var _this2$_urls = _toArray(_this2._urls),
25554 first = _this2$_urls[0],
25555 reset = _this2$_urls.slice(1);
25556
25557 _this2._urls = [].concat(_toConsumableArray(reset), [first]);
25558 return ws;
25559 });
25560 };
25561
25562 _proto._createWs = function _createWs(urls, protocol) {
25563 var _this3 = this;
25564
25565 return tryAll(urls.map(function (url) {
25566 return function (resolve, reject) {
25567 debug$3("connect [".concat(url, "] ").concat(protocol));
25568 var WebSocket = getAdapter('WebSocket');
25569 var ws = protocol ? new WebSocket(url, protocol) : new WebSocket(url);
25570 ws.binaryType = _this3.binaryType || 'arraybuffer';
25571
25572 ws.onopen = function () {
25573 return resolve(ws);
25574 };
25575
25576 ws.onclose = function (error) {
25577 if (error instanceof Error) {
25578 return reject(error);
25579 } // in browser, error event is useless
25580
25581
25582 return reject(new Error("Failed to connect [".concat(url, "]")));
25583 };
25584
25585 ws.onerror = ws.onclose;
25586 };
25587 })).then(function (ws) {
25588 _this3._ws = ws;
25589 _this3._ws.onclose = _this3._handleClose.bind(_this3);
25590 _this3._ws.onmessage = _this3._handleMessage.bind(_this3);
25591 return ws;
25592 });
25593 };
25594
25595 _proto._destroyWs = function _destroyWs() {
25596 var ws = this._ws;
25597 if (!ws) return;
25598 ws.onopen = null;
25599 ws.onclose = null;
25600 ws.onerror = null;
25601 ws.onmessage = null;
25602 this._ws = null;
25603 ws.close();
25604 } // eslint-disable-next-line class-methods-use-this
25605 ;
25606
25607 _proto.onbeforeevent = function onbeforeevent(event, from, to) {
25608 for (var _len2 = arguments.length, payload = new Array(_len2 > 3 ? _len2 - 3 : 0), _key2 = 3; _key2 < _len2; _key2++) {
25609 payload[_key2 - 3] = arguments[_key2];
25610 }
25611
25612 debug$3("".concat(event, ": ").concat(from, " -> ").concat(to, " %o"), payload);
25613 };
25614
25615 _proto.onopen = function onopen() {
25616 this.emit(OPEN);
25617 };
25618
25619 _proto.onconnected = function onconnected() {
25620 this._startConnectionKeeper();
25621 };
25622
25623 _proto.onleaveconnected = function onleaveconnected(event, from, to) {
25624 this._stopConnectionKeeper();
25625
25626 this._destroyWs();
25627
25628 if (to === 'offline' || to === 'disconnected') {
25629 this.emit(DISCONNECT);
25630 }
25631 };
25632
25633 _proto.onpause = function onpause() {
25634 this.emit(OFFLINE);
25635 };
25636
25637 _proto.onbeforeresume = function onbeforeresume() {
25638 this.emit(ONLINE);
25639 };
25640
25641 _proto.onreconnect = function onreconnect() {
25642 this.emit(RECONNECT);
25643 };
25644
25645 _proto.ondisconnected = function ondisconnected(event, from, to) {
25646 var _this4 = this;
25647
25648 var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
25649 var delay = from === OFFLINE ? 0 : DEFAULT_RETRY_STRATEGY.call(null, attempt);
25650 debug$3("schedule attempt=".concat(attempt, " delay=").concat(delay));
25651 this.emit(SCHEDULE, attempt, delay);
25652
25653 if (this.__scheduledRetry) {
25654 clearTimeout(this.__scheduledRetry);
25655 }
25656
25657 this.__scheduledRetry = setTimeout(function () {
25658 if (_this4.is('disconnected')) {
25659 _this4.retry(attempt);
25660 }
25661 }, delay);
25662 };
25663
25664 _proto.onretry = function onretry(event, from, to) {
25665 var _this5 = this;
25666
25667 var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
25668 this.emit(RETRY, attempt);
25669
25670 this._open().then(function () {
25671 return _this5.can('reconnect') && _this5.reconnect();
25672 }, function () {
25673 return _this5.can('fail') && _this5.fail(attempt + 1);
25674 });
25675 };
25676
25677 _proto.onerror = function onerror(event, from, to, error) {
25678 this.emit(ERROR, error);
25679 };
25680
25681 _proto.onclose = function onclose() {
25682 if (global$1.removeEventListener) {
25683 if (this.__pause) global$1.removeEventListener('offline', this.__pause);
25684 if (this.__resume) global$1.removeEventListener('online', this.__resume);
25685 }
25686 };
25687
25688 _proto.checkConnectionAvailability = function checkConnectionAvailability() {
25689 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'API';
25690
25691 if (!this.is('connected')) {
25692 var currentState = this.current;
25693 console.warn("".concat(name, " should not be called when the connection is ").concat(currentState));
25694
25695 if (this.is('disconnected') || this.is('reconnecting')) {
25696 console.warn('disconnect and reconnect event should be handled to avoid such calls.');
25697 }
25698
25699 throw new Error('Connection unavailable');
25700 }
25701 } // jsdoc-ignore-start
25702 ;
25703
25704 _proto. // jsdoc-ignore-end
25705 _ping = function _ping() {
25706 debug$3('ping');
25707
25708 try {
25709 this.ping();
25710 } catch (error) {
25711 console.warn("websocket ping error: ".concat(error.message));
25712 }
25713 };
25714
25715 _proto.ping = function ping() {
25716 if (this._ws.ping) {
25717 this._ws.ping();
25718 } else {
25719 console.warn("The WebSocket implement does not support sending ping frame.\n Override ping method to use application defined ping/pong mechanism.");
25720 }
25721 };
25722
25723 _proto._postponeTimeoutTimer = function _postponeTimeoutTimer() {
25724 var _this6 = this;
25725
25726 debug$3('_postponeTimeoutTimer');
25727
25728 this._clearTimeoutTimers();
25729
25730 this._timeoutTimer = setTimeout(function () {
25731 debug$3('timeout');
25732
25733 _this6.disconnect();
25734 }, TIMEOUT_TIME);
25735 };
25736
25737 _proto._clearTimeoutTimers = function _clearTimeoutTimers() {
25738 if (this._timeoutTimer) {
25739 clearTimeout(this._timeoutTimer);
25740 }
25741 };
25742
25743 _proto._startConnectionKeeper = function _startConnectionKeeper() {
25744 debug$3('start connection keeper');
25745 this._heartbeatTimer = setInterval(this._ping.bind(this), HEARTBEAT_TIME);
25746 var addListener = this._ws.addListener || this._ws.addEventListener;
25747
25748 if (!addListener) {
25749 debug$3('connection keeper disabled due to the lack of #addEventListener.');
25750 return;
25751 }
25752
25753 addListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
25754 addListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
25755
25756 this._postponeTimeoutTimer();
25757 };
25758
25759 _proto._stopConnectionKeeper = function _stopConnectionKeeper() {
25760 debug$3('stop connection keeper'); // websockets/ws#489
25761
25762 var removeListener = this._ws.removeListener || this._ws.removeEventListener;
25763
25764 if (removeListener) {
25765 removeListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
25766 removeListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
25767
25768 this._clearTimeoutTimers();
25769 }
25770
25771 if (this._heartbeatTimer) {
25772 clearInterval(this._heartbeatTimer);
25773 }
25774 };
25775
25776 _proto._handleClose = function _handleClose(event) {
25777 debug$3("ws closed [".concat(event.code, "] ").concat(event.reason)); // socket closed manually, ignore close event.
25778
25779 if (this.isFinished()) return;
25780 this.handleClose(event);
25781 };
25782
25783 _proto.handleClose = function handleClose() {
25784 // reconnect
25785 this.disconnect();
25786 } // jsdoc-ignore-start
25787 ;
25788
25789 _proto. // jsdoc-ignore-end
25790 send = function send(data) {
25791 debug$3('send', data);
25792
25793 this._ws.send(data);
25794 };
25795
25796 _proto._handleMessage = function _handleMessage(event) {
25797 debug$3('message', event.data);
25798 this.handleMessage(event.data);
25799 };
25800
25801 _proto.handleMessage = function handleMessage(message) {
25802 this.emit(MESSAGE, message);
25803 };
25804
25805 return WebSocketPlus;
25806}(EventEmitter), (_applyDecoratedDescriptor(_class.prototype, "_ping", [requireConnected], (0, _getOwnPropertyDescriptor2.default)(_class.prototype, "_ping"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "send", [requireConnected], (0, _getOwnPropertyDescriptor2.default)(_class.prototype, "send"), _class.prototype)), _class);
25807StateMachine.create({
25808 target: WebSocketPlus.prototype,
25809 initial: {
25810 state: 'initialized',
25811 event: 'init',
25812 defer: true
25813 },
25814 terminal: 'closed',
25815 events: [{
25816 name: 'open',
25817 from: 'initialized',
25818 to: 'connected'
25819 }, {
25820 name: 'disconnect',
25821 from: 'connected',
25822 to: 'disconnected'
25823 }, {
25824 name: 'retry',
25825 from: 'disconnected',
25826 to: 'reconnecting'
25827 }, {
25828 name: 'fail',
25829 from: 'reconnecting',
25830 to: 'disconnected'
25831 }, {
25832 name: 'reconnect',
25833 from: 'reconnecting',
25834 to: 'connected'
25835 }, {
25836 name: 'pause',
25837 from: ['connected', 'disconnected', 'reconnecting'],
25838 to: 'offline'
25839 }, {}, {
25840 name: 'resume',
25841 from: 'offline',
25842 to: 'disconnected'
25843 }, {
25844 name: 'close',
25845 from: ['connected', 'disconnected', 'reconnecting', 'offline'],
25846 to: 'closed'
25847 }, {
25848 name: 'throw',
25849 from: '*',
25850 to: 'error'
25851 }]
25852});
25853
25854var error = (0, _freeze2.default)({
25855 1000: {
25856 name: 'CLOSE_NORMAL'
25857 },
25858 1006: {
25859 name: 'CLOSE_ABNORMAL'
25860 },
25861 4100: {
25862 name: 'APP_NOT_AVAILABLE',
25863 message: 'App not exists or realtime message service is disabled.'
25864 },
25865 4102: {
25866 name: 'SIGNATURE_FAILED',
25867 message: 'Login signature mismatch.'
25868 },
25869 4103: {
25870 name: 'INVALID_LOGIN',
25871 message: 'Malformed clientId.'
25872 },
25873 4105: {
25874 name: 'SESSION_REQUIRED',
25875 message: 'Message sent before session opened.'
25876 },
25877 4107: {
25878 name: 'READ_TIMEOUT'
25879 },
25880 4108: {
25881 name: 'LOGIN_TIMEOUT'
25882 },
25883 4109: {
25884 name: 'FRAME_TOO_LONG'
25885 },
25886 4110: {
25887 name: 'INVALID_ORIGIN',
25888 message: 'Access denied by domain whitelist.'
25889 },
25890 4111: {
25891 name: 'SESSION_CONFLICT'
25892 },
25893 4112: {
25894 name: 'SESSION_TOKEN_EXPIRED'
25895 },
25896 4113: {
25897 name: 'APP_QUOTA_EXCEEDED',
25898 message: 'The daily active users limit exceeded.'
25899 },
25900 4116: {
25901 name: 'MESSAGE_SENT_QUOTA_EXCEEDED',
25902 message: 'Command sent too fast.'
25903 },
25904 4200: {
25905 name: 'INTERNAL_ERROR',
25906 message: 'Internal error, please contact LeanCloud for support.'
25907 },
25908 4301: {
25909 name: 'CONVERSATION_API_FAILED',
25910 message: 'Upstream Conversatoin API failed, see error.detail for details.'
25911 },
25912 4302: {
25913 name: 'CONVERSATION_SIGNATURE_FAILED',
25914 message: 'Conversation action signature mismatch.'
25915 },
25916 4303: {
25917 name: 'CONVERSATION_NOT_FOUND'
25918 },
25919 4304: {
25920 name: 'CONVERSATION_FULL'
25921 },
25922 4305: {
25923 name: 'CONVERSATION_REJECTED_BY_APP',
25924 message: 'Conversation action rejected by hook.'
25925 },
25926 4306: {
25927 name: 'CONVERSATION_UPDATE_FAILED'
25928 },
25929 4307: {
25930 name: 'CONVERSATION_READ_ONLY'
25931 },
25932 4308: {
25933 name: 'CONVERSATION_NOT_ALLOWED'
25934 },
25935 4309: {
25936 name: 'CONVERSATION_UPDATE_REJECTED',
25937 message: 'Conversation update rejected because the client is not a member.'
25938 },
25939 4310: {
25940 name: 'CONVERSATION_QUERY_FAILED',
25941 message: 'Conversation query failed because it is too expansive.'
25942 },
25943 4311: {
25944 name: 'CONVERSATION_LOG_FAILED'
25945 },
25946 4312: {
25947 name: 'CONVERSATION_LOG_REJECTED',
25948 message: 'Message query rejected because the client is not a member of the conversation.'
25949 },
25950 4313: {
25951 name: 'SYSTEM_CONVERSATION_REQUIRED'
25952 },
25953 4314: {
25954 name: 'NORMAL_CONVERSATION_REQUIRED'
25955 },
25956 4315: {
25957 name: 'CONVERSATION_BLACKLISTED',
25958 message: 'Blacklisted in the conversation.'
25959 },
25960 4316: {
25961 name: 'TRANSIENT_CONVERSATION_REQUIRED'
25962 },
25963 4317: {
25964 name: 'CONVERSATION_MEMBERSHIP_REQUIRED'
25965 },
25966 4318: {
25967 name: 'CONVERSATION_API_QUOTA_EXCEEDED',
25968 message: 'LeanCloud API quota exceeded. You may upgrade your plan.'
25969 },
25970 4323: {
25971 name: 'TEMPORARY_CONVERSATION_EXPIRED',
25972 message: 'Temporary conversation expired or does not exist.'
25973 },
25974 4401: {
25975 name: 'INVALID_MESSAGING_TARGET',
25976 message: 'Conversation does not exist or client is not a member.'
25977 },
25978 4402: {
25979 name: 'MESSAGE_REJECTED_BY_APP',
25980 message: 'Message rejected by hook.'
25981 },
25982 4403: {
25983 name: 'MESSAGE_OWNERSHIP_REQUIRED'
25984 },
25985 4404: {
25986 name: 'MESSAGE_NOT_FOUND'
25987 },
25988 4405: {
25989 name: 'MESSAGE_UPDATE_REJECTED_BY_APP',
25990 message: 'Message update rejected by hook.'
25991 },
25992 4406: {
25993 name: 'MESSAGE_EDIT_DISABLED'
25994 },
25995 4407: {
25996 name: 'MESSAGE_RECALL_DISABLED'
25997 },
25998 5130: {
25999 name: 'OWNER_PROMOTION_NOT_ALLOWED',
26000 message: "Updating a member's role to owner is not allowed."
26001 }
26002});
26003var ErrorCode = (0, _freeze2.default)((0, _keys2.default)(error).reduce(function (result, code) {
26004 return (0, _assign2.default)(result, _defineProperty({}, error[code].name, Number(code)));
26005}, {}));
26006var createError = function createError(_ref) {
26007 var code = _ref.code,
26008 reason = _ref.reason,
26009 appCode = _ref.appCode,
26010 detail = _ref.detail,
26011 errorMessage = _ref.error;
26012 var message = reason || detail || errorMessage;
26013 var name = reason;
26014
26015 if (!message && error[code]) {
26016 name = error[code].name;
26017 message = error[code].message || name;
26018 }
26019
26020 if (!message) {
26021 message = "Unknow Error: ".concat(code);
26022 }
26023
26024 var err = new Error(message);
26025 return (0, _assign2.default)(err, {
26026 code: code,
26027 appCode: appCode,
26028 detail: detail,
26029 name: name
26030 });
26031};
26032
26033var debug$4 = d('LC:Connection');
26034var COMMAND_TIMEOUT = 20000;
26035var EXPIRE = (0, _symbol2.default)('expire');
26036
26037var isIdempotentCommand = function isIdempotentCommand(command) {
26038 return !(command.cmd === CommandType.direct || command.cmd === CommandType.session && command.op === OpType.open || command.cmd === CommandType.conv && (command.op === OpType.start || command.op === OpType.update || command.op === OpType.members));
26039};
26040
26041var Connection = /*#__PURE__*/function (_WebSocketPlus) {
26042 _inheritsLoose(Connection, _WebSocketPlus);
26043
26044 function Connection(getUrl, _ref) {
26045 var _this;
26046
26047 var format = _ref.format,
26048 version = _ref.version;
26049 debug$4('initializing Connection');
26050 var protocolString = "lc.".concat(format, ".").concat(version);
26051 _this = _WebSocketPlus.call(this, getUrl, protocolString) || this;
26052 _this._protocolFormat = format;
26053 _this._commands = {};
26054 _this._serialId = 0;
26055 return _this;
26056 }
26057
26058 var _proto = Connection.prototype;
26059
26060 _proto.send = /*#__PURE__*/function () {
26061 var _send = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(command) {
26062 var _this2 = this;
26063
26064 var waitingForRespond,
26065 buffer,
26066 serialId,
26067 duplicatedCommand,
26068 message,
26069 promise,
26070 _args = arguments;
26071 return _regeneratorRuntime.wrap(function _callee$(_context) {
26072 while (1) {
26073 switch (_context.prev = _context.next) {
26074 case 0:
26075 waitingForRespond = _args.length > 1 && _args[1] !== undefined ? _args[1] : true;
26076
26077 if (!waitingForRespond) {
26078 _context.next = 11;
26079 break;
26080 }
26081
26082 if (!isIdempotentCommand(command)) {
26083 _context.next = 8;
26084 break;
26085 }
26086
26087 buffer = command.toArrayBuffer();
26088 duplicatedCommand = values(this._commands).find(function (_ref2) {
26089 var targetBuffer = _ref2.buffer,
26090 targetCommand = _ref2.command;
26091 return targetCommand.cmd === command.cmd && targetCommand.op === command.op && equalBuffer(targetBuffer, buffer);
26092 });
26093
26094 if (!duplicatedCommand) {
26095 _context.next = 8;
26096 break;
26097 }
26098
26099 console.warn("Duplicated command [cmd:".concat(command.cmd, " op:").concat(command.op, "] is throttled."));
26100 return _context.abrupt("return", duplicatedCommand.promise);
26101
26102 case 8:
26103 this._serialId += 1;
26104 serialId = this._serialId;
26105 command.i = serialId; // eslint-disable-line no-param-reassign
26106
26107 case 11:
26108 if (debug$4.enabled) debug$4('↑ %O sent', trim(command));
26109
26110 if (this._protocolFormat === 'proto2base64') {
26111 message = command.toBase64();
26112 } else if (command.toArrayBuffer) {
26113 message = command.toArrayBuffer();
26114 }
26115
26116 if (message) {
26117 _context.next = 15;
26118 break;
26119 }
26120
26121 throw new TypeError("".concat(command, " is not a GenericCommand"));
26122
26123 case 15:
26124 _WebSocketPlus.prototype.send.call(this, message);
26125
26126 if (waitingForRespond) {
26127 _context.next = 18;
26128 break;
26129 }
26130
26131 return _context.abrupt("return", undefined);
26132
26133 case 18:
26134 promise = new _promise2.default(function (resolve, reject) {
26135 _this2._commands[serialId] = {
26136 command: command,
26137 buffer: buffer,
26138 resolve: resolve,
26139 reject: reject,
26140 timeout: setTimeout(function () {
26141 if (_this2._commands[serialId]) {
26142 if (debug$4.enabled) debug$4('✗ %O timeout', trim(command));
26143 reject(createError({
26144 error: "Command Timeout [cmd:".concat(command.cmd, " op:").concat(command.op, "]"),
26145 name: 'COMMAND_TIMEOUT'
26146 }));
26147 delete _this2._commands[serialId];
26148 }
26149 }, COMMAND_TIMEOUT)
26150 };
26151 });
26152 this._commands[serialId].promise = promise;
26153 return _context.abrupt("return", promise);
26154
26155 case 21:
26156 case "end":
26157 return _context.stop();
26158 }
26159 }
26160 }, _callee, this);
26161 }));
26162
26163 function send(_x) {
26164 return _send.apply(this, arguments);
26165 }
26166
26167 return send;
26168 }();
26169
26170 _proto.handleMessage = function handleMessage(msg) {
26171 var message;
26172
26173 try {
26174 message = GenericCommand.decode(msg);
26175 if (debug$4.enabled) debug$4('↓ %O received', trim(message));
26176 } catch (e) {
26177 console.warn('Decode message failed:', e.message, msg);
26178 return;
26179 }
26180
26181 var serialId = message.i;
26182
26183 if (serialId) {
26184 if (this._commands[serialId]) {
26185 clearTimeout(this._commands[serialId].timeout);
26186
26187 if (message.cmd === CommandType.error) {
26188 this._commands[serialId].reject(createError(message.errorMessage));
26189 } else {
26190 this._commands[serialId].resolve(message);
26191 }
26192
26193 delete this._commands[serialId];
26194 } else {
26195 console.warn("Unexpected command received with serialId [".concat(serialId, "],\n which have timed out or never been requested."));
26196 }
26197 } else {
26198 switch (message.cmd) {
26199 case CommandType.error:
26200 {
26201 this.emit(ERROR, createError(message.errorMessage));
26202 return;
26203 }
26204
26205 case CommandType.goaway:
26206 {
26207 this.emit(EXPIRE);
26208 return;
26209 }
26210
26211 default:
26212 {
26213 this.emit(MESSAGE, message);
26214 }
26215 }
26216 }
26217 };
26218
26219 _proto.ping = function ping() {
26220 return this.send(new GenericCommand({
26221 cmd: CommandType.echo
26222 }))["catch"](function (error) {
26223 return debug$4('ping failed:', error);
26224 });
26225 };
26226
26227 return Connection;
26228}(WebSocketPlus);
26229
26230var debug$5 = d('LC:request');
26231var request = function request(_ref) {
26232 var _ref$method = _ref.method,
26233 method = _ref$method === void 0 ? 'GET' : _ref$method,
26234 _url = _ref.url,
26235 query = _ref.query,
26236 headers = _ref.headers,
26237 data = _ref.data,
26238 time = _ref.timeout;
26239 var url = _url;
26240
26241 if (query) {
26242 var queryString = (0, _keys2.default)(query).map(function (key) {
26243 var value = query[key];
26244 if (value === undefined) return undefined;
26245 var v = isPlainObject(value) ? (0, _stringify2.default)(value) : value;
26246 return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(v));
26247 }).filter(function (qs) {
26248 return qs;
26249 }).join('&');
26250 url = "".concat(url, "?").concat(queryString);
26251 }
26252
26253 debug$5('Req: %O %O %O', method, url, {
26254 headers: headers,
26255 data: data
26256 });
26257 var request = getAdapter('request');
26258 var promise = request(url, {
26259 method: method,
26260 headers: headers,
26261 data: data
26262 }).then(function (response) {
26263 if (response.ok === false) {
26264 var error = createError(response.data);
26265 error.response = response;
26266 throw error;
26267 }
26268
26269 debug$5('Res: %O %O %O', url, response.status, response.data);
26270 return response.data;
26271 })["catch"](function (error) {
26272 if (error.response) {
26273 debug$5('Error: %O %O %O', url, error.response.status, error.response.data);
26274 }
26275
26276 throw error;
26277 });
26278 return time ? promiseTimeout.timeout(promise, time) : promise;
26279};
26280
26281var applyDecorators = function applyDecorators(decorators, target) {
26282 if (decorators) {
26283 decorators.forEach(function (decorator) {
26284 try {
26285 decorator(target);
26286 } catch (error) {
26287 if (decorator._pluginName) {
26288 error.message += "[".concat(decorator._pluginName, "]");
26289 }
26290
26291 throw error;
26292 }
26293 });
26294 }
26295};
26296var applyDispatcher = function applyDispatcher(dispatchers, payload) {
26297 return ensureArray(dispatchers).reduce(function (resultPromise, dispatcher) {
26298 return resultPromise.then(function (shouldDispatch) {
26299 return shouldDispatch === false ? false : dispatcher.apply(void 0, _toConsumableArray(payload));
26300 })["catch"](function (error) {
26301 if (dispatcher._pluginName) {
26302 // eslint-disable-next-line no-param-reassign
26303 error.message += "[".concat(dispatcher._pluginName, "]");
26304 }
26305
26306 throw error;
26307 });
26308 }, _promise2.default.resolve(true));
26309};
26310
26311var version = "5.0.0-rc.4";
26312
26313function ownKeys$2(object, enumerableOnly) {
26314 var keys = (0, _keys2.default)(object);if (_getOwnPropertySymbols2.default) {
26315 var symbols = (0, _getOwnPropertySymbols2.default)(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {
26316 return (0, _getOwnPropertyDescriptor2.default)(object, sym).enumerable;
26317 });keys.push.apply(keys, symbols);
26318 }return keys;
26319}
26320
26321function _objectSpread$2(target) {
26322 for (var i = 1; i < arguments.length; i++) {
26323 var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {
26324 ownKeys$2(Object(source), true).forEach(function (key) {
26325 _defineProperty(target, key, source[key]);
26326 });
26327 } else if (_getOwnPropertyDescriptors2.default) {
26328 (0, _defineProperties2.default)(target, (0, _getOwnPropertyDescriptors2.default)(source));
26329 } else {
26330 ownKeys$2(Object(source)).forEach(function (key) {
26331 (0, _defineProperty3.default)(target, key, (0, _getOwnPropertyDescriptor2.default)(source, key));
26332 });
26333 }
26334 }return target;
26335}
26336var debug$6 = d('LC:Realtime');
26337var routerCache = new Cache('push-router');
26338var initializedApp = {};
26339
26340var Realtime = /*#__PURE__*/function (_EventEmitter) {
26341 _inheritsLoose(Realtime, _EventEmitter);
26342
26343 /**
26344 * @extends EventEmitter
26345 * @param {Object} options
26346 * @param {String} options.appId
26347 * @param {String} options.appKey (since 4.0.0)
26348 * @param {String|Object} [options.server] 指定服务器域名,中国节点应用此参数必填(since 4.0.0)
26349 * @param {Boolean} [options.pushOfflineMessages=false] 启用推送离线消息模式(默认为发送未读消息通知模式)
26350 * @param {Boolean} [options.noBinary=false] 设置 WebSocket 使用字符串格式收发消息(默认为二进制格式)。
26351 * 适用于 WebSocket 实现不支持二进制数据格式的情况
26352 * @param {Boolean} [options.ssl=true] 使用 wss 进行连接
26353 * @param {String|String[]} [options.RTMServers] 指定私有部署的 RTM 服务器地址(since 4.0.0)
26354 * @param {Plugin[]} [options.plugins] 加载插件(since 3.1.0)
26355 */
26356 function Realtime(_ref) {
26357 var _this2;
26358
26359 var plugins = _ref.plugins,
26360 options = _objectWithoutProperties(_ref, ["plugins"]);
26361
26362 debug$6('initializing Realtime %s %O', version, options);
26363 _this2 = _EventEmitter.call(this) || this;
26364 var appId = options.appId;
26365
26366 if (typeof appId !== 'string') {
26367 throw new TypeError("appId [".concat(appId, "] is not a string"));
26368 }
26369
26370 if (initializedApp[appId]) {
26371 throw new Error("App [".concat(appId, "] is aleady initialized."));
26372 }
26373
26374 initializedApp[appId] = true;
26375
26376 if (typeof options.appKey !== 'string') {
26377 throw new TypeError("appKey [".concat(options.appKey, "] is not a string"));
26378 }
26379
26380 if (isCNApp(appId)) {
26381 if (!options.server) {
26382 throw new TypeError("server option is required for apps from CN region");
26383 }
26384 }
26385
26386 _this2._options = _objectSpread$2({
26387 appId: undefined,
26388 appKey: undefined,
26389 pushOfflineMessages: false,
26390 noBinary: false,
26391 ssl: true,
26392 RTMServerName: typeof process !== 'undefined' ? process.env.RTM_SERVER_NAME : undefined
26393 }, options);
26394 _this2._cache = new Cache('endpoints');
26395
26396 var _this = internal(_assertThisInitialized(_this2));
26397
26398 _this.clients = new _set2.default();
26399 _this.pendingClients = new _set2.default();
26400 var mergedPlugins = [].concat(_toConsumableArray(ensureArray(Realtime.__preRegisteredPlugins)), _toConsumableArray(ensureArray(plugins)));
26401 debug$6('Using plugins %o', mergedPlugins.map(function (plugin) {
26402 return plugin.name;
26403 }));
26404 _this2._plugins = mergedPlugins.reduce(function (result, plugin) {
26405 (0, _keys2.default)(plugin).forEach(function (hook) {
26406 if ({}.hasOwnProperty.call(plugin, hook) && hook !== 'name') {
26407 if (plugin.name) {
26408 ensureArray(plugin[hook]).forEach(function (value) {
26409 // eslint-disable-next-line no-param-reassign
26410 value._pluginName = plugin.name;
26411 });
26412 } // eslint-disable-next-line no-param-reassign
26413
26414
26415 result[hook] = ensureArray(result[hook]).concat(plugin[hook]);
26416 }
26417 });
26418 return result;
26419 }, {}); // onRealtimeCreate hook
26420
26421 applyDecorators(_this2._plugins.onRealtimeCreate, _assertThisInitialized(_this2));
26422 return _this2;
26423 }
26424
26425 var _proto = Realtime.prototype;
26426
26427 _proto._request = /*#__PURE__*/function () {
26428 var _request2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref2) {
26429 var method, _url, _ref2$version, version, path, query, headers, data, url, _this$_options, appId, server, _yield$this$construct, api;
26430
26431 return _regeneratorRuntime.wrap(function _callee$(_context) {
26432 while (1) {
26433 switch (_context.prev = _context.next) {
26434 case 0:
26435 method = _ref2.method, _url = _ref2.url, _ref2$version = _ref2.version, version = _ref2$version === void 0 ? '1.1' : _ref2$version, path = _ref2.path, query = _ref2.query, headers = _ref2.headers, data = _ref2.data;
26436 url = _url;
26437
26438 if (url) {
26439 _context.next = 9;
26440 break;
26441 }
26442
26443 _this$_options = this._options, appId = _this$_options.appId, server = _this$_options.server;
26444 _context.next = 6;
26445 return this.constructor._getServerUrls({
26446 appId: appId,
26447 server: server
26448 });
26449
26450 case 6:
26451 _yield$this$construct = _context.sent;
26452 api = _yield$this$construct.api;
26453 url = "".concat(api, "/").concat(version).concat(path);
26454
26455 case 9:
26456 return _context.abrupt("return", request({
26457 url: url,
26458 method: method,
26459 query: query,
26460 headers: _objectSpread$2({
26461 'X-LC-Id': this._options.appId,
26462 'X-LC-Key': this._options.appKey
26463 }, headers),
26464 data: data
26465 }));
26466
26467 case 10:
26468 case "end":
26469 return _context.stop();
26470 }
26471 }
26472 }, _callee, this);
26473 }));
26474
26475 function _request(_x) {
26476 return _request2.apply(this, arguments);
26477 }
26478
26479 return _request;
26480 }();
26481
26482 _proto._open = function _open() {
26483 var _this3 = this;
26484
26485 if (this._openPromise) return this._openPromise;
26486 var format = 'protobuf2';
26487
26488 if (this._options.noBinary) {
26489 // 不发送 binary data,fallback to base64 string
26490 format = 'proto2base64';
26491 }
26492
26493 var version = 3;
26494
26495 if (this._options.pushOfflineMessages) {
26496 // 不推送离线消息,而是发送对话的未读通知
26497 version = 1;
26498 }
26499
26500 var protocol = {
26501 format: format,
26502 version: version
26503 };
26504 this._openPromise = new _promise2.default(function (resolve, reject) {
26505 debug$6('No connection established, create a new one.');
26506 var connection = new Connection(function () {
26507 return _this3._getRTMServers(_this3._options);
26508 }, protocol);
26509 connection.on(OPEN, function () {
26510 return resolve(connection);
26511 }).on(ERROR, reject).on(EXPIRE, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
26512 return _regeneratorRuntime.wrap(function _callee2$(_context2) {
26513 while (1) {
26514 switch (_context2.prev = _context2.next) {
26515 case 0:
26516 debug$6('Connection expired. Refresh endpoints.');
26517
26518 _this3._cache.set('endpoints', null, 0);
26519
26520 _context2.next = 4;
26521 return _this3._getRTMServers(_this3._options);
26522
26523 case 4:
26524 connection.urls = _context2.sent;
26525 connection.disconnect();
26526
26527 case 6:
26528 case "end":
26529 return _context2.stop();
26530 }
26531 }
26532 }, _callee2);
26533 }))).on(MESSAGE, _this3._dispatchCommand.bind(_this3));
26534 /**
26535 * 连接断开。
26536 * 连接断开可能是因为 SDK 进入了离线状态(see {@link Realtime#event:OFFLINE}),或长时间没有收到服务器心跳。
26537 * 连接断开后所有的网络操作都会失败,请在连接断开后禁用相关的 UI 元素。
26538 * @event Realtime#DISCONNECT
26539 */
26540
26541 /**
26542 * 计划在一段时间后尝试重新连接
26543 * @event Realtime#SCHEDULE
26544 * @param {Number} attempt 尝试重连的次数
26545 * @param {Number} delay 延迟的毫秒数
26546 */
26547
26548 /**
26549 * 正在尝试重新连接
26550 * @event Realtime#RETRY
26551 * @param {Number} attempt 尝试重连的次数
26552 */
26553
26554 /**
26555 * 连接恢复正常。
26556 * 请重新启用在 {@link Realtime#event:DISCONNECT} 事件中禁用的相关 UI 元素
26557 * @event Realtime#RECONNECT
26558 */
26559
26560 /**
26561 * 客户端连接断开
26562 * @event IMClient#DISCONNECT
26563 * @see Realtime#event:DISCONNECT
26564 * @since 3.2.0
26565 */
26566
26567 /**
26568 * 计划在一段时间后尝试重新连接
26569 * @event IMClient#SCHEDULE
26570 * @param {Number} attempt 尝试重连的次数
26571 * @param {Number} delay 延迟的毫秒数
26572 * @since 3.2.0
26573 */
26574
26575 /**
26576 * 正在尝试重新连接
26577 * @event IMClient#RETRY
26578 * @param {Number} attempt 尝试重连的次数
26579 * @since 3.2.0
26580 */
26581
26582 /**
26583 * 客户端进入离线状态。
26584 * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
26585 * @event Realtime#OFFLINE
26586 * @since 3.4.0
26587 */
26588
26589 /**
26590 * 客户端恢复在线状态
26591 * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
26592 * @event Realtime#ONLINE
26593 * @since 3.4.0
26594 */
26595
26596 /**
26597 * 进入离线状态。
26598 * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
26599 * @event IMClient#OFFLINE
26600 * @since 3.4.0
26601 */
26602
26603 /**
26604 * 恢复在线状态
26605 * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
26606 * @event IMClient#ONLINE
26607 * @since 3.4.0
26608 */
26609 // event proxy
26610
26611 [DISCONNECT, RECONNECT, RETRY, SCHEDULE, OFFLINE, ONLINE].forEach(function (event) {
26612 return connection.on(event, function () {
26613 for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
26614 payload[_key] = arguments[_key];
26615 }
26616
26617 debug$6("".concat(event, " event emitted. %o"), payload);
26618
26619 _this3.emit.apply(_this3, [event].concat(payload));
26620
26621 if (event !== RECONNECT) {
26622 internal(_this3).clients.forEach(function (client) {
26623 client.emit.apply(client, [event].concat(payload));
26624 });
26625 }
26626 });
26627 }); // override handleClose
26628
26629 connection.handleClose = function handleClose(event) {
26630 var isFatal = [ErrorCode.APP_NOT_AVAILABLE, ErrorCode.INVALID_LOGIN, ErrorCode.INVALID_ORIGIN].some(function (errorCode) {
26631 return errorCode === event.code;
26632 });
26633
26634 if (isFatal) {
26635 // in these cases, SDK should throw.
26636 this["throw"](createError(event));
26637 } else {
26638 // reconnect
26639 this.disconnect();
26640 }
26641 };
26642
26643 internal(_this3).connection = connection;
26644 });
26645 return this._openPromise;
26646 };
26647
26648 _proto._getRTMServers = /*#__PURE__*/function () {
26649 var _getRTMServers2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(options) {
26650 var info, cachedEndPoints, _info, server, secondary, ttl;
26651
26652 return _regeneratorRuntime.wrap(function _callee3$(_context3) {
26653 while (1) {
26654 switch (_context3.prev = _context3.next) {
26655 case 0:
26656 if (!options.RTMServers) {
26657 _context3.next = 2;
26658 break;
26659 }
26660
26661 return _context3.abrupt("return", shuffle(ensureArray(options.RTMServers)));
26662
26663 case 2:
26664 cachedEndPoints = this._cache.get('endpoints');
26665
26666 if (!cachedEndPoints) {
26667 _context3.next = 7;
26668 break;
26669 }
26670
26671 info = cachedEndPoints;
26672 _context3.next = 14;
26673 break;
26674
26675 case 7:
26676 _context3.next = 9;
26677 return this.constructor._fetchRTMServers(options);
26678
26679 case 9:
26680 info = _context3.sent;
26681 _info = info, server = _info.server, secondary = _info.secondary, ttl = _info.ttl;
26682
26683 if (!(typeof server !== 'string' && typeof secondary !== 'string' && typeof ttl !== 'number')) {
26684 _context3.next = 13;
26685 break;
26686 }
26687
26688 throw new Error("malformed RTM route response: ".concat((0, _stringify2.default)(info)));
26689
26690 case 13:
26691 this._cache.set('endpoints', info, info.ttl * 1000);
26692
26693 case 14:
26694 debug$6('endpoint info: %O', info);
26695 return _context3.abrupt("return", [info.server, info.secondary]);
26696
26697 case 16:
26698 case "end":
26699 return _context3.stop();
26700 }
26701 }
26702 }, _callee3, this);
26703 }));
26704
26705 function _getRTMServers(_x2) {
26706 return _getRTMServers2.apply(this, arguments);
26707 }
26708
26709 return _getRTMServers;
26710 }();
26711
26712 Realtime._getServerUrls = /*#__PURE__*/function () {
26713 var _getServerUrls2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(_ref4) {
26714 var appId, server, cachedRouter, defaultProtocol;
26715 return _regeneratorRuntime.wrap(function _callee4$(_context4) {
26716 while (1) {
26717 switch (_context4.prev = _context4.next) {
26718 case 0:
26719 appId = _ref4.appId, server = _ref4.server;
26720 debug$6('fetch server urls');
26721
26722 if (!server) {
26723 _context4.next = 6;
26724 break;
26725 }
26726
26727 if (!(typeof server !== 'string')) {
26728 _context4.next = 5;
26729 break;
26730 }
26731
26732 return _context4.abrupt("return", server);
26733
26734 case 5:
26735 return _context4.abrupt("return", {
26736 RTMRouter: server,
26737 api: server
26738 });
26739
26740 case 6:
26741 cachedRouter = routerCache.get(appId);
26742
26743 if (!cachedRouter) {
26744 _context4.next = 9;
26745 break;
26746 }
26747
26748 return _context4.abrupt("return", cachedRouter);
26749
26750 case 9:
26751 defaultProtocol = 'https://';
26752 return _context4.abrupt("return", request({
26753 url: 'https://app-router.com/2/route',
26754 query: {
26755 appId: appId
26756 },
26757 timeout: 20000
26758 }).then(tap(debug$6)).then(function (_ref5) {
26759 var RTMRouterServer = _ref5.rtm_router_server,
26760 APIServer = _ref5.api_server,
26761 _ref5$ttl = _ref5.ttl,
26762 ttl = _ref5$ttl === void 0 ? 3600 : _ref5$ttl;
26763
26764 if (!RTMRouterServer) {
26765 throw new Error('rtm router not exists');
26766 }
26767
26768 var serverUrls = {
26769 RTMRouter: "".concat(defaultProtocol).concat(RTMRouterServer),
26770 api: "".concat(defaultProtocol).concat(APIServer)
26771 };
26772 routerCache.set(appId, serverUrls, ttl * 1000);
26773 return serverUrls;
26774 })["catch"](function () {
26775 var id = appId.slice(0, 8).toLowerCase();
26776 var domain = 'lncldglobal.com';
26777 return {
26778 RTMRouter: "".concat(defaultProtocol).concat(id, ".rtm.").concat(domain),
26779 api: "".concat(defaultProtocol).concat(id, ".api.").concat(domain)
26780 };
26781 }));
26782
26783 case 11:
26784 case "end":
26785 return _context4.stop();
26786 }
26787 }
26788 }, _callee4);
26789 }));
26790
26791 function _getServerUrls(_x3) {
26792 return _getServerUrls2.apply(this, arguments);
26793 }
26794
26795 return _getServerUrls;
26796 }();
26797
26798 Realtime._fetchRTMServers = function _fetchRTMServers(_ref6) {
26799 var appId = _ref6.appId,
26800 ssl = _ref6.ssl,
26801 server = _ref6.server,
26802 RTMServerName = _ref6.RTMServerName;
26803 debug$6('fetch endpoint info');
26804 return this._getServerUrls({
26805 appId: appId,
26806 server: server
26807 }).then(tap(debug$6)).then(function (_ref7) {
26808 var RTMRouter = _ref7.RTMRouter;
26809 return request({
26810 url: "".concat(RTMRouter, "/v1/route"),
26811 query: {
26812 appId: appId,
26813 secure: ssl,
26814 features: isWeapp ? 'wechat' : undefined,
26815 server: RTMServerName,
26816 _t: Date.now()
26817 },
26818 timeout: 20000
26819 }).then(tap(debug$6));
26820 });
26821 };
26822
26823 _proto._close = function _close() {
26824 if (this._openPromise) {
26825 this._openPromise.then(function (connection) {
26826 return connection.close();
26827 });
26828 }
26829
26830 delete this._openPromise;
26831 }
26832 /**
26833 * 手动进行重连。
26834 * SDK 在网络出现异常时会自动按照一定的时间间隔尝试重连,调用该方法会立即尝试重连并重置重连尝试计数器。
26835 * 只能在 `SCHEDULE` 事件之后,`RETRY` 事件之前调用,如果当前网络正常或者正在进行重连,调用该方法会抛异常。
26836 */
26837 ;
26838
26839 _proto.retry = function retry() {
26840 var _internal = internal(this),
26841 connection = _internal.connection;
26842
26843 if (!connection) {
26844 throw new Error('no connection established');
26845 }
26846
26847 if (connection.cannot('retry')) {
26848 throw new Error("retrying not allowed when not disconnected. the connection is now ".concat(connection.current));
26849 }
26850
26851 return connection.retry();
26852 }
26853 /**
26854 * 暂停,使 SDK 进入离线状态。
26855 * 你可以在网络断开、应用进入后台等时刻调用该方法让 SDK 进入离线状态,离线状态下不会尝试重连。
26856 * 在浏览器中 SDK 会自动监听网络变化,因此无需手动调用该方法。
26857 *
26858 * @since 3.4.0
26859 * @see Realtime#event:OFFLINE
26860 */
26861 ;
26862
26863 _proto.pause = function pause() {
26864 // 这个方法常常在网络断开、进入后台时被调用,此时 connection 可能没有建立或者已经 close。
26865 // 因此不像 retry,这个方法应该尽可能 loose
26866 var _internal2 = internal(this),
26867 connection = _internal2.connection;
26868
26869 if (!connection) return;
26870 if (connection.can('pause')) connection.pause();
26871 }
26872 /**
26873 * 恢复在线状态。
26874 * 你可以在网络恢复、应用回到前台等时刻调用该方法让 SDK 恢复在线状态,恢复在线状态后 SDK 会开始尝试重连。
26875 *
26876 * @since 3.4.0
26877 * @see Realtime#event:ONLINE
26878 */
26879 ;
26880
26881 _proto.resume = function resume() {
26882 // 与 pause 一样,这个方法应该尽可能 loose
26883 var _internal3 = internal(this),
26884 connection = _internal3.connection;
26885
26886 if (!connection) return;
26887 if (connection.can('resume')) connection.resume();
26888 };
26889
26890 _proto._registerPending = function _registerPending(value) {
26891 internal(this).pendingClients.add(value);
26892 };
26893
26894 _proto._deregisterPending = function _deregisterPending(client) {
26895 internal(this).pendingClients["delete"](client);
26896 };
26897
26898 _proto._register = function _register(client) {
26899 internal(this).clients.add(client);
26900 };
26901
26902 _proto._deregister = function _deregister(client) {
26903 var _this = internal(this);
26904
26905 _this.clients["delete"](client);
26906
26907 if (_this.clients.size + _this.pendingClients.size === 0) {
26908 this._close();
26909 }
26910 };
26911
26912 _proto._dispatchCommand = function _dispatchCommand(command) {
26913 return applyDispatcher(this._plugins.beforeCommandDispatch, [command, this]).then(function (shouldDispatch) {
26914 // no plugin handled this command
26915 if (shouldDispatch) return debug$6('[WARN] Unexpected message received: %O', trim(command));
26916 return false;
26917 });
26918 };
26919
26920 return Realtime;
26921}(EventEmitter); // For test purpose only
26922
26923var polyfilledPromise = _promise2.default;
26924
26925exports.EventEmitter = EventEmitter;
26926exports.Promise = polyfilledPromise;
26927exports.Protocals = message;
26928exports.Protocols = message;
26929exports.Realtime = Realtime;
26930exports.debug = debug$2;
26931exports.getAdapter = getAdapter;
26932exports.setAdapters = setAdapters;
26933//# sourceMappingURL=core.js.map
26934/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(66)))
26935
26936/***/ }),
26937/* 380 */
26938/***/ (function(module, exports, __webpack_require__) {
26939
26940__webpack_require__(59);
26941__webpack_require__(35);
26942__webpack_require__(37);
26943__webpack_require__(381);
26944__webpack_require__(385);
26945__webpack_require__(388);
26946__webpack_require__(389);
26947module.exports = __webpack_require__(1).Set;
26948
26949
26950/***/ }),
26951/* 381 */
26952/***/ (function(module, exports, __webpack_require__) {
26953
26954"use strict";
26955
26956var strong = __webpack_require__(382);
26957var validate = __webpack_require__(58);
26958var SET = 'Set';
26959
26960// 23.2 Set Objects
26961module.exports = __webpack_require__(194)(SET, function (get) {
26962 return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
26963}, {
26964 // 23.2.3.1 Set.prototype.add(value)
26965 add: function add(value) {
26966 return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value);
26967 }
26968}, strong);
26969
26970
26971/***/ }),
26972/* 382 */
26973/***/ (function(module, exports, __webpack_require__) {
26974
26975"use strict";
26976
26977var dP = __webpack_require__(20).f;
26978var create = __webpack_require__(60);
26979var redefineAll = __webpack_require__(65);
26980var ctx = __webpack_require__(22);
26981var anInstance = __webpack_require__(64);
26982var forOf = __webpack_require__(38);
26983var $iterDefine = __webpack_require__(82);
26984var step = __webpack_require__(120);
26985var setSpecies = __webpack_require__(127);
26986var DESCRIPTORS = __webpack_require__(16);
26987var fastKey = __webpack_require__(45).fastKey;
26988var validate = __webpack_require__(58);
26989var SIZE = DESCRIPTORS ? '_s' : 'size';
26990
26991var getEntry = function (that, key) {
26992 // fast case
26993 var index = fastKey(key);
26994 var entry;
26995 if (index !== 'F') return that._i[index];
26996 // frozen object case
26997 for (entry = that._f; entry; entry = entry.n) {
26998 if (entry.k == key) return entry;
26999 }
27000};
27001
27002module.exports = {
27003 getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
27004 var C = wrapper(function (that, iterable) {
27005 anInstance(that, C, NAME, '_i');
27006 that._t = NAME; // collection type
27007 that._i = create(null); // index
27008 that._f = undefined; // first entry
27009 that._l = undefined; // last entry
27010 that[SIZE] = 0; // size
27011 if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
27012 });
27013 redefineAll(C.prototype, {
27014 // 23.1.3.1 Map.prototype.clear()
27015 // 23.2.3.2 Set.prototype.clear()
27016 clear: function clear() {
27017 for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) {
27018 entry.r = true;
27019 if (entry.p) entry.p = entry.p.n = undefined;
27020 delete data[entry.i];
27021 }
27022 that._f = that._l = undefined;
27023 that[SIZE] = 0;
27024 },
27025 // 23.1.3.3 Map.prototype.delete(key)
27026 // 23.2.3.4 Set.prototype.delete(value)
27027 'delete': function (key) {
27028 var that = validate(this, NAME);
27029 var entry = getEntry(that, key);
27030 if (entry) {
27031 var next = entry.n;
27032 var prev = entry.p;
27033 delete that._i[entry.i];
27034 entry.r = true;
27035 if (prev) prev.n = next;
27036 if (next) next.p = prev;
27037 if (that._f == entry) that._f = next;
27038 if (that._l == entry) that._l = prev;
27039 that[SIZE]--;
27040 } return !!entry;
27041 },
27042 // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
27043 // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
27044 forEach: function forEach(callbackfn /* , that = undefined */) {
27045 validate(this, NAME);
27046 var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);
27047 var entry;
27048 while (entry = entry ? entry.n : this._f) {
27049 f(entry.v, entry.k, this);
27050 // revert to the last existing entry
27051 while (entry && entry.r) entry = entry.p;
27052 }
27053 },
27054 // 23.1.3.7 Map.prototype.has(key)
27055 // 23.2.3.7 Set.prototype.has(value)
27056 has: function has(key) {
27057 return !!getEntry(validate(this, NAME), key);
27058 }
27059 });
27060 if (DESCRIPTORS) dP(C.prototype, 'size', {
27061 get: function () {
27062 return validate(this, NAME)[SIZE];
27063 }
27064 });
27065 return C;
27066 },
27067 def: function (that, key, value) {
27068 var entry = getEntry(that, key);
27069 var prev, index;
27070 // change existing entry
27071 if (entry) {
27072 entry.v = value;
27073 // create new entry
27074 } else {
27075 that._l = entry = {
27076 i: index = fastKey(key, true), // <- index
27077 k: key, // <- key
27078 v: value, // <- value
27079 p: prev = that._l, // <- previous entry
27080 n: undefined, // <- next entry
27081 r: false // <- removed
27082 };
27083 if (!that._f) that._f = entry;
27084 if (prev) prev.n = entry;
27085 that[SIZE]++;
27086 // add to index
27087 if (index !== 'F') that._i[index] = entry;
27088 } return that;
27089 },
27090 getEntry: getEntry,
27091 setStrong: function (C, NAME, IS_MAP) {
27092 // add .keys, .values, .entries, [@@iterator]
27093 // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
27094 $iterDefine(C, NAME, function (iterated, kind) {
27095 this._t = validate(iterated, NAME); // target
27096 this._k = kind; // kind
27097 this._l = undefined; // previous
27098 }, function () {
27099 var that = this;
27100 var kind = that._k;
27101 var entry = that._l;
27102 // revert to the last existing entry
27103 while (entry && entry.r) entry = entry.p;
27104 // get next entry
27105 if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) {
27106 // or finish the iteration
27107 that._t = undefined;
27108 return step(1);
27109 }
27110 // return step by kind
27111 if (kind == 'keys') return step(0, entry.k);
27112 if (kind == 'values') return step(0, entry.v);
27113 return step(0, [entry.k, entry.v]);
27114 }, IS_MAP ? 'entries' : 'values', !IS_MAP, true);
27115
27116 // add [@@species], 23.1.2.2, 23.2.2.2
27117 setSpecies(NAME);
27118 }
27119};
27120
27121
27122/***/ }),
27123/* 383 */
27124/***/ (function(module, exports, __webpack_require__) {
27125
27126// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
27127var speciesConstructor = __webpack_require__(384);
27128
27129module.exports = function (original, length) {
27130 return new (speciesConstructor(original))(length);
27131};
27132
27133
27134/***/ }),
27135/* 384 */
27136/***/ (function(module, exports, __webpack_require__) {
27137
27138var isObject = __webpack_require__(9);
27139var isArray = __webpack_require__(184);
27140var SPECIES = __webpack_require__(8)('species');
27141
27142module.exports = function (original) {
27143 var C;
27144 if (isArray(original)) {
27145 C = original.constructor;
27146 // cross-realm fallback
27147 if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
27148 if (isObject(C)) {
27149 C = C[SPECIES];
27150 if (C === null) C = undefined;
27151 }
27152 } return C === undefined ? Array : C;
27153};
27154
27155
27156/***/ }),
27157/* 385 */
27158/***/ (function(module, exports, __webpack_require__) {
27159
27160// https://github.com/DavidBruant/Map-Set.prototype.toJSON
27161var $export = __webpack_require__(4);
27162
27163$export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(386)('Set') });
27164
27165
27166/***/ }),
27167/* 386 */
27168/***/ (function(module, exports, __webpack_require__) {
27169
27170// https://github.com/DavidBruant/Map-Set.prototype.toJSON
27171var classof = __webpack_require__(63);
27172var from = __webpack_require__(387);
27173module.exports = function (NAME) {
27174 return function toJSON() {
27175 if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic");
27176 return from(this);
27177 };
27178};
27179
27180
27181/***/ }),
27182/* 387 */
27183/***/ (function(module, exports, __webpack_require__) {
27184
27185var forOf = __webpack_require__(38);
27186
27187module.exports = function (iter, ITERATOR) {
27188 var result = [];
27189 forOf(iter, false, result.push, result, ITERATOR);
27190 return result;
27191};
27192
27193
27194/***/ }),
27195/* 388 */
27196/***/ (function(module, exports, __webpack_require__) {
27197
27198// https://tc39.github.io/proposal-setmap-offrom/#sec-set.of
27199__webpack_require__(195)('Set');
27200
27201
27202/***/ }),
27203/* 389 */
27204/***/ (function(module, exports, __webpack_require__) {
27205
27206// https://tc39.github.io/proposal-setmap-offrom/#sec-set.from
27207__webpack_require__(196)('Set');
27208
27209
27210/***/ }),
27211/* 390 */
27212/***/ (function(module, exports, __webpack_require__) {
27213
27214module.exports = { "default": __webpack_require__(391), __esModule: true };
27215
27216/***/ }),
27217/* 391 */
27218/***/ (function(module, exports, __webpack_require__) {
27219
27220__webpack_require__(59);
27221__webpack_require__(37);
27222__webpack_require__(392);
27223__webpack_require__(394);
27224__webpack_require__(395);
27225module.exports = __webpack_require__(1).WeakMap;
27226
27227
27228/***/ }),
27229/* 392 */
27230/***/ (function(module, exports, __webpack_require__) {
27231
27232"use strict";
27233
27234var global = __webpack_require__(5);
27235var each = __webpack_require__(114)(0);
27236var redefine = __webpack_require__(85);
27237var meta = __webpack_require__(45);
27238var assign = __webpack_require__(197);
27239var weak = __webpack_require__(393);
27240var isObject = __webpack_require__(9);
27241var validate = __webpack_require__(58);
27242var NATIVE_WEAK_MAP = __webpack_require__(58);
27243var IS_IE11 = !global.ActiveXObject && 'ActiveXObject' in global;
27244var WEAK_MAP = 'WeakMap';
27245var getWeak = meta.getWeak;
27246var isExtensible = Object.isExtensible;
27247var uncaughtFrozenStore = weak.ufstore;
27248var InternalMap;
27249
27250var wrapper = function (get) {
27251 return function WeakMap() {
27252 return get(this, arguments.length > 0 ? arguments[0] : undefined);
27253 };
27254};
27255
27256var methods = {
27257 // 23.3.3.3 WeakMap.prototype.get(key)
27258 get: function get(key) {
27259 if (isObject(key)) {
27260 var data = getWeak(key);
27261 if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key);
27262 return data ? data[this._i] : undefined;
27263 }
27264 },
27265 // 23.3.3.5 WeakMap.prototype.set(key, value)
27266 set: function set(key, value) {
27267 return weak.def(validate(this, WEAK_MAP), key, value);
27268 }
27269};
27270
27271// 23.3 WeakMap Objects
27272var $WeakMap = module.exports = __webpack_require__(194)(WEAK_MAP, wrapper, methods, weak, true, true);
27273
27274// IE11 WeakMap frozen keys fix
27275if (NATIVE_WEAK_MAP && IS_IE11) {
27276 InternalMap = weak.getConstructor(wrapper, WEAK_MAP);
27277 assign(InternalMap.prototype, methods);
27278 meta.NEED = true;
27279 each(['delete', 'has', 'get', 'set'], function (key) {
27280 var proto = $WeakMap.prototype;
27281 var method = proto[key];
27282 redefine(proto, key, function (a, b) {
27283 // store frozen objects on internal weakmap shim
27284 if (isObject(a) && !isExtensible(a)) {
27285 if (!this._f) this._f = new InternalMap();
27286 var result = this._f[key](a, b);
27287 return key == 'set' ? this : result;
27288 // store all the rest on native weakmap
27289 } return method.call(this, a, b);
27290 });
27291 });
27292}
27293
27294
27295/***/ }),
27296/* 393 */
27297/***/ (function(module, exports, __webpack_require__) {
27298
27299"use strict";
27300
27301var redefineAll = __webpack_require__(65);
27302var getWeak = __webpack_require__(45).getWeak;
27303var anObject = __webpack_require__(15);
27304var isObject = __webpack_require__(9);
27305var anInstance = __webpack_require__(64);
27306var forOf = __webpack_require__(38);
27307var createArrayMethod = __webpack_require__(114);
27308var $has = __webpack_require__(25);
27309var validate = __webpack_require__(58);
27310var arrayFind = createArrayMethod(5);
27311var arrayFindIndex = createArrayMethod(6);
27312var id = 0;
27313
27314// fallback for uncaught frozen keys
27315var uncaughtFrozenStore = function (that) {
27316 return that._l || (that._l = new UncaughtFrozenStore());
27317};
27318var UncaughtFrozenStore = function () {
27319 this.a = [];
27320};
27321var findUncaughtFrozen = function (store, key) {
27322 return arrayFind(store.a, function (it) {
27323 return it[0] === key;
27324 });
27325};
27326UncaughtFrozenStore.prototype = {
27327 get: function (key) {
27328 var entry = findUncaughtFrozen(this, key);
27329 if (entry) return entry[1];
27330 },
27331 has: function (key) {
27332 return !!findUncaughtFrozen(this, key);
27333 },
27334 set: function (key, value) {
27335 var entry = findUncaughtFrozen(this, key);
27336 if (entry) entry[1] = value;
27337 else this.a.push([key, value]);
27338 },
27339 'delete': function (key) {
27340 var index = arrayFindIndex(this.a, function (it) {
27341 return it[0] === key;
27342 });
27343 if (~index) this.a.splice(index, 1);
27344 return !!~index;
27345 }
27346};
27347
27348module.exports = {
27349 getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
27350 var C = wrapper(function (that, iterable) {
27351 anInstance(that, C, NAME, '_i');
27352 that._t = NAME; // collection type
27353 that._i = id++; // collection id
27354 that._l = undefined; // leak store for uncaught frozen objects
27355 if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
27356 });
27357 redefineAll(C.prototype, {
27358 // 23.3.3.2 WeakMap.prototype.delete(key)
27359 // 23.4.3.3 WeakSet.prototype.delete(value)
27360 'delete': function (key) {
27361 if (!isObject(key)) return false;
27362 var data = getWeak(key);
27363 if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key);
27364 return data && $has(data, this._i) && delete data[this._i];
27365 },
27366 // 23.3.3.4 WeakMap.prototype.has(key)
27367 // 23.4.3.4 WeakSet.prototype.has(value)
27368 has: function has(key) {
27369 if (!isObject(key)) return false;
27370 var data = getWeak(key);
27371 if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key);
27372 return data && $has(data, this._i);
27373 }
27374 });
27375 return C;
27376 },
27377 def: function (that, key, value) {
27378 var data = getWeak(anObject(key), true);
27379 if (data === true) uncaughtFrozenStore(that).set(key, value);
27380 else data[that._i] = value;
27381 return that;
27382 },
27383 ufstore: uncaughtFrozenStore
27384};
27385
27386
27387/***/ }),
27388/* 394 */
27389/***/ (function(module, exports, __webpack_require__) {
27390
27391// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of
27392__webpack_require__(195)('WeakMap');
27393
27394
27395/***/ }),
27396/* 395 */
27397/***/ (function(module, exports, __webpack_require__) {
27398
27399// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from
27400__webpack_require__(196)('WeakMap');
27401
27402
27403/***/ }),
27404/* 396 */
27405/***/ (function(module, exports, __webpack_require__) {
27406
27407module.exports = { "default": __webpack_require__(397), __esModule: true };
27408
27409/***/ }),
27410/* 397 */
27411/***/ (function(module, exports, __webpack_require__) {
27412
27413__webpack_require__(398);
27414var $Object = __webpack_require__(1).Object;
27415module.exports = function defineProperties(T, D) {
27416 return $Object.defineProperties(T, D);
27417};
27418
27419
27420/***/ }),
27421/* 398 */
27422/***/ (function(module, exports, __webpack_require__) {
27423
27424var $export = __webpack_require__(4);
27425// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
27426$export($export.S + $export.F * !__webpack_require__(16), 'Object', { defineProperties: __webpack_require__(116) });
27427
27428
27429/***/ }),
27430/* 399 */
27431/***/ (function(module, exports, __webpack_require__) {
27432
27433module.exports = { "default": __webpack_require__(400), __esModule: true };
27434
27435/***/ }),
27436/* 400 */
27437/***/ (function(module, exports, __webpack_require__) {
27438
27439__webpack_require__(401);
27440module.exports = __webpack_require__(1).Object.getOwnPropertyDescriptors;
27441
27442
27443/***/ }),
27444/* 401 */
27445/***/ (function(module, exports, __webpack_require__) {
27446
27447// https://github.com/tc39/proposal-object-getownpropertydescriptors
27448var $export = __webpack_require__(4);
27449var ownKeys = __webpack_require__(402);
27450var toIObject = __webpack_require__(26);
27451var gOPD = __webpack_require__(76);
27452var createProperty = __webpack_require__(192);
27453
27454$export($export.S, 'Object', {
27455 getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
27456 var O = toIObject(object);
27457 var getDesc = gOPD.f;
27458 var keys = ownKeys(O);
27459 var result = {};
27460 var i = 0;
27461 var key, desc;
27462 while (keys.length > i) {
27463 desc = getDesc(O, key = keys[i++]);
27464 if (desc !== undefined) createProperty(result, key, desc);
27465 }
27466 return result;
27467 }
27468});
27469
27470
27471/***/ }),
27472/* 402 */
27473/***/ (function(module, exports, __webpack_require__) {
27474
27475// all object keys, includes non-enumerable and symbols
27476var gOPN = __webpack_require__(110);
27477var gOPS = __webpack_require__(74);
27478var anObject = __webpack_require__(15);
27479var Reflect = __webpack_require__(5).Reflect;
27480module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) {
27481 var keys = gOPN.f(anObject(it));
27482 var getSymbols = gOPS.f;
27483 return getSymbols ? keys.concat(getSymbols(it)) : keys;
27484};
27485
27486
27487/***/ }),
27488/* 403 */
27489/***/ (function(module, exports, __webpack_require__) {
27490
27491__webpack_require__(183);
27492module.exports = __webpack_require__(1).Object.getOwnPropertySymbols;
27493
27494
27495/***/ }),
27496/* 404 */
27497/***/ (function(module, exports, __webpack_require__) {
27498
27499__webpack_require__(405);
27500module.exports = __webpack_require__(1).Object.assign;
27501
27502
27503/***/ }),
27504/* 405 */
27505/***/ (function(module, exports, __webpack_require__) {
27506
27507// 19.1.3.1 Object.assign(target, source)
27508var $export = __webpack_require__(4);
27509
27510$export($export.S + $export.F, 'Object', { assign: __webpack_require__(197) });
27511
27512
27513/***/ }),
27514/* 406 */
27515/***/ (function(module, exports, __webpack_require__) {
27516
27517module.exports = { "default": __webpack_require__(407), __esModule: true };
27518
27519/***/ }),
27520/* 407 */
27521/***/ (function(module, exports, __webpack_require__) {
27522
27523__webpack_require__(408);
27524module.exports = __webpack_require__(1).Object.freeze;
27525
27526
27527/***/ }),
27528/* 408 */
27529/***/ (function(module, exports, __webpack_require__) {
27530
27531// 19.1.2.5 Object.freeze(O)
27532var isObject = __webpack_require__(9);
27533var meta = __webpack_require__(45).onFreeze;
27534
27535__webpack_require__(70)('freeze', function ($freeze) {
27536 return function freeze(it) {
27537 return $freeze && isObject(it) ? $freeze(meta(it)) : it;
27538 };
27539});
27540
27541
27542/***/ }),
27543/* 409 */
27544/***/ (function(module, exports, __webpack_require__) {
27545
27546var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*
27547 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
27548
27549 Licensed under the Apache License, Version 2.0 (the "License");
27550 you may not use this file except in compliance with the License.
27551 You may obtain a copy of the License at
27552
27553 http://www.apache.org/licenses/LICENSE-2.0
27554
27555 Unless required by applicable law or agreed to in writing, software
27556 distributed under the License is distributed on an "AS IS" BASIS,
27557 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
27558 See the License for the specific language governing permissions and
27559 limitations under the License.
27560 */
27561
27562/**
27563 * @license protobuf.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
27564 * Released under the Apache License, Version 2.0
27565 * see: https://github.com/dcodeIO/protobuf.js for details
27566 */
27567(function(global, factory) {
27568
27569 /* AMD */ if (true)
27570 !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(410)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
27571 __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
27572 (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
27573 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
27574 /* CommonJS */ else if (typeof require === "function" && typeof module === "object" && module && module["exports"])
27575 module["exports"] = factory(require("bytebuffer"), true);
27576 /* Global */ else
27577 (global["dcodeIO"] = global["dcodeIO"] || {})["ProtoBuf"] = factory(global["dcodeIO"]["ByteBuffer"]);
27578
27579})(this, function(ByteBuffer, isCommonJS) {
27580 "use strict";
27581
27582 /**
27583 * The ProtoBuf namespace.
27584 * @exports ProtoBuf
27585 * @namespace
27586 * @expose
27587 */
27588 var ProtoBuf = {};
27589
27590 /**
27591 * @type {!function(new: ByteBuffer, ...[*])}
27592 * @expose
27593 */
27594 ProtoBuf.ByteBuffer = ByteBuffer;
27595
27596 /**
27597 * @type {?function(new: Long, ...[*])}
27598 * @expose
27599 */
27600 ProtoBuf.Long = ByteBuffer.Long || null;
27601
27602 /**
27603 * ProtoBuf.js version.
27604 * @type {string}
27605 * @const
27606 * @expose
27607 */
27608 ProtoBuf.VERSION = "5.0.3";
27609
27610 /**
27611 * Wire types.
27612 * @type {Object.<string,number>}
27613 * @const
27614 * @expose
27615 */
27616 ProtoBuf.WIRE_TYPES = {};
27617
27618 /**
27619 * Varint wire type.
27620 * @type {number}
27621 * @expose
27622 */
27623 ProtoBuf.WIRE_TYPES.VARINT = 0;
27624
27625 /**
27626 * Fixed 64 bits wire type.
27627 * @type {number}
27628 * @const
27629 * @expose
27630 */
27631 ProtoBuf.WIRE_TYPES.BITS64 = 1;
27632
27633 /**
27634 * Length delimited wire type.
27635 * @type {number}
27636 * @const
27637 * @expose
27638 */
27639 ProtoBuf.WIRE_TYPES.LDELIM = 2;
27640
27641 /**
27642 * Start group wire type.
27643 * @type {number}
27644 * @const
27645 * @expose
27646 */
27647 ProtoBuf.WIRE_TYPES.STARTGROUP = 3;
27648
27649 /**
27650 * End group wire type.
27651 * @type {number}
27652 * @const
27653 * @expose
27654 */
27655 ProtoBuf.WIRE_TYPES.ENDGROUP = 4;
27656
27657 /**
27658 * Fixed 32 bits wire type.
27659 * @type {number}
27660 * @const
27661 * @expose
27662 */
27663 ProtoBuf.WIRE_TYPES.BITS32 = 5;
27664
27665 /**
27666 * Packable wire types.
27667 * @type {!Array.<number>}
27668 * @const
27669 * @expose
27670 */
27671 ProtoBuf.PACKABLE_WIRE_TYPES = [
27672 ProtoBuf.WIRE_TYPES.VARINT,
27673 ProtoBuf.WIRE_TYPES.BITS64,
27674 ProtoBuf.WIRE_TYPES.BITS32
27675 ];
27676
27677 /**
27678 * Types.
27679 * @dict
27680 * @type {!Object.<string,{name: string, wireType: number, defaultValue: *}>}
27681 * @const
27682 * @expose
27683 */
27684 ProtoBuf.TYPES = {
27685 // According to the protobuf spec.
27686 "int32": {
27687 name: "int32",
27688 wireType: ProtoBuf.WIRE_TYPES.VARINT,
27689 defaultValue: 0
27690 },
27691 "uint32": {
27692 name: "uint32",
27693 wireType: ProtoBuf.WIRE_TYPES.VARINT,
27694 defaultValue: 0
27695 },
27696 "sint32": {
27697 name: "sint32",
27698 wireType: ProtoBuf.WIRE_TYPES.VARINT,
27699 defaultValue: 0
27700 },
27701 "int64": {
27702 name: "int64",
27703 wireType: ProtoBuf.WIRE_TYPES.VARINT,
27704 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
27705 },
27706 "uint64": {
27707 name: "uint64",
27708 wireType: ProtoBuf.WIRE_TYPES.VARINT,
27709 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
27710 },
27711 "sint64": {
27712 name: "sint64",
27713 wireType: ProtoBuf.WIRE_TYPES.VARINT,
27714 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
27715 },
27716 "bool": {
27717 name: "bool",
27718 wireType: ProtoBuf.WIRE_TYPES.VARINT,
27719 defaultValue: false
27720 },
27721 "double": {
27722 name: "double",
27723 wireType: ProtoBuf.WIRE_TYPES.BITS64,
27724 defaultValue: 0
27725 },
27726 "string": {
27727 name: "string",
27728 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
27729 defaultValue: ""
27730 },
27731 "bytes": {
27732 name: "bytes",
27733 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
27734 defaultValue: null // overridden in the code, must be a unique instance
27735 },
27736 "fixed32": {
27737 name: "fixed32",
27738 wireType: ProtoBuf.WIRE_TYPES.BITS32,
27739 defaultValue: 0
27740 },
27741 "sfixed32": {
27742 name: "sfixed32",
27743 wireType: ProtoBuf.WIRE_TYPES.BITS32,
27744 defaultValue: 0
27745 },
27746 "fixed64": {
27747 name: "fixed64",
27748 wireType: ProtoBuf.WIRE_TYPES.BITS64,
27749 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
27750 },
27751 "sfixed64": {
27752 name: "sfixed64",
27753 wireType: ProtoBuf.WIRE_TYPES.BITS64,
27754 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
27755 },
27756 "float": {
27757 name: "float",
27758 wireType: ProtoBuf.WIRE_TYPES.BITS32,
27759 defaultValue: 0
27760 },
27761 "enum": {
27762 name: "enum",
27763 wireType: ProtoBuf.WIRE_TYPES.VARINT,
27764 defaultValue: 0
27765 },
27766 "message": {
27767 name: "message",
27768 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
27769 defaultValue: null
27770 },
27771 "group": {
27772 name: "group",
27773 wireType: ProtoBuf.WIRE_TYPES.STARTGROUP,
27774 defaultValue: null
27775 }
27776 };
27777
27778 /**
27779 * Valid map key types.
27780 * @type {!Array.<!Object.<string,{name: string, wireType: number, defaultValue: *}>>}
27781 * @const
27782 * @expose
27783 */
27784 ProtoBuf.MAP_KEY_TYPES = [
27785 ProtoBuf.TYPES["int32"],
27786 ProtoBuf.TYPES["sint32"],
27787 ProtoBuf.TYPES["sfixed32"],
27788 ProtoBuf.TYPES["uint32"],
27789 ProtoBuf.TYPES["fixed32"],
27790 ProtoBuf.TYPES["int64"],
27791 ProtoBuf.TYPES["sint64"],
27792 ProtoBuf.TYPES["sfixed64"],
27793 ProtoBuf.TYPES["uint64"],
27794 ProtoBuf.TYPES["fixed64"],
27795 ProtoBuf.TYPES["bool"],
27796 ProtoBuf.TYPES["string"],
27797 ProtoBuf.TYPES["bytes"]
27798 ];
27799
27800 /**
27801 * Minimum field id.
27802 * @type {number}
27803 * @const
27804 * @expose
27805 */
27806 ProtoBuf.ID_MIN = 1;
27807
27808 /**
27809 * Maximum field id.
27810 * @type {number}
27811 * @const
27812 * @expose
27813 */
27814 ProtoBuf.ID_MAX = 0x1FFFFFFF;
27815
27816 /**
27817 * If set to `true`, field names will be converted from underscore notation to camel case. Defaults to `false`.
27818 * Must be set prior to parsing.
27819 * @type {boolean}
27820 * @expose
27821 */
27822 ProtoBuf.convertFieldsToCamelCase = false;
27823
27824 /**
27825 * By default, messages are populated with (setX, set_x) accessors for each field. This can be disabled by
27826 * setting this to `false` prior to building messages.
27827 * @type {boolean}
27828 * @expose
27829 */
27830 ProtoBuf.populateAccessors = true;
27831
27832 /**
27833 * By default, messages are populated with default values if a field is not present on the wire. To disable
27834 * this behavior, set this setting to `false`.
27835 * @type {boolean}
27836 * @expose
27837 */
27838 ProtoBuf.populateDefaults = true;
27839
27840 /**
27841 * @alias ProtoBuf.Util
27842 * @expose
27843 */
27844 ProtoBuf.Util = (function() {
27845 "use strict";
27846
27847 /**
27848 * ProtoBuf utilities.
27849 * @exports ProtoBuf.Util
27850 * @namespace
27851 */
27852 var Util = {};
27853
27854 /**
27855 * Flag if running in node or not.
27856 * @type {boolean}
27857 * @const
27858 * @expose
27859 */
27860 Util.IS_NODE = !!(
27861 typeof process === 'object' && process+'' === '[object process]' && !process['browser']
27862 );
27863
27864 /**
27865 * Constructs a XMLHttpRequest object.
27866 * @return {XMLHttpRequest}
27867 * @throws {Error} If XMLHttpRequest is not supported
27868 * @expose
27869 */
27870 Util.XHR = function() {
27871 // No dependencies please, ref: http://www.quirksmode.org/js/xmlhttp.html
27872 var XMLHttpFactories = [
27873 function () {return new XMLHttpRequest()},
27874 function () {return new ActiveXObject("Msxml2.XMLHTTP")},
27875 function () {return new ActiveXObject("Msxml3.XMLHTTP")},
27876 function () {return new ActiveXObject("Microsoft.XMLHTTP")}
27877 ];
27878 /** @type {?XMLHttpRequest} */
27879 var xhr = null;
27880 for (var i=0;i<XMLHttpFactories.length;i++) {
27881 try { xhr = XMLHttpFactories[i](); }
27882 catch (e) { continue; }
27883 break;
27884 }
27885 if (!xhr)
27886 throw Error("XMLHttpRequest is not supported");
27887 return xhr;
27888 };
27889
27890 /**
27891 * Fetches a resource.
27892 * @param {string} path Resource path
27893 * @param {function(?string)=} callback Callback receiving the resource's contents. If omitted the resource will
27894 * be fetched synchronously. If the request failed, contents will be null.
27895 * @return {?string|undefined} Resource contents if callback is omitted (null if the request failed), else undefined.
27896 * @expose
27897 */
27898 Util.fetch = function(path, callback) {
27899 if (callback && typeof callback != 'function')
27900 callback = null;
27901 if (Util.IS_NODE) {
27902 var fs = __webpack_require__(412);
27903 if (callback) {
27904 fs.readFile(path, function(err, data) {
27905 if (err)
27906 callback(null);
27907 else
27908 callback(""+data);
27909 });
27910 } else
27911 try {
27912 return fs.readFileSync(path);
27913 } catch (e) {
27914 return null;
27915 }
27916 } else {
27917 var xhr = Util.XHR();
27918 xhr.open('GET', path, callback ? true : false);
27919 // xhr.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
27920 xhr.setRequestHeader('Accept', 'text/plain');
27921 if (typeof xhr.overrideMimeType === 'function') xhr.overrideMimeType('text/plain');
27922 if (callback) {
27923 xhr.onreadystatechange = function() {
27924 if (xhr.readyState != 4) return;
27925 if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
27926 callback(xhr.responseText);
27927 else
27928 callback(null);
27929 };
27930 if (xhr.readyState == 4)
27931 return;
27932 xhr.send(null);
27933 } else {
27934 xhr.send(null);
27935 if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
27936 return xhr.responseText;
27937 return null;
27938 }
27939 }
27940 };
27941
27942 /**
27943 * Converts a string to camel case.
27944 * @param {string} str
27945 * @returns {string}
27946 * @expose
27947 */
27948 Util.toCamelCase = function(str) {
27949 return str.replace(/_([a-zA-Z])/g, function ($0, $1) {
27950 return $1.toUpperCase();
27951 });
27952 };
27953
27954 return Util;
27955 })();
27956
27957 /**
27958 * Language expressions.
27959 * @type {!Object.<string,!RegExp>}
27960 * @expose
27961 */
27962 ProtoBuf.Lang = {
27963
27964 // Characters always ending a statement
27965 DELIM: /[\s\{\}=;:\[\],'"\(\)<>]/g,
27966
27967 // Field rules
27968 RULE: /^(?:required|optional|repeated|map)$/,
27969
27970 // Field types
27971 TYPE: /^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,
27972
27973 // Names
27974 NAME: /^[a-zA-Z_][a-zA-Z_0-9]*$/,
27975
27976 // Type definitions
27977 TYPEDEF: /^[a-zA-Z][a-zA-Z_0-9]*$/,
27978
27979 // Type references
27980 TYPEREF: /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,
27981
27982 // Fully qualified type references
27983 FQTYPEREF: /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/,
27984
27985 // All numbers
27986 NUMBER: /^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,
27987
27988 // Decimal numbers
27989 NUMBER_DEC: /^(?:[1-9][0-9]*|0)$/,
27990
27991 // Hexadecimal numbers
27992 NUMBER_HEX: /^0[xX][0-9a-fA-F]+$/,
27993
27994 // Octal numbers
27995 NUMBER_OCT: /^0[0-7]+$/,
27996
27997 // Floating point numbers
27998 NUMBER_FLT: /^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,
27999
28000 // Booleans
28001 BOOL: /^(?:true|false)$/i,
28002
28003 // Id numbers
28004 ID: /^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
28005
28006 // Negative id numbers (enum values)
28007 NEGID: /^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
28008
28009 // Whitespaces
28010 WHITESPACE: /\s/,
28011
28012 // All strings
28013 STRING: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,
28014
28015 // Double quoted strings
28016 STRING_DQ: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,
28017
28018 // Single quoted strings
28019 STRING_SQ: /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g
28020 };
28021
28022
28023 /**
28024 * @alias ProtoBuf.Reflect
28025 * @expose
28026 */
28027 ProtoBuf.Reflect = (function(ProtoBuf) {
28028 "use strict";
28029
28030 /**
28031 * Reflection types.
28032 * @exports ProtoBuf.Reflect
28033 * @namespace
28034 */
28035 var Reflect = {};
28036
28037 /**
28038 * Constructs a Reflect base class.
28039 * @exports ProtoBuf.Reflect.T
28040 * @constructor
28041 * @abstract
28042 * @param {!ProtoBuf.Builder} builder Builder reference
28043 * @param {?ProtoBuf.Reflect.T} parent Parent object
28044 * @param {string} name Object name
28045 */
28046 var T = function(builder, parent, name) {
28047
28048 /**
28049 * Builder reference.
28050 * @type {!ProtoBuf.Builder}
28051 * @expose
28052 */
28053 this.builder = builder;
28054
28055 /**
28056 * Parent object.
28057 * @type {?ProtoBuf.Reflect.T}
28058 * @expose
28059 */
28060 this.parent = parent;
28061
28062 /**
28063 * Object name in namespace.
28064 * @type {string}
28065 * @expose
28066 */
28067 this.name = name;
28068
28069 /**
28070 * Fully qualified class name
28071 * @type {string}
28072 * @expose
28073 */
28074 this.className;
28075 };
28076
28077 /**
28078 * @alias ProtoBuf.Reflect.T.prototype
28079 * @inner
28080 */
28081 var TPrototype = T.prototype;
28082
28083 /**
28084 * Returns the fully qualified name of this object.
28085 * @returns {string} Fully qualified name as of ".PATH.TO.THIS"
28086 * @expose
28087 */
28088 TPrototype.fqn = function() {
28089 var name = this.name,
28090 ptr = this;
28091 do {
28092 ptr = ptr.parent;
28093 if (ptr == null)
28094 break;
28095 name = ptr.name+"."+name;
28096 } while (true);
28097 return name;
28098 };
28099
28100 /**
28101 * Returns a string representation of this Reflect object (its fully qualified name).
28102 * @param {boolean=} includeClass Set to true to include the class name. Defaults to false.
28103 * @return String representation
28104 * @expose
28105 */
28106 TPrototype.toString = function(includeClass) {
28107 return (includeClass ? this.className + " " : "") + this.fqn();
28108 };
28109
28110 /**
28111 * Builds this type.
28112 * @throws {Error} If this type cannot be built directly
28113 * @expose
28114 */
28115 TPrototype.build = function() {
28116 throw Error(this.toString(true)+" cannot be built directly");
28117 };
28118
28119 /**
28120 * @alias ProtoBuf.Reflect.T
28121 * @expose
28122 */
28123 Reflect.T = T;
28124
28125 /**
28126 * Constructs a new Namespace.
28127 * @exports ProtoBuf.Reflect.Namespace
28128 * @param {!ProtoBuf.Builder} builder Builder reference
28129 * @param {?ProtoBuf.Reflect.Namespace} parent Namespace parent
28130 * @param {string} name Namespace name
28131 * @param {Object.<string,*>=} options Namespace options
28132 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
28133 * @constructor
28134 * @extends ProtoBuf.Reflect.T
28135 */
28136 var Namespace = function(builder, parent, name, options, syntax) {
28137 T.call(this, builder, parent, name);
28138
28139 /**
28140 * @override
28141 */
28142 this.className = "Namespace";
28143
28144 /**
28145 * Children inside the namespace.
28146 * @type {!Array.<ProtoBuf.Reflect.T>}
28147 */
28148 this.children = [];
28149
28150 /**
28151 * Options.
28152 * @type {!Object.<string, *>}
28153 */
28154 this.options = options || {};
28155
28156 /**
28157 * Syntax level (e.g., proto2 or proto3).
28158 * @type {!string}
28159 */
28160 this.syntax = syntax || "proto2";
28161 };
28162
28163 /**
28164 * @alias ProtoBuf.Reflect.Namespace.prototype
28165 * @inner
28166 */
28167 var NamespacePrototype = Namespace.prototype = Object.create(T.prototype);
28168
28169 /**
28170 * Returns an array of the namespace's children.
28171 * @param {ProtoBuf.Reflect.T=} type Filter type (returns instances of this type only). Defaults to null (all children).
28172 * @return {Array.<ProtoBuf.Reflect.T>}
28173 * @expose
28174 */
28175 NamespacePrototype.getChildren = function(type) {
28176 type = type || null;
28177 if (type == null)
28178 return this.children.slice();
28179 var children = [];
28180 for (var i=0, k=this.children.length; i<k; ++i)
28181 if (this.children[i] instanceof type)
28182 children.push(this.children[i]);
28183 return children;
28184 };
28185
28186 /**
28187 * Adds a child to the namespace.
28188 * @param {ProtoBuf.Reflect.T} child Child
28189 * @throws {Error} If the child cannot be added (duplicate)
28190 * @expose
28191 */
28192 NamespacePrototype.addChild = function(child) {
28193 var other;
28194 if (other = this.getChild(child.name)) {
28195 // Try to revert camelcase transformation on collision
28196 if (other instanceof Message.Field && other.name !== other.originalName && this.getChild(other.originalName) === null)
28197 other.name = other.originalName; // Revert previous first (effectively keeps both originals)
28198 else if (child instanceof Message.Field && child.name !== child.originalName && this.getChild(child.originalName) === null)
28199 child.name = child.originalName;
28200 else
28201 throw Error("Duplicate name in namespace "+this.toString(true)+": "+child.name);
28202 }
28203 this.children.push(child);
28204 };
28205
28206 /**
28207 * Gets a child by its name or id.
28208 * @param {string|number} nameOrId Child name or id
28209 * @return {?ProtoBuf.Reflect.T} The child or null if not found
28210 * @expose
28211 */
28212 NamespacePrototype.getChild = function(nameOrId) {
28213 var key = typeof nameOrId === 'number' ? 'id' : 'name';
28214 for (var i=0, k=this.children.length; i<k; ++i)
28215 if (this.children[i][key] === nameOrId)
28216 return this.children[i];
28217 return null;
28218 };
28219
28220 /**
28221 * Resolves a reflect object inside of this namespace.
28222 * @param {string|!Array.<string>} qn Qualified name to resolve
28223 * @param {boolean=} excludeNonNamespace Excludes non-namespace types, defaults to `false`
28224 * @return {?ProtoBuf.Reflect.Namespace} The resolved type or null if not found
28225 * @expose
28226 */
28227 NamespacePrototype.resolve = function(qn, excludeNonNamespace) {
28228 var part = typeof qn === 'string' ? qn.split(".") : qn,
28229 ptr = this,
28230 i = 0;
28231 if (part[i] === "") { // Fully qualified name, e.g. ".My.Message'
28232 while (ptr.parent !== null)
28233 ptr = ptr.parent;
28234 i++;
28235 }
28236 var child;
28237 do {
28238 do {
28239 if (!(ptr instanceof Reflect.Namespace)) {
28240 ptr = null;
28241 break;
28242 }
28243 child = ptr.getChild(part[i]);
28244 if (!child || !(child instanceof Reflect.T) || (excludeNonNamespace && !(child instanceof Reflect.Namespace))) {
28245 ptr = null;
28246 break;
28247 }
28248 ptr = child; i++;
28249 } while (i < part.length);
28250 if (ptr != null)
28251 break; // Found
28252 // Else search the parent
28253 if (this.parent !== null)
28254 return this.parent.resolve(qn, excludeNonNamespace);
28255 } while (ptr != null);
28256 return ptr;
28257 };
28258
28259 /**
28260 * Determines the shortest qualified name of the specified type, if any, relative to this namespace.
28261 * @param {!ProtoBuf.Reflect.T} t Reflection type
28262 * @returns {string} The shortest qualified name or, if there is none, the fqn
28263 * @expose
28264 */
28265 NamespacePrototype.qn = function(t) {
28266 var part = [], ptr = t;
28267 do {
28268 part.unshift(ptr.name);
28269 ptr = ptr.parent;
28270 } while (ptr !== null);
28271 for (var len=1; len <= part.length; len++) {
28272 var qn = part.slice(part.length-len);
28273 if (t === this.resolve(qn, t instanceof Reflect.Namespace))
28274 return qn.join(".");
28275 }
28276 return t.fqn();
28277 };
28278
28279 /**
28280 * Builds the namespace and returns the runtime counterpart.
28281 * @return {Object.<string,Function|Object>} Runtime namespace
28282 * @expose
28283 */
28284 NamespacePrototype.build = function() {
28285 /** @dict */
28286 var ns = {};
28287 var children = this.children;
28288 for (var i=0, k=children.length, child; i<k; ++i) {
28289 child = children[i];
28290 if (child instanceof Namespace)
28291 ns[child.name] = child.build();
28292 }
28293 if (Object.defineProperty)
28294 Object.defineProperty(ns, "$options", { "value": this.buildOpt() });
28295 return ns;
28296 };
28297
28298 /**
28299 * Builds the namespace's '$options' property.
28300 * @return {Object.<string,*>}
28301 */
28302 NamespacePrototype.buildOpt = function() {
28303 var opt = {},
28304 keys = Object.keys(this.options);
28305 for (var i=0, k=keys.length; i<k; ++i) {
28306 var key = keys[i],
28307 val = this.options[keys[i]];
28308 // TODO: Options are not resolved, yet.
28309 // if (val instanceof Namespace) {
28310 // opt[key] = val.build();
28311 // } else {
28312 opt[key] = val;
28313 // }
28314 }
28315 return opt;
28316 };
28317
28318 /**
28319 * Gets the value assigned to the option with the specified name.
28320 * @param {string=} name Returns the option value if specified, otherwise all options are returned.
28321 * @return {*|Object.<string,*>}null} Option value or NULL if there is no such option
28322 */
28323 NamespacePrototype.getOption = function(name) {
28324 if (typeof name === 'undefined')
28325 return this.options;
28326 return typeof this.options[name] !== 'undefined' ? this.options[name] : null;
28327 };
28328
28329 /**
28330 * @alias ProtoBuf.Reflect.Namespace
28331 * @expose
28332 */
28333 Reflect.Namespace = Namespace;
28334
28335 /**
28336 * Constructs a new Element implementation that checks and converts values for a
28337 * particular field type, as appropriate.
28338 *
28339 * An Element represents a single value: either the value of a singular field,
28340 * or a value contained in one entry of a repeated field or map field. This
28341 * class does not implement these higher-level concepts; it only encapsulates
28342 * the low-level typechecking and conversion.
28343 *
28344 * @exports ProtoBuf.Reflect.Element
28345 * @param {{name: string, wireType: number}} type Resolved data type
28346 * @param {ProtoBuf.Reflect.T|null} resolvedType Resolved type, if relevant
28347 * (e.g. submessage field).
28348 * @param {boolean} isMapKey Is this element a Map key? The value will be
28349 * converted to string form if so.
28350 * @param {string} syntax Syntax level of defining message type, e.g.,
28351 * proto2 or proto3.
28352 * @param {string} name Name of the field containing this element (for error
28353 * messages)
28354 * @constructor
28355 */
28356 var Element = function(type, resolvedType, isMapKey, syntax, name) {
28357
28358 /**
28359 * Element type, as a string (e.g., int32).
28360 * @type {{name: string, wireType: number}}
28361 */
28362 this.type = type;
28363
28364 /**
28365 * Element type reference to submessage or enum definition, if needed.
28366 * @type {ProtoBuf.Reflect.T|null}
28367 */
28368 this.resolvedType = resolvedType;
28369
28370 /**
28371 * Element is a map key.
28372 * @type {boolean}
28373 */
28374 this.isMapKey = isMapKey;
28375
28376 /**
28377 * Syntax level of defining message type, e.g., proto2 or proto3.
28378 * @type {string}
28379 */
28380 this.syntax = syntax;
28381
28382 /**
28383 * Name of the field containing this element (for error messages)
28384 * @type {string}
28385 */
28386 this.name = name;
28387
28388 if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0)
28389 throw Error("Invalid map key type: " + type.name);
28390 };
28391
28392 var ElementPrototype = Element.prototype;
28393
28394 /**
28395 * Obtains a (new) default value for the specified type.
28396 * @param type {string|{name: string, wireType: number}} Field type
28397 * @returns {*} Default value
28398 * @inner
28399 */
28400 function mkDefault(type) {
28401 if (typeof type === 'string')
28402 type = ProtoBuf.TYPES[type];
28403 if (typeof type.defaultValue === 'undefined')
28404 throw Error("default value for type "+type.name+" is not supported");
28405 if (type == ProtoBuf.TYPES["bytes"])
28406 return new ByteBuffer(0);
28407 return type.defaultValue;
28408 }
28409
28410 /**
28411 * Returns the default value for this field in proto3.
28412 * @function
28413 * @param type {string|{name: string, wireType: number}} the field type
28414 * @returns {*} Default value
28415 */
28416 Element.defaultFieldValue = mkDefault;
28417
28418 /**
28419 * Makes a Long from a value.
28420 * @param {{low: number, high: number, unsigned: boolean}|string|number} value Value
28421 * @param {boolean=} unsigned Whether unsigned or not, defaults to reuse it from Long-like objects or to signed for
28422 * strings and numbers
28423 * @returns {!Long}
28424 * @throws {Error} If the value cannot be converted to a Long
28425 * @inner
28426 */
28427 function mkLong(value, unsigned) {
28428 if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean'
28429 && value.low === value.low && value.high === value.high)
28430 return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned);
28431 if (typeof value === 'string')
28432 return ProtoBuf.Long.fromString(value, unsigned || false, 10);
28433 if (typeof value === 'number')
28434 return ProtoBuf.Long.fromNumber(value, unsigned || false);
28435 throw Error("not convertible to Long");
28436 }
28437
28438 ElementPrototype.toString = function() {
28439 return (this.name || '') + (this.isMapKey ? 'map' : 'value') + ' element';
28440 }
28441
28442 /**
28443 * Checks if the given value can be set for an element of this type (singular
28444 * field or one element of a repeated field or map).
28445 * @param {*} value Value to check
28446 * @return {*} Verified, maybe adjusted, value
28447 * @throws {Error} If the value cannot be verified for this element slot
28448 * @expose
28449 */
28450 ElementPrototype.verifyValue = function(value) {
28451 var self = this;
28452 function fail(val, msg) {
28453 throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
28454 }
28455 switch (this.type) {
28456 // Signed 32bit
28457 case ProtoBuf.TYPES["int32"]:
28458 case ProtoBuf.TYPES["sint32"]:
28459 case ProtoBuf.TYPES["sfixed32"]:
28460 // Account for !NaN: value === value
28461 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
28462 fail(typeof value, "not an integer");
28463 return value > 4294967295 ? value | 0 : value;
28464
28465 // Unsigned 32bit
28466 case ProtoBuf.TYPES["uint32"]:
28467 case ProtoBuf.TYPES["fixed32"]:
28468 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
28469 fail(typeof value, "not an integer");
28470 return value < 0 ? value >>> 0 : value;
28471
28472 // Signed 64bit
28473 case ProtoBuf.TYPES["int64"]:
28474 case ProtoBuf.TYPES["sint64"]:
28475 case ProtoBuf.TYPES["sfixed64"]: {
28476 if (ProtoBuf.Long)
28477 try {
28478 return mkLong(value, false);
28479 } catch (e) {
28480 fail(typeof value, e.message);
28481 }
28482 else
28483 fail(typeof value, "requires Long.js");
28484 }
28485
28486 // Unsigned 64bit
28487 case ProtoBuf.TYPES["uint64"]:
28488 case ProtoBuf.TYPES["fixed64"]: {
28489 if (ProtoBuf.Long)
28490 try {
28491 return mkLong(value, true);
28492 } catch (e) {
28493 fail(typeof value, e.message);
28494 }
28495 else
28496 fail(typeof value, "requires Long.js");
28497 }
28498
28499 // Bool
28500 case ProtoBuf.TYPES["bool"]:
28501 if (typeof value !== 'boolean')
28502 fail(typeof value, "not a boolean");
28503 return value;
28504
28505 // Float
28506 case ProtoBuf.TYPES["float"]:
28507 case ProtoBuf.TYPES["double"]:
28508 if (typeof value !== 'number')
28509 fail(typeof value, "not a number");
28510 return value;
28511
28512 // Length-delimited string
28513 case ProtoBuf.TYPES["string"]:
28514 if (typeof value !== 'string' && !(value && value instanceof String))
28515 fail(typeof value, "not a string");
28516 return ""+value; // Convert String object to string
28517
28518 // Length-delimited bytes
28519 case ProtoBuf.TYPES["bytes"]:
28520 if (ByteBuffer.isByteBuffer(value))
28521 return value;
28522 return ByteBuffer.wrap(value, "base64");
28523
28524 // Constant enum value
28525 case ProtoBuf.TYPES["enum"]: {
28526 var values = this.resolvedType.getChildren(ProtoBuf.Reflect.Enum.Value);
28527 for (i=0; i<values.length; i++)
28528 if (values[i].name == value)
28529 return values[i].id;
28530 else if (values[i].id == value)
28531 return values[i].id;
28532
28533 if (this.syntax === 'proto3') {
28534 // proto3: just make sure it's an integer.
28535 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
28536 fail(typeof value, "not an integer");
28537 if (value > 4294967295 || value < 0)
28538 fail(typeof value, "not in range for uint32")
28539 return value;
28540 } else {
28541 // proto2 requires enum values to be valid.
28542 fail(value, "not a valid enum value");
28543 }
28544 }
28545 // Embedded message
28546 case ProtoBuf.TYPES["group"]:
28547 case ProtoBuf.TYPES["message"]: {
28548 if (!value || typeof value !== 'object')
28549 fail(typeof value, "object expected");
28550 if (value instanceof this.resolvedType.clazz)
28551 return value;
28552 if (value instanceof ProtoBuf.Builder.Message) {
28553 // Mismatched type: Convert to object (see: https://github.com/dcodeIO/ProtoBuf.js/issues/180)
28554 var obj = {};
28555 for (var i in value)
28556 if (value.hasOwnProperty(i))
28557 obj[i] = value[i];
28558 value = obj;
28559 }
28560 // Else let's try to construct one from a key-value object
28561 return new (this.resolvedType.clazz)(value); // May throw for a hundred of reasons
28562 }
28563 }
28564
28565 // We should never end here
28566 throw Error("[INTERNAL] Illegal value for "+this.toString(true)+": "+value+" (undefined type "+this.type+")");
28567 };
28568
28569 /**
28570 * Calculates the byte length of an element on the wire.
28571 * @param {number} id Field number
28572 * @param {*} value Field value
28573 * @returns {number} Byte length
28574 * @throws {Error} If the value cannot be calculated
28575 * @expose
28576 */
28577 ElementPrototype.calculateLength = function(id, value) {
28578 if (value === null) return 0; // Nothing to encode
28579 // Tag has already been written
28580 var n;
28581 switch (this.type) {
28582 case ProtoBuf.TYPES["int32"]:
28583 return value < 0 ? ByteBuffer.calculateVarint64(value) : ByteBuffer.calculateVarint32(value);
28584 case ProtoBuf.TYPES["uint32"]:
28585 return ByteBuffer.calculateVarint32(value);
28586 case ProtoBuf.TYPES["sint32"]:
28587 return ByteBuffer.calculateVarint32(ByteBuffer.zigZagEncode32(value));
28588 case ProtoBuf.TYPES["fixed32"]:
28589 case ProtoBuf.TYPES["sfixed32"]:
28590 case ProtoBuf.TYPES["float"]:
28591 return 4;
28592 case ProtoBuf.TYPES["int64"]:
28593 case ProtoBuf.TYPES["uint64"]:
28594 return ByteBuffer.calculateVarint64(value);
28595 case ProtoBuf.TYPES["sint64"]:
28596 return ByteBuffer.calculateVarint64(ByteBuffer.zigZagEncode64(value));
28597 case ProtoBuf.TYPES["fixed64"]:
28598 case ProtoBuf.TYPES["sfixed64"]:
28599 return 8;
28600 case ProtoBuf.TYPES["bool"]:
28601 return 1;
28602 case ProtoBuf.TYPES["enum"]:
28603 return ByteBuffer.calculateVarint32(value);
28604 case ProtoBuf.TYPES["double"]:
28605 return 8;
28606 case ProtoBuf.TYPES["string"]:
28607 n = ByteBuffer.calculateUTF8Bytes(value);
28608 return ByteBuffer.calculateVarint32(n) + n;
28609 case ProtoBuf.TYPES["bytes"]:
28610 if (value.remaining() < 0)
28611 throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
28612 return ByteBuffer.calculateVarint32(value.remaining()) + value.remaining();
28613 case ProtoBuf.TYPES["message"]:
28614 n = this.resolvedType.calculate(value);
28615 return ByteBuffer.calculateVarint32(n) + n;
28616 case ProtoBuf.TYPES["group"]:
28617 n = this.resolvedType.calculate(value);
28618 return n + ByteBuffer.calculateVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
28619 }
28620 // We should never end here
28621 throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
28622 };
28623
28624 /**
28625 * Encodes a value to the specified buffer. Does not encode the key.
28626 * @param {number} id Field number
28627 * @param {*} value Field value
28628 * @param {ByteBuffer} buffer ByteBuffer to encode to
28629 * @return {ByteBuffer} The ByteBuffer for chaining
28630 * @throws {Error} If the value cannot be encoded
28631 * @expose
28632 */
28633 ElementPrototype.encodeValue = function(id, value, buffer) {
28634 if (value === null) return buffer; // Nothing to encode
28635 // Tag has already been written
28636
28637 switch (this.type) {
28638 // 32bit signed varint
28639 case ProtoBuf.TYPES["int32"]:
28640 // "If you use int32 or int64 as the type for a negative number, the resulting varint is always ten bytes
28641 // long – it is, effectively, treated like a very large unsigned integer." (see #122)
28642 if (value < 0)
28643 buffer.writeVarint64(value);
28644 else
28645 buffer.writeVarint32(value);
28646 break;
28647
28648 // 32bit unsigned varint
28649 case ProtoBuf.TYPES["uint32"]:
28650 buffer.writeVarint32(value);
28651 break;
28652
28653 // 32bit varint zig-zag
28654 case ProtoBuf.TYPES["sint32"]:
28655 buffer.writeVarint32ZigZag(value);
28656 break;
28657
28658 // Fixed unsigned 32bit
28659 case ProtoBuf.TYPES["fixed32"]:
28660 buffer.writeUint32(value);
28661 break;
28662
28663 // Fixed signed 32bit
28664 case ProtoBuf.TYPES["sfixed32"]:
28665 buffer.writeInt32(value);
28666 break;
28667
28668 // 64bit varint as-is
28669 case ProtoBuf.TYPES["int64"]:
28670 case ProtoBuf.TYPES["uint64"]:
28671 buffer.writeVarint64(value); // throws
28672 break;
28673
28674 // 64bit varint zig-zag
28675 case ProtoBuf.TYPES["sint64"]:
28676 buffer.writeVarint64ZigZag(value); // throws
28677 break;
28678
28679 // Fixed unsigned 64bit
28680 case ProtoBuf.TYPES["fixed64"]:
28681 buffer.writeUint64(value); // throws
28682 break;
28683
28684 // Fixed signed 64bit
28685 case ProtoBuf.TYPES["sfixed64"]:
28686 buffer.writeInt64(value); // throws
28687 break;
28688
28689 // Bool
28690 case ProtoBuf.TYPES["bool"]:
28691 if (typeof value === 'string')
28692 buffer.writeVarint32(value.toLowerCase() === 'false' ? 0 : !!value);
28693 else
28694 buffer.writeVarint32(value ? 1 : 0);
28695 break;
28696
28697 // Constant enum value
28698 case ProtoBuf.TYPES["enum"]:
28699 buffer.writeVarint32(value);
28700 break;
28701
28702 // 32bit float
28703 case ProtoBuf.TYPES["float"]:
28704 buffer.writeFloat32(value);
28705 break;
28706
28707 // 64bit float
28708 case ProtoBuf.TYPES["double"]:
28709 buffer.writeFloat64(value);
28710 break;
28711
28712 // Length-delimited string
28713 case ProtoBuf.TYPES["string"]:
28714 buffer.writeVString(value);
28715 break;
28716
28717 // Length-delimited bytes
28718 case ProtoBuf.TYPES["bytes"]:
28719 if (value.remaining() < 0)
28720 throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
28721 var prevOffset = value.offset;
28722 buffer.writeVarint32(value.remaining());
28723 buffer.append(value);
28724 value.offset = prevOffset;
28725 break;
28726
28727 // Embedded message
28728 case ProtoBuf.TYPES["message"]:
28729 var bb = new ByteBuffer().LE();
28730 this.resolvedType.encode(value, bb);
28731 buffer.writeVarint32(bb.offset);
28732 buffer.append(bb.flip());
28733 break;
28734
28735 // Legacy group
28736 case ProtoBuf.TYPES["group"]:
28737 this.resolvedType.encode(value, buffer);
28738 buffer.writeVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
28739 break;
28740
28741 default:
28742 // We should never end here
28743 throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
28744 }
28745 return buffer;
28746 };
28747
28748 /**
28749 * Decode one element value from the specified buffer.
28750 * @param {ByteBuffer} buffer ByteBuffer to decode from
28751 * @param {number} wireType The field wire type
28752 * @param {number} id The field number
28753 * @return {*} Decoded value
28754 * @throws {Error} If the field cannot be decoded
28755 * @expose
28756 */
28757 ElementPrototype.decode = function(buffer, wireType, id) {
28758 if (wireType != this.type.wireType)
28759 throw Error("Unexpected wire type for element");
28760
28761 var value, nBytes;
28762 switch (this.type) {
28763 // 32bit signed varint
28764 case ProtoBuf.TYPES["int32"]:
28765 return buffer.readVarint32() | 0;
28766
28767 // 32bit unsigned varint
28768 case ProtoBuf.TYPES["uint32"]:
28769 return buffer.readVarint32() >>> 0;
28770
28771 // 32bit signed varint zig-zag
28772 case ProtoBuf.TYPES["sint32"]:
28773 return buffer.readVarint32ZigZag() | 0;
28774
28775 // Fixed 32bit unsigned
28776 case ProtoBuf.TYPES["fixed32"]:
28777 return buffer.readUint32() >>> 0;
28778
28779 case ProtoBuf.TYPES["sfixed32"]:
28780 return buffer.readInt32() | 0;
28781
28782 // 64bit signed varint
28783 case ProtoBuf.TYPES["int64"]:
28784 return buffer.readVarint64();
28785
28786 // 64bit unsigned varint
28787 case ProtoBuf.TYPES["uint64"]:
28788 return buffer.readVarint64().toUnsigned();
28789
28790 // 64bit signed varint zig-zag
28791 case ProtoBuf.TYPES["sint64"]:
28792 return buffer.readVarint64ZigZag();
28793
28794 // Fixed 64bit unsigned
28795 case ProtoBuf.TYPES["fixed64"]:
28796 return buffer.readUint64();
28797
28798 // Fixed 64bit signed
28799 case ProtoBuf.TYPES["sfixed64"]:
28800 return buffer.readInt64();
28801
28802 // Bool varint
28803 case ProtoBuf.TYPES["bool"]:
28804 return !!buffer.readVarint32();
28805
28806 // Constant enum value (varint)
28807 case ProtoBuf.TYPES["enum"]:
28808 // The following Builder.Message#set will already throw
28809 return buffer.readVarint32();
28810
28811 // 32bit float
28812 case ProtoBuf.TYPES["float"]:
28813 return buffer.readFloat();
28814
28815 // 64bit float
28816 case ProtoBuf.TYPES["double"]:
28817 return buffer.readDouble();
28818
28819 // Length-delimited string
28820 case ProtoBuf.TYPES["string"]:
28821 return buffer.readVString();
28822
28823 // Length-delimited bytes
28824 case ProtoBuf.TYPES["bytes"]: {
28825 nBytes = buffer.readVarint32();
28826 if (buffer.remaining() < nBytes)
28827 throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
28828 value = buffer.clone(); // Offset already set
28829 value.limit = value.offset+nBytes;
28830 buffer.offset += nBytes;
28831 return value;
28832 }
28833
28834 // Length-delimited embedded message
28835 case ProtoBuf.TYPES["message"]: {
28836 nBytes = buffer.readVarint32();
28837 return this.resolvedType.decode(buffer, nBytes);
28838 }
28839
28840 // Legacy group
28841 case ProtoBuf.TYPES["group"]:
28842 return this.resolvedType.decode(buffer, -1, id);
28843 }
28844
28845 // We should never end here
28846 throw Error("[INTERNAL] Illegal decode type");
28847 };
28848
28849 /**
28850 * Converts a value from a string to the canonical element type.
28851 *
28852 * Legal only when isMapKey is true.
28853 *
28854 * @param {string} str The string value
28855 * @returns {*} The value
28856 */
28857 ElementPrototype.valueFromString = function(str) {
28858 if (!this.isMapKey) {
28859 throw Error("valueFromString() called on non-map-key element");
28860 }
28861
28862 switch (this.type) {
28863 case ProtoBuf.TYPES["int32"]:
28864 case ProtoBuf.TYPES["sint32"]:
28865 case ProtoBuf.TYPES["sfixed32"]:
28866 case ProtoBuf.TYPES["uint32"]:
28867 case ProtoBuf.TYPES["fixed32"]:
28868 return this.verifyValue(parseInt(str));
28869
28870 case ProtoBuf.TYPES["int64"]:
28871 case ProtoBuf.TYPES["sint64"]:
28872 case ProtoBuf.TYPES["sfixed64"]:
28873 case ProtoBuf.TYPES["uint64"]:
28874 case ProtoBuf.TYPES["fixed64"]:
28875 // Long-based fields support conversions from string already.
28876 return this.verifyValue(str);
28877
28878 case ProtoBuf.TYPES["bool"]:
28879 return str === "true";
28880
28881 case ProtoBuf.TYPES["string"]:
28882 return this.verifyValue(str);
28883
28884 case ProtoBuf.TYPES["bytes"]:
28885 return ByteBuffer.fromBinary(str);
28886 }
28887 };
28888
28889 /**
28890 * Converts a value from the canonical element type to a string.
28891 *
28892 * It should be the case that `valueFromString(valueToString(val))` returns
28893 * a value equivalent to `verifyValue(val)` for every legal value of `val`
28894 * according to this element type.
28895 *
28896 * This may be used when the element must be stored or used as a string,
28897 * e.g., as a map key on an Object.
28898 *
28899 * Legal only when isMapKey is true.
28900 *
28901 * @param {*} val The value
28902 * @returns {string} The string form of the value.
28903 */
28904 ElementPrototype.valueToString = function(value) {
28905 if (!this.isMapKey) {
28906 throw Error("valueToString() called on non-map-key element");
28907 }
28908
28909 if (this.type === ProtoBuf.TYPES["bytes"]) {
28910 return value.toString("binary");
28911 } else {
28912 return value.toString();
28913 }
28914 };
28915
28916 /**
28917 * @alias ProtoBuf.Reflect.Element
28918 * @expose
28919 */
28920 Reflect.Element = Element;
28921
28922 /**
28923 * Constructs a new Message.
28924 * @exports ProtoBuf.Reflect.Message
28925 * @param {!ProtoBuf.Builder} builder Builder reference
28926 * @param {!ProtoBuf.Reflect.Namespace} parent Parent message or namespace
28927 * @param {string} name Message name
28928 * @param {Object.<string,*>=} options Message options
28929 * @param {boolean=} isGroup `true` if this is a legacy group
28930 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
28931 * @constructor
28932 * @extends ProtoBuf.Reflect.Namespace
28933 */
28934 var Message = function(builder, parent, name, options, isGroup, syntax) {
28935 Namespace.call(this, builder, parent, name, options, syntax);
28936
28937 /**
28938 * @override
28939 */
28940 this.className = "Message";
28941
28942 /**
28943 * Extensions range.
28944 * @type {!Array.<number>|undefined}
28945 * @expose
28946 */
28947 this.extensions = undefined;
28948
28949 /**
28950 * Runtime message class.
28951 * @type {?function(new:ProtoBuf.Builder.Message)}
28952 * @expose
28953 */
28954 this.clazz = null;
28955
28956 /**
28957 * Whether this is a legacy group or not.
28958 * @type {boolean}
28959 * @expose
28960 */
28961 this.isGroup = !!isGroup;
28962
28963 // The following cached collections are used to efficiently iterate over or look up fields when decoding.
28964
28965 /**
28966 * Cached fields.
28967 * @type {?Array.<!ProtoBuf.Reflect.Message.Field>}
28968 * @private
28969 */
28970 this._fields = null;
28971
28972 /**
28973 * Cached fields by id.
28974 * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>}
28975 * @private
28976 */
28977 this._fieldsById = null;
28978
28979 /**
28980 * Cached fields by name.
28981 * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>}
28982 * @private
28983 */
28984 this._fieldsByName = null;
28985 };
28986
28987 /**
28988 * @alias ProtoBuf.Reflect.Message.prototype
28989 * @inner
28990 */
28991 var MessagePrototype = Message.prototype = Object.create(Namespace.prototype);
28992
28993 /**
28994 * Builds the message and returns the runtime counterpart, which is a fully functional class.
28995 * @see ProtoBuf.Builder.Message
28996 * @param {boolean=} rebuild Whether to rebuild or not, defaults to false
28997 * @return {ProtoBuf.Reflect.Message} Message class
28998 * @throws {Error} If the message cannot be built
28999 * @expose
29000 */
29001 MessagePrototype.build = function(rebuild) {
29002 if (this.clazz && !rebuild)
29003 return this.clazz;
29004
29005 // Create the runtime Message class in its own scope
29006 var clazz = (function(ProtoBuf, T) {
29007
29008 var fields = T.getChildren(ProtoBuf.Reflect.Message.Field),
29009 oneofs = T.getChildren(ProtoBuf.Reflect.Message.OneOf);
29010
29011 /**
29012 * Constructs a new runtime Message.
29013 * @name ProtoBuf.Builder.Message
29014 * @class Barebone of all runtime messages.
29015 * @param {!Object.<string,*>|string} values Preset values
29016 * @param {...string} var_args
29017 * @constructor
29018 * @throws {Error} If the message cannot be created
29019 */
29020 var Message = function(values, var_args) {
29021 ProtoBuf.Builder.Message.call(this);
29022
29023 // Create virtual oneof properties
29024 for (var i=0, k=oneofs.length; i<k; ++i)
29025 this[oneofs[i].name] = null;
29026 // Create fields and set default values
29027 for (i=0, k=fields.length; i<k; ++i) {
29028 var field = fields[i];
29029 this[field.name] =
29030 field.repeated ? [] :
29031 (field.map ? new ProtoBuf.Map(field) : null);
29032 if ((field.required || T.syntax === 'proto3') &&
29033 field.defaultValue !== null)
29034 this[field.name] = field.defaultValue;
29035 }
29036
29037 if (arguments.length > 0) {
29038 var value;
29039 // Set field values from a values object
29040 if (arguments.length === 1 && values !== null && typeof values === 'object' &&
29041 /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) &&
29042 /* not a repeated field */ !Array.isArray(values) &&
29043 /* not a Map */ !(values instanceof ProtoBuf.Map) &&
29044 /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) &&
29045 /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) &&
29046 /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) {
29047 this.$set(values);
29048 } else // Set field values from arguments, in declaration order
29049 for (i=0, k=arguments.length; i<k; ++i)
29050 if (typeof (value = arguments[i]) !== 'undefined')
29051 this.$set(fields[i].name, value); // May throw
29052 }
29053 };
29054
29055 /**
29056 * @alias ProtoBuf.Builder.Message.prototype
29057 * @inner
29058 */
29059 var MessagePrototype = Message.prototype = Object.create(ProtoBuf.Builder.Message.prototype);
29060
29061 /**
29062 * Adds a value to a repeated field.
29063 * @name ProtoBuf.Builder.Message#add
29064 * @function
29065 * @param {string} key Field name
29066 * @param {*} value Value to add
29067 * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
29068 * @returns {!ProtoBuf.Builder.Message} this
29069 * @throws {Error} If the value cannot be added
29070 * @expose
29071 */
29072 MessagePrototype.add = function(key, value, noAssert) {
29073 var field = T._fieldsByName[key];
29074 if (!noAssert) {
29075 if (!field)
29076 throw Error(this+"#"+key+" is undefined");
29077 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
29078 throw Error(this+"#"+key+" is not a field: "+field.toString(true)); // May throw if it's an enum or embedded message
29079 if (!field.repeated)
29080 throw Error(this+"#"+key+" is not a repeated field");
29081 value = field.verifyValue(value, true);
29082 }
29083 if (this[key] === null)
29084 this[key] = [];
29085 this[key].push(value);
29086 return this;
29087 };
29088
29089 /**
29090 * Adds a value to a repeated field. This is an alias for {@link ProtoBuf.Builder.Message#add}.
29091 * @name ProtoBuf.Builder.Message#$add
29092 * @function
29093 * @param {string} key Field name
29094 * @param {*} value Value to add
29095 * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
29096 * @returns {!ProtoBuf.Builder.Message} this
29097 * @throws {Error} If the value cannot be added
29098 * @expose
29099 */
29100 MessagePrototype.$add = MessagePrototype.add;
29101
29102 /**
29103 * Sets a field's value.
29104 * @name ProtoBuf.Builder.Message#set
29105 * @function
29106 * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
29107 * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
29108 * @param {boolean=} noAssert Whether to not assert for an actual field / proper value type, defaults to `false`
29109 * @returns {!ProtoBuf.Builder.Message} this
29110 * @throws {Error} If the value cannot be set
29111 * @expose
29112 */
29113 MessagePrototype.set = function(keyOrObj, value, noAssert) {
29114 if (keyOrObj && typeof keyOrObj === 'object') {
29115 noAssert = value;
29116 for (var ikey in keyOrObj) {
29117 // Check if virtual oneof field - don't set these
29118 if (keyOrObj.hasOwnProperty(ikey) && typeof (value = keyOrObj[ikey]) !== 'undefined' && T._oneofsByName[ikey] === undefined)
29119 this.$set(ikey, value, noAssert);
29120 }
29121 return this;
29122 }
29123 var field = T._fieldsByName[keyOrObj];
29124 if (!noAssert) {
29125 if (!field)
29126 throw Error(this+"#"+keyOrObj+" is not a field: undefined");
29127 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
29128 throw Error(this+"#"+keyOrObj+" is not a field: "+field.toString(true));
29129 this[field.name] = (value = field.verifyValue(value)); // May throw
29130 } else
29131 this[keyOrObj] = value;
29132 if (field && field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
29133 var currentField = this[field.oneof.name]; // Virtual field references currently set field
29134 if (value !== null) {
29135 if (currentField !== null && currentField !== field.name)
29136 this[currentField] = null; // Clear currently set field
29137 this[field.oneof.name] = field.name; // Point virtual field at this field
29138 } else if (/* value === null && */currentField === keyOrObj)
29139 this[field.oneof.name] = null; // Clear virtual field (current field explicitly cleared)
29140 }
29141 return this;
29142 };
29143
29144 /**
29145 * Sets a field's value. This is an alias for [@link ProtoBuf.Builder.Message#set}.
29146 * @name ProtoBuf.Builder.Message#$set
29147 * @function
29148 * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
29149 * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
29150 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
29151 * @throws {Error} If the value cannot be set
29152 * @expose
29153 */
29154 MessagePrototype.$set = MessagePrototype.set;
29155
29156 /**
29157 * Gets a field's value.
29158 * @name ProtoBuf.Builder.Message#get
29159 * @function
29160 * @param {string} key Key
29161 * @param {boolean=} noAssert Whether to not assert for an actual field, defaults to `false`
29162 * @return {*} Value
29163 * @throws {Error} If there is no such field
29164 * @expose
29165 */
29166 MessagePrototype.get = function(key, noAssert) {
29167 if (noAssert)
29168 return this[key];
29169 var field = T._fieldsByName[key];
29170 if (!field || !(field instanceof ProtoBuf.Reflect.Message.Field))
29171 throw Error(this+"#"+key+" is not a field: undefined");
29172 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
29173 throw Error(this+"#"+key+" is not a field: "+field.toString(true));
29174 return this[field.name];
29175 };
29176
29177 /**
29178 * Gets a field's value. This is an alias for {@link ProtoBuf.Builder.Message#$get}.
29179 * @name ProtoBuf.Builder.Message#$get
29180 * @function
29181 * @param {string} key Key
29182 * @return {*} Value
29183 * @throws {Error} If there is no such field
29184 * @expose
29185 */
29186 MessagePrototype.$get = MessagePrototype.get;
29187
29188 // Getters and setters
29189
29190 for (var i=0; i<fields.length; i++) {
29191 var field = fields[i];
29192 // no setters for extension fields as these are named by their fqn
29193 if (field instanceof ProtoBuf.Reflect.Message.ExtensionField)
29194 continue;
29195
29196 if (T.builder.options['populateAccessors'])
29197 (function(field) {
29198 // set/get[SomeValue]
29199 var Name = field.originalName.replace(/(_[a-zA-Z])/g, function(match) {
29200 return match.toUpperCase().replace('_','');
29201 });
29202 Name = Name.substring(0,1).toUpperCase() + Name.substring(1);
29203
29204 // set/get_[some_value] FIXME: Do we really need these?
29205 var name = field.originalName.replace(/([A-Z])/g, function(match) {
29206 return "_"+match;
29207 });
29208
29209 /**
29210 * The current field's unbound setter function.
29211 * @function
29212 * @param {*} value
29213 * @param {boolean=} noAssert
29214 * @returns {!ProtoBuf.Builder.Message}
29215 * @inner
29216 */
29217 var setter = function(value, noAssert) {
29218 this[field.name] = noAssert ? value : field.verifyValue(value);
29219 return this;
29220 };
29221
29222 /**
29223 * The current field's unbound getter function.
29224 * @function
29225 * @returns {*}
29226 * @inner
29227 */
29228 var getter = function() {
29229 return this[field.name];
29230 };
29231
29232 if (T.getChild("set"+Name) === null)
29233 /**
29234 * Sets a value. This method is present for each field, but only if there is no name conflict with
29235 * another field.
29236 * @name ProtoBuf.Builder.Message#set[SomeField]
29237 * @function
29238 * @param {*} value Value to set
29239 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
29240 * @returns {!ProtoBuf.Builder.Message} this
29241 * @abstract
29242 * @throws {Error} If the value cannot be set
29243 */
29244 MessagePrototype["set"+Name] = setter;
29245
29246 if (T.getChild("set_"+name) === null)
29247 /**
29248 * Sets a value. This method is present for each field, but only if there is no name conflict with
29249 * another field.
29250 * @name ProtoBuf.Builder.Message#set_[some_field]
29251 * @function
29252 * @param {*} value Value to set
29253 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
29254 * @returns {!ProtoBuf.Builder.Message} this
29255 * @abstract
29256 * @throws {Error} If the value cannot be set
29257 */
29258 MessagePrototype["set_"+name] = setter;
29259
29260 if (T.getChild("get"+Name) === null)
29261 /**
29262 * Gets a value. This method is present for each field, but only if there is no name conflict with
29263 * another field.
29264 * @name ProtoBuf.Builder.Message#get[SomeField]
29265 * @function
29266 * @abstract
29267 * @return {*} The value
29268 */
29269 MessagePrototype["get"+Name] = getter;
29270
29271 if (T.getChild("get_"+name) === null)
29272 /**
29273 * Gets a value. This method is present for each field, but only if there is no name conflict with
29274 * another field.
29275 * @name ProtoBuf.Builder.Message#get_[some_field]
29276 * @function
29277 * @return {*} The value
29278 * @abstract
29279 */
29280 MessagePrototype["get_"+name] = getter;
29281
29282 })(field);
29283 }
29284
29285 // En-/decoding
29286
29287 /**
29288 * Encodes the message.
29289 * @name ProtoBuf.Builder.Message#$encode
29290 * @function
29291 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
29292 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
29293 * @return {!ByteBuffer} Encoded message as a ByteBuffer
29294 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
29295 * returns the encoded ByteBuffer in the `encoded` property on the error.
29296 * @expose
29297 * @see ProtoBuf.Builder.Message#encode64
29298 * @see ProtoBuf.Builder.Message#encodeHex
29299 * @see ProtoBuf.Builder.Message#encodeAB
29300 */
29301 MessagePrototype.encode = function(buffer, noVerify) {
29302 if (typeof buffer === 'boolean')
29303 noVerify = buffer,
29304 buffer = undefined;
29305 var isNew = false;
29306 if (!buffer)
29307 buffer = new ByteBuffer(),
29308 isNew = true;
29309 var le = buffer.littleEndian;
29310 try {
29311 T.encode(this, buffer.LE(), noVerify);
29312 return (isNew ? buffer.flip() : buffer).LE(le);
29313 } catch (e) {
29314 buffer.LE(le);
29315 throw(e);
29316 }
29317 };
29318
29319 /**
29320 * Encodes a message using the specified data payload.
29321 * @param {!Object.<string,*>} data Data payload
29322 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
29323 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
29324 * @return {!ByteBuffer} Encoded message as a ByteBuffer
29325 * @expose
29326 */
29327 Message.encode = function(data, buffer, noVerify) {
29328 return new Message(data).encode(buffer, noVerify);
29329 };
29330
29331 /**
29332 * Calculates the byte length of the message.
29333 * @name ProtoBuf.Builder.Message#calculate
29334 * @function
29335 * @returns {number} Byte length
29336 * @throws {Error} If the message cannot be calculated or if required fields are missing.
29337 * @expose
29338 */
29339 MessagePrototype.calculate = function() {
29340 return T.calculate(this);
29341 };
29342
29343 /**
29344 * Encodes the varint32 length-delimited message.
29345 * @name ProtoBuf.Builder.Message#encodeDelimited
29346 * @function
29347 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
29348 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
29349 * @return {!ByteBuffer} Encoded message as a ByteBuffer
29350 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
29351 * returns the encoded ByteBuffer in the `encoded` property on the error.
29352 * @expose
29353 */
29354 MessagePrototype.encodeDelimited = function(buffer, noVerify) {
29355 var isNew = false;
29356 if (!buffer)
29357 buffer = new ByteBuffer(),
29358 isNew = true;
29359 var enc = new ByteBuffer().LE();
29360 T.encode(this, enc, noVerify).flip();
29361 buffer.writeVarint32(enc.remaining());
29362 buffer.append(enc);
29363 return isNew ? buffer.flip() : buffer;
29364 };
29365
29366 /**
29367 * Directly encodes the message to an ArrayBuffer.
29368 * @name ProtoBuf.Builder.Message#encodeAB
29369 * @function
29370 * @return {ArrayBuffer} Encoded message as ArrayBuffer
29371 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
29372 * returns the encoded ArrayBuffer in the `encoded` property on the error.
29373 * @expose
29374 */
29375 MessagePrototype.encodeAB = function() {
29376 try {
29377 return this.encode().toArrayBuffer();
29378 } catch (e) {
29379 if (e["encoded"]) e["encoded"] = e["encoded"].toArrayBuffer();
29380 throw(e);
29381 }
29382 };
29383
29384 /**
29385 * Returns the message as an ArrayBuffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeAB}.
29386 * @name ProtoBuf.Builder.Message#toArrayBuffer
29387 * @function
29388 * @return {ArrayBuffer} Encoded message as ArrayBuffer
29389 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
29390 * returns the encoded ArrayBuffer in the `encoded` property on the error.
29391 * @expose
29392 */
29393 MessagePrototype.toArrayBuffer = MessagePrototype.encodeAB;
29394
29395 /**
29396 * Directly encodes the message to a node Buffer.
29397 * @name ProtoBuf.Builder.Message#encodeNB
29398 * @function
29399 * @return {!Buffer}
29400 * @throws {Error} If the message cannot be encoded, not running under node.js or if required fields are
29401 * missing. The later still returns the encoded node Buffer in the `encoded` property on the error.
29402 * @expose
29403 */
29404 MessagePrototype.encodeNB = function() {
29405 try {
29406 return this.encode().toBuffer();
29407 } catch (e) {
29408 if (e["encoded"]) e["encoded"] = e["encoded"].toBuffer();
29409 throw(e);
29410 }
29411 };
29412
29413 /**
29414 * Returns the message as a node Buffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeNB}.
29415 * @name ProtoBuf.Builder.Message#toBuffer
29416 * @function
29417 * @return {!Buffer}
29418 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
29419 * returns the encoded node Buffer in the `encoded` property on the error.
29420 * @expose
29421 */
29422 MessagePrototype.toBuffer = MessagePrototype.encodeNB;
29423
29424 /**
29425 * Directly encodes the message to a base64 encoded string.
29426 * @name ProtoBuf.Builder.Message#encode64
29427 * @function
29428 * @return {string} Base64 encoded string
29429 * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
29430 * still returns the encoded base64 string in the `encoded` property on the error.
29431 * @expose
29432 */
29433 MessagePrototype.encode64 = function() {
29434 try {
29435 return this.encode().toBase64();
29436 } catch (e) {
29437 if (e["encoded"]) e["encoded"] = e["encoded"].toBase64();
29438 throw(e);
29439 }
29440 };
29441
29442 /**
29443 * Returns the message as a base64 encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encode64}.
29444 * @name ProtoBuf.Builder.Message#toBase64
29445 * @function
29446 * @return {string} Base64 encoded string
29447 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
29448 * returns the encoded base64 string in the `encoded` property on the error.
29449 * @expose
29450 */
29451 MessagePrototype.toBase64 = MessagePrototype.encode64;
29452
29453 /**
29454 * Directly encodes the message to a hex encoded string.
29455 * @name ProtoBuf.Builder.Message#encodeHex
29456 * @function
29457 * @return {string} Hex encoded string
29458 * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
29459 * still returns the encoded hex string in the `encoded` property on the error.
29460 * @expose
29461 */
29462 MessagePrototype.encodeHex = function() {
29463 try {
29464 return this.encode().toHex();
29465 } catch (e) {
29466 if (e["encoded"]) e["encoded"] = e["encoded"].toHex();
29467 throw(e);
29468 }
29469 };
29470
29471 /**
29472 * Returns the message as a hex encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encodeHex}.
29473 * @name ProtoBuf.Builder.Message#toHex
29474 * @function
29475 * @return {string} Hex encoded string
29476 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
29477 * returns the encoded hex string in the `encoded` property on the error.
29478 * @expose
29479 */
29480 MessagePrototype.toHex = MessagePrototype.encodeHex;
29481
29482 /**
29483 * Clones a message object or field value to a raw object.
29484 * @param {*} obj Object to clone
29485 * @param {boolean} binaryAsBase64 Whether to include binary data as base64 strings or as a buffer otherwise
29486 * @param {boolean} longsAsStrings Whether to encode longs as strings
29487 * @param {!ProtoBuf.Reflect.T=} resolvedType The resolved field type if a field
29488 * @returns {*} Cloned object
29489 * @inner
29490 */
29491 function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) {
29492 if (obj === null || typeof obj !== 'object') {
29493 // Convert enum values to their respective names
29494 if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) {
29495 var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj);
29496 if (name !== null)
29497 return name;
29498 }
29499 // Pass-through string, number, boolean, null...
29500 return obj;
29501 }
29502 // Convert ByteBuffers to raw buffer or strings
29503 if (ByteBuffer.isByteBuffer(obj))
29504 return binaryAsBase64 ? obj.toBase64() : obj.toBuffer();
29505 // Convert Longs to proper objects or strings
29506 if (ProtoBuf.Long.isLong(obj))
29507 return longsAsStrings ? obj.toString() : ProtoBuf.Long.fromValue(obj);
29508 var clone;
29509 // Clone arrays
29510 if (Array.isArray(obj)) {
29511 clone = [];
29512 obj.forEach(function(v, k) {
29513 clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType);
29514 });
29515 return clone;
29516 }
29517 clone = {};
29518 // Convert maps to objects
29519 if (obj instanceof ProtoBuf.Map) {
29520 var it = obj.entries();
29521 for (var e = it.next(); !e.done; e = it.next())
29522 clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType);
29523 return clone;
29524 }
29525 // Everything else is a non-null object
29526 var type = obj.$type,
29527 field = undefined;
29528 for (var i in obj)
29529 if (obj.hasOwnProperty(i)) {
29530 if (type && (field = type.getChild(i)))
29531 clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType);
29532 else
29533 clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings);
29534 }
29535 return clone;
29536 }
29537
29538 /**
29539 * Returns the message's raw payload.
29540 * @param {boolean=} binaryAsBase64 Whether to include binary data as base64 strings instead of Buffers, defaults to `false`
29541 * @param {boolean} longsAsStrings Whether to encode longs as strings
29542 * @returns {Object.<string,*>} Raw payload
29543 * @expose
29544 */
29545 MessagePrototype.toRaw = function(binaryAsBase64, longsAsStrings) {
29546 return cloneRaw(this, !!binaryAsBase64, !!longsAsStrings, this.$type);
29547 };
29548
29549 /**
29550 * Encodes a message to JSON.
29551 * @returns {string} JSON string
29552 * @expose
29553 */
29554 MessagePrototype.encodeJSON = function() {
29555 return JSON.stringify(
29556 cloneRaw(this,
29557 /* binary-as-base64 */ true,
29558 /* longs-as-strings */ true,
29559 this.$type
29560 )
29561 );
29562 };
29563
29564 /**
29565 * Decodes a message from the specified buffer or string.
29566 * @name ProtoBuf.Builder.Message.decode
29567 * @function
29568 * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
29569 * @param {(number|string)=} length Message length. Defaults to decode all the remainig data.
29570 * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
29571 * @return {!ProtoBuf.Builder.Message} Decoded message
29572 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
29573 * returns the decoded message with missing fields in the `decoded` property on the error.
29574 * @expose
29575 * @see ProtoBuf.Builder.Message.decode64
29576 * @see ProtoBuf.Builder.Message.decodeHex
29577 */
29578 Message.decode = function(buffer, length, enc) {
29579 if (typeof length === 'string')
29580 enc = length,
29581 length = -1;
29582 if (typeof buffer === 'string')
29583 buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
29584 else if (!ByteBuffer.isByteBuffer(buffer))
29585 buffer = ByteBuffer.wrap(buffer); // May throw
29586 var le = buffer.littleEndian;
29587 try {
29588 var msg = T.decode(buffer.LE(), length);
29589 buffer.LE(le);
29590 return msg;
29591 } catch (e) {
29592 buffer.LE(le);
29593 throw(e);
29594 }
29595 };
29596
29597 /**
29598 * Decodes a varint32 length-delimited message from the specified buffer or string.
29599 * @name ProtoBuf.Builder.Message.decodeDelimited
29600 * @function
29601 * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
29602 * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
29603 * @return {ProtoBuf.Builder.Message} Decoded message or `null` if not enough bytes are available yet
29604 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
29605 * returns the decoded message with missing fields in the `decoded` property on the error.
29606 * @expose
29607 */
29608 Message.decodeDelimited = function(buffer, enc) {
29609 if (typeof buffer === 'string')
29610 buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
29611 else if (!ByteBuffer.isByteBuffer(buffer))
29612 buffer = ByteBuffer.wrap(buffer); // May throw
29613 if (buffer.remaining() < 1)
29614 return null;
29615 var off = buffer.offset,
29616 len = buffer.readVarint32();
29617 if (buffer.remaining() < len) {
29618 buffer.offset = off;
29619 return null;
29620 }
29621 try {
29622 var msg = T.decode(buffer.slice(buffer.offset, buffer.offset + len).LE());
29623 buffer.offset += len;
29624 return msg;
29625 } catch (err) {
29626 buffer.offset += len;
29627 throw err;
29628 }
29629 };
29630
29631 /**
29632 * Decodes the message from the specified base64 encoded string.
29633 * @name ProtoBuf.Builder.Message.decode64
29634 * @function
29635 * @param {string} str String to decode from
29636 * @return {!ProtoBuf.Builder.Message} Decoded message
29637 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
29638 * returns the decoded message with missing fields in the `decoded` property on the error.
29639 * @expose
29640 */
29641 Message.decode64 = function(str) {
29642 return Message.decode(str, "base64");
29643 };
29644
29645 /**
29646 * Decodes the message from the specified hex encoded string.
29647 * @name ProtoBuf.Builder.Message.decodeHex
29648 * @function
29649 * @param {string} str String to decode from
29650 * @return {!ProtoBuf.Builder.Message} Decoded message
29651 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
29652 * returns the decoded message with missing fields in the `decoded` property on the error.
29653 * @expose
29654 */
29655 Message.decodeHex = function(str) {
29656 return Message.decode(str, "hex");
29657 };
29658
29659 /**
29660 * Decodes the message from a JSON string.
29661 * @name ProtoBuf.Builder.Message.decodeJSON
29662 * @function
29663 * @param {string} str String to decode from
29664 * @return {!ProtoBuf.Builder.Message} Decoded message
29665 * @throws {Error} If the message cannot be decoded or if required fields are
29666 * missing.
29667 * @expose
29668 */
29669 Message.decodeJSON = function(str) {
29670 return new Message(JSON.parse(str));
29671 };
29672
29673 // Utility
29674
29675 /**
29676 * Returns a string representation of this Message.
29677 * @name ProtoBuf.Builder.Message#toString
29678 * @function
29679 * @return {string} String representation as of ".Fully.Qualified.MessageName"
29680 * @expose
29681 */
29682 MessagePrototype.toString = function() {
29683 return T.toString();
29684 };
29685
29686 // Properties
29687
29688 /**
29689 * Message options.
29690 * @name ProtoBuf.Builder.Message.$options
29691 * @type {Object.<string,*>}
29692 * @expose
29693 */
29694 var $optionsS; // cc needs this
29695
29696 /**
29697 * Message options.
29698 * @name ProtoBuf.Builder.Message#$options
29699 * @type {Object.<string,*>}
29700 * @expose
29701 */
29702 var $options;
29703
29704 /**
29705 * Reflection type.
29706 * @name ProtoBuf.Builder.Message.$type
29707 * @type {!ProtoBuf.Reflect.Message}
29708 * @expose
29709 */
29710 var $typeS;
29711
29712 /**
29713 * Reflection type.
29714 * @name ProtoBuf.Builder.Message#$type
29715 * @type {!ProtoBuf.Reflect.Message}
29716 * @expose
29717 */
29718 var $type;
29719
29720 if (Object.defineProperty)
29721 Object.defineProperty(Message, '$options', { "value": T.buildOpt() }),
29722 Object.defineProperty(MessagePrototype, "$options", { "value": Message["$options"] }),
29723 Object.defineProperty(Message, "$type", { "value": T }),
29724 Object.defineProperty(MessagePrototype, "$type", { "value": T });
29725
29726 return Message;
29727
29728 })(ProtoBuf, this);
29729
29730 // Static enums and prototyped sub-messages / cached collections
29731 this._fields = [];
29732 this._fieldsById = {};
29733 this._fieldsByName = {};
29734 this._oneofsByName = {};
29735 for (var i=0, k=this.children.length, child; i<k; i++) {
29736 child = this.children[i];
29737 if (child instanceof Enum || child instanceof Message || child instanceof Service) {
29738 if (clazz.hasOwnProperty(child.name))
29739 throw Error("Illegal reflect child of "+this.toString(true)+": "+child.toString(true)+" cannot override static property '"+child.name+"'");
29740 clazz[child.name] = child.build();
29741 } else if (child instanceof Message.Field)
29742 child.build(),
29743 this._fields.push(child),
29744 this._fieldsById[child.id] = child,
29745 this._fieldsByName[child.name] = child;
29746 else if (child instanceof Message.OneOf) {
29747 this._oneofsByName[child.name] = child;
29748 }
29749 else if (!(child instanceof Message.OneOf) && !(child instanceof Extension)) // Not built
29750 throw Error("Illegal reflect child of "+this.toString(true)+": "+this.children[i].toString(true));
29751 }
29752
29753 return this.clazz = clazz;
29754 };
29755
29756 /**
29757 * Encodes a runtime message's contents to the specified buffer.
29758 * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
29759 * @param {ByteBuffer} buffer ByteBuffer to write to
29760 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
29761 * @return {ByteBuffer} The ByteBuffer for chaining
29762 * @throws {Error} If required fields are missing or the message cannot be encoded for another reason
29763 * @expose
29764 */
29765 MessagePrototype.encode = function(message, buffer, noVerify) {
29766 var fieldMissing = null,
29767 field;
29768 for (var i=0, k=this._fields.length, val; i<k; ++i) {
29769 field = this._fields[i];
29770 val = message[field.name];
29771 if (field.required && val === null) {
29772 if (fieldMissing === null)
29773 fieldMissing = field;
29774 } else
29775 field.encode(noVerify ? val : field.verifyValue(val), buffer, message);
29776 }
29777 if (fieldMissing !== null) {
29778 var err = Error("Missing at least one required field for "+this.toString(true)+": "+fieldMissing);
29779 err["encoded"] = buffer; // Still expose what we got
29780 throw(err);
29781 }
29782 return buffer;
29783 };
29784
29785 /**
29786 * Calculates a runtime message's byte length.
29787 * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
29788 * @returns {number} Byte length
29789 * @throws {Error} If required fields are missing or the message cannot be calculated for another reason
29790 * @expose
29791 */
29792 MessagePrototype.calculate = function(message) {
29793 for (var n=0, i=0, k=this._fields.length, field, val; i<k; ++i) {
29794 field = this._fields[i];
29795 val = message[field.name];
29796 if (field.required && val === null)
29797 throw Error("Missing at least one required field for "+this.toString(true)+": "+field);
29798 else
29799 n += field.calculate(val, message);
29800 }
29801 return n;
29802 };
29803
29804 /**
29805 * Skips all data until the end of the specified group has been reached.
29806 * @param {number} expectedId Expected GROUPEND id
29807 * @param {!ByteBuffer} buf ByteBuffer
29808 * @returns {boolean} `true` if a value as been skipped, `false` if the end has been reached
29809 * @throws {Error} If it wasn't possible to find the end of the group (buffer overrun or end tag mismatch)
29810 * @inner
29811 */
29812 function skipTillGroupEnd(expectedId, buf) {
29813 var tag = buf.readVarint32(), // Throws on OOB
29814 wireType = tag & 0x07,
29815 id = tag >>> 3;
29816 switch (wireType) {
29817 case ProtoBuf.WIRE_TYPES.VARINT:
29818 do tag = buf.readUint8();
29819 while ((tag & 0x80) === 0x80);
29820 break;
29821 case ProtoBuf.WIRE_TYPES.BITS64:
29822 buf.offset += 8;
29823 break;
29824 case ProtoBuf.WIRE_TYPES.LDELIM:
29825 tag = buf.readVarint32(); // reads the varint
29826 buf.offset += tag; // skips n bytes
29827 break;
29828 case ProtoBuf.WIRE_TYPES.STARTGROUP:
29829 skipTillGroupEnd(id, buf);
29830 break;
29831 case ProtoBuf.WIRE_TYPES.ENDGROUP:
29832 if (id === expectedId)
29833 return false;
29834 else
29835 throw Error("Illegal GROUPEND after unknown group: "+id+" ("+expectedId+" expected)");
29836 case ProtoBuf.WIRE_TYPES.BITS32:
29837 buf.offset += 4;
29838 break;
29839 default:
29840 throw Error("Illegal wire type in unknown group "+expectedId+": "+wireType);
29841 }
29842 return true;
29843 }
29844
29845 /**
29846 * Decodes an encoded message and returns the decoded message.
29847 * @param {ByteBuffer} buffer ByteBuffer to decode from
29848 * @param {number=} length Message length. Defaults to decode all remaining data.
29849 * @param {number=} expectedGroupEndId Expected GROUPEND id if this is a legacy group
29850 * @return {ProtoBuf.Builder.Message} Decoded message
29851 * @throws {Error} If the message cannot be decoded
29852 * @expose
29853 */
29854 MessagePrototype.decode = function(buffer, length, expectedGroupEndId) {
29855 if (typeof length !== 'number')
29856 length = -1;
29857 var start = buffer.offset,
29858 msg = new (this.clazz)(),
29859 tag, wireType, id, field;
29860 while (buffer.offset < start+length || (length === -1 && buffer.remaining() > 0)) {
29861 tag = buffer.readVarint32();
29862 wireType = tag & 0x07;
29863 id = tag >>> 3;
29864 if (wireType === ProtoBuf.WIRE_TYPES.ENDGROUP) {
29865 if (id !== expectedGroupEndId)
29866 throw Error("Illegal group end indicator for "+this.toString(true)+": "+id+" ("+(expectedGroupEndId ? expectedGroupEndId+" expected" : "not a group")+")");
29867 break;
29868 }
29869 if (!(field = this._fieldsById[id])) {
29870 // "messages created by your new code can be parsed by your old code: old binaries simply ignore the new field when parsing."
29871 switch (wireType) {
29872 case ProtoBuf.WIRE_TYPES.VARINT:
29873 buffer.readVarint32();
29874 break;
29875 case ProtoBuf.WIRE_TYPES.BITS32:
29876 buffer.offset += 4;
29877 break;
29878 case ProtoBuf.WIRE_TYPES.BITS64:
29879 buffer.offset += 8;
29880 break;
29881 case ProtoBuf.WIRE_TYPES.LDELIM:
29882 var len = buffer.readVarint32();
29883 buffer.offset += len;
29884 break;
29885 case ProtoBuf.WIRE_TYPES.STARTGROUP:
29886 while (skipTillGroupEnd(id, buffer)) {}
29887 break;
29888 default:
29889 throw Error("Illegal wire type for unknown field "+id+" in "+this.toString(true)+"#decode: "+wireType);
29890 }
29891 continue;
29892 }
29893 if (field.repeated && !field.options["packed"]) {
29894 msg[field.name].push(field.decode(wireType, buffer));
29895 } else if (field.map) {
29896 var keyval = field.decode(wireType, buffer);
29897 msg[field.name].set(keyval[0], keyval[1]);
29898 } else {
29899 msg[field.name] = field.decode(wireType, buffer);
29900 if (field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
29901 var currentField = msg[field.oneof.name]; // Virtual field references currently set field
29902 if (currentField !== null && currentField !== field.name)
29903 msg[currentField] = null; // Clear currently set field
29904 msg[field.oneof.name] = field.name; // Point virtual field at this field
29905 }
29906 }
29907 }
29908
29909 // Check if all required fields are present and set default values for optional fields that are not
29910 for (var i=0, k=this._fields.length; i<k; ++i) {
29911 field = this._fields[i];
29912 if (msg[field.name] === null) {
29913 if (this.syntax === "proto3") { // Proto3 sets default values by specification
29914 msg[field.name] = field.defaultValue;
29915 } else if (field.required) {
29916 var err = Error("Missing at least one required field for " + this.toString(true) + ": " + field.name);
29917 err["decoded"] = msg; // Still expose what we got
29918 throw(err);
29919 } else if (ProtoBuf.populateDefaults && field.defaultValue !== null)
29920 msg[field.name] = field.defaultValue;
29921 }
29922 }
29923 return msg;
29924 };
29925
29926 /**
29927 * @alias ProtoBuf.Reflect.Message
29928 * @expose
29929 */
29930 Reflect.Message = Message;
29931
29932 /**
29933 * Constructs a new Message Field.
29934 * @exports ProtoBuf.Reflect.Message.Field
29935 * @param {!ProtoBuf.Builder} builder Builder reference
29936 * @param {!ProtoBuf.Reflect.Message} message Message reference
29937 * @param {string} rule Rule, one of requried, optional, repeated
29938 * @param {string?} keytype Key data type, if any.
29939 * @param {string} type Data type, e.g. int32
29940 * @param {string} name Field name
29941 * @param {number} id Unique field id
29942 * @param {Object.<string,*>=} options Options
29943 * @param {!ProtoBuf.Reflect.Message.OneOf=} oneof Enclosing OneOf
29944 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
29945 * @constructor
29946 * @extends ProtoBuf.Reflect.T
29947 */
29948 var Field = function(builder, message, rule, keytype, type, name, id, options, oneof, syntax) {
29949 T.call(this, builder, message, name);
29950
29951 /**
29952 * @override
29953 */
29954 this.className = "Message.Field";
29955
29956 /**
29957 * Message field required flag.
29958 * @type {boolean}
29959 * @expose
29960 */
29961 this.required = rule === "required";
29962
29963 /**
29964 * Message field repeated flag.
29965 * @type {boolean}
29966 * @expose
29967 */
29968 this.repeated = rule === "repeated";
29969
29970 /**
29971 * Message field map flag.
29972 * @type {boolean}
29973 * @expose
29974 */
29975 this.map = rule === "map";
29976
29977 /**
29978 * Message field key type. Type reference string if unresolved, protobuf
29979 * type if resolved. Valid only if this.map === true, null otherwise.
29980 * @type {string|{name: string, wireType: number}|null}
29981 * @expose
29982 */
29983 this.keyType = keytype || null;
29984
29985 /**
29986 * Message field type. Type reference string if unresolved, protobuf type if
29987 * resolved. In a map field, this is the value type.
29988 * @type {string|{name: string, wireType: number}}
29989 * @expose
29990 */
29991 this.type = type;
29992
29993 /**
29994 * Resolved type reference inside the global namespace.
29995 * @type {ProtoBuf.Reflect.T|null}
29996 * @expose
29997 */
29998 this.resolvedType = null;
29999
30000 /**
30001 * Unique message field id.
30002 * @type {number}
30003 * @expose
30004 */
30005 this.id = id;
30006
30007 /**
30008 * Message field options.
30009 * @type {!Object.<string,*>}
30010 * @dict
30011 * @expose
30012 */
30013 this.options = options || {};
30014
30015 /**
30016 * Default value.
30017 * @type {*}
30018 * @expose
30019 */
30020 this.defaultValue = null;
30021
30022 /**
30023 * Enclosing OneOf.
30024 * @type {?ProtoBuf.Reflect.Message.OneOf}
30025 * @expose
30026 */
30027 this.oneof = oneof || null;
30028
30029 /**
30030 * Syntax level of this definition (e.g., proto3).
30031 * @type {string}
30032 * @expose
30033 */
30034 this.syntax = syntax || 'proto2';
30035
30036 /**
30037 * Original field name.
30038 * @type {string}
30039 * @expose
30040 */
30041 this.originalName = this.name; // Used to revert camelcase transformation on naming collisions
30042
30043 /**
30044 * Element implementation. Created in build() after types are resolved.
30045 * @type {ProtoBuf.Element}
30046 * @expose
30047 */
30048 this.element = null;
30049
30050 /**
30051 * Key element implementation, for map fields. Created in build() after
30052 * types are resolved.
30053 * @type {ProtoBuf.Element}
30054 * @expose
30055 */
30056 this.keyElement = null;
30057
30058 // Convert field names to camel case notation if the override is set
30059 if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField))
30060 this.name = ProtoBuf.Util.toCamelCase(this.name);
30061 };
30062
30063 /**
30064 * @alias ProtoBuf.Reflect.Message.Field.prototype
30065 * @inner
30066 */
30067 var FieldPrototype = Field.prototype = Object.create(T.prototype);
30068
30069 /**
30070 * Builds the field.
30071 * @override
30072 * @expose
30073 */
30074 FieldPrototype.build = function() {
30075 this.element = new Element(this.type, this.resolvedType, false, this.syntax, this.name);
30076 if (this.map)
30077 this.keyElement = new Element(this.keyType, undefined, true, this.syntax, this.name);
30078
30079 // In proto3, fields do not have field presence, and every field is set to
30080 // its type's default value ("", 0, 0.0, or false).
30081 if (this.syntax === 'proto3' && !this.repeated && !this.map)
30082 this.defaultValue = Element.defaultFieldValue(this.type);
30083
30084 // Otherwise, default values are present when explicitly specified
30085 else if (typeof this.options['default'] !== 'undefined')
30086 this.defaultValue = this.verifyValue(this.options['default']);
30087 };
30088
30089 /**
30090 * Checks if the given value can be set for this field.
30091 * @param {*} value Value to check
30092 * @param {boolean=} skipRepeated Whether to skip the repeated value check or not. Defaults to false.
30093 * @return {*} Verified, maybe adjusted, value
30094 * @throws {Error} If the value cannot be set for this field
30095 * @expose
30096 */
30097 FieldPrototype.verifyValue = function(value, skipRepeated) {
30098 skipRepeated = skipRepeated || false;
30099 var self = this;
30100 function fail(val, msg) {
30101 throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
30102 }
30103 if (value === null) { // NULL values for optional fields
30104 if (this.required)
30105 fail(typeof value, "required");
30106 if (this.syntax === 'proto3' && this.type !== ProtoBuf.TYPES["message"])
30107 fail(typeof value, "proto3 field without field presence cannot be null");
30108 return null;
30109 }
30110 var i;
30111 if (this.repeated && !skipRepeated) { // Repeated values as arrays
30112 if (!Array.isArray(value))
30113 value = [value];
30114 var res = [];
30115 for (i=0; i<value.length; i++)
30116 res.push(this.element.verifyValue(value[i]));
30117 return res;
30118 }
30119 if (this.map && !skipRepeated) { // Map values as objects
30120 if (!(value instanceof ProtoBuf.Map)) {
30121 // If not already a Map, attempt to convert.
30122 if (!(value instanceof Object)) {
30123 fail(typeof value,
30124 "expected ProtoBuf.Map or raw object for map field");
30125 }
30126 return new ProtoBuf.Map(this, value);
30127 } else {
30128 return value;
30129 }
30130 }
30131 // All non-repeated fields expect no array
30132 if (!this.repeated && Array.isArray(value))
30133 fail(typeof value, "no array expected");
30134
30135 return this.element.verifyValue(value);
30136 };
30137
30138 /**
30139 * Determines whether the field will have a presence on the wire given its
30140 * value.
30141 * @param {*} value Verified field value
30142 * @param {!ProtoBuf.Builder.Message} message Runtime message
30143 * @return {boolean} Whether the field will be present on the wire
30144 */
30145 FieldPrototype.hasWirePresence = function(value, message) {
30146 if (this.syntax !== 'proto3')
30147 return (value !== null);
30148 if (this.oneof && message[this.oneof.name] === this.name)
30149 return true;
30150 switch (this.type) {
30151 case ProtoBuf.TYPES["int32"]:
30152 case ProtoBuf.TYPES["sint32"]:
30153 case ProtoBuf.TYPES["sfixed32"]:
30154 case ProtoBuf.TYPES["uint32"]:
30155 case ProtoBuf.TYPES["fixed32"]:
30156 return value !== 0;
30157
30158 case ProtoBuf.TYPES["int64"]:
30159 case ProtoBuf.TYPES["sint64"]:
30160 case ProtoBuf.TYPES["sfixed64"]:
30161 case ProtoBuf.TYPES["uint64"]:
30162 case ProtoBuf.TYPES["fixed64"]:
30163 return value.low !== 0 || value.high !== 0;
30164
30165 case ProtoBuf.TYPES["bool"]:
30166 return value;
30167
30168 case ProtoBuf.TYPES["float"]:
30169 case ProtoBuf.TYPES["double"]:
30170 return value !== 0.0;
30171
30172 case ProtoBuf.TYPES["string"]:
30173 return value.length > 0;
30174
30175 case ProtoBuf.TYPES["bytes"]:
30176 return value.remaining() > 0;
30177
30178 case ProtoBuf.TYPES["enum"]:
30179 return value !== 0;
30180
30181 case ProtoBuf.TYPES["message"]:
30182 return value !== null;
30183 default:
30184 return true;
30185 }
30186 };
30187
30188 /**
30189 * Encodes the specified field value to the specified buffer.
30190 * @param {*} value Verified field value
30191 * @param {ByteBuffer} buffer ByteBuffer to encode to
30192 * @param {!ProtoBuf.Builder.Message} message Runtime message
30193 * @return {ByteBuffer} The ByteBuffer for chaining
30194 * @throws {Error} If the field cannot be encoded
30195 * @expose
30196 */
30197 FieldPrototype.encode = function(value, buffer, message) {
30198 if (this.type === null || typeof this.type !== 'object')
30199 throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
30200 if (value === null || (this.repeated && value.length == 0))
30201 return buffer; // Optional omitted
30202 try {
30203 if (this.repeated) {
30204 var i;
30205 // "Only repeated fields of primitive numeric types (types which use the varint, 32-bit, or 64-bit wire
30206 // types) can be declared 'packed'."
30207 if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
30208 // "All of the elements of the field are packed into a single key-value pair with wire type 2
30209 // (length-delimited). Each element is encoded the same way it would be normally, except without a
30210 // tag preceding it."
30211 buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
30212 buffer.ensureCapacity(buffer.offset += 1); // We do not know the length yet, so let's assume a varint of length 1
30213 var start = buffer.offset; // Remember where the contents begin
30214 for (i=0; i<value.length; i++)
30215 this.element.encodeValue(this.id, value[i], buffer);
30216 var len = buffer.offset-start,
30217 varintLen = ByteBuffer.calculateVarint32(len);
30218 if (varintLen > 1) { // We need to move the contents
30219 var contents = buffer.slice(start, buffer.offset);
30220 start += varintLen-1;
30221 buffer.offset = start;
30222 buffer.append(contents);
30223 }
30224 buffer.writeVarint32(len, start-varintLen);
30225 } else {
30226 // "If your message definition has repeated elements (without the [packed=true] option), the encoded
30227 // message has zero or more key-value pairs with the same tag number"
30228 for (i=0; i<value.length; i++)
30229 buffer.writeVarint32((this.id << 3) | this.type.wireType),
30230 this.element.encodeValue(this.id, value[i], buffer);
30231 }
30232 } else if (this.map) {
30233 // Write out each map entry as a submessage.
30234 value.forEach(function(val, key, m) {
30235 // Compute the length of the submessage (key, val) pair.
30236 var length =
30237 ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
30238 this.keyElement.calculateLength(1, key) +
30239 ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
30240 this.element.calculateLength(2, val);
30241
30242 // Submessage with wire type of length-delimited.
30243 buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
30244 buffer.writeVarint32(length);
30245
30246 // Write out the key and val.
30247 buffer.writeVarint32((1 << 3) | this.keyType.wireType);
30248 this.keyElement.encodeValue(1, key, buffer);
30249 buffer.writeVarint32((2 << 3) | this.type.wireType);
30250 this.element.encodeValue(2, val, buffer);
30251 }, this);
30252 } else {
30253 if (this.hasWirePresence(value, message)) {
30254 buffer.writeVarint32((this.id << 3) | this.type.wireType);
30255 this.element.encodeValue(this.id, value, buffer);
30256 }
30257 }
30258 } catch (e) {
30259 throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
30260 }
30261 return buffer;
30262 };
30263
30264 /**
30265 * Calculates the length of this field's value on the network level.
30266 * @param {*} value Field value
30267 * @param {!ProtoBuf.Builder.Message} message Runtime message
30268 * @returns {number} Byte length
30269 * @expose
30270 */
30271 FieldPrototype.calculate = function(value, message) {
30272 value = this.verifyValue(value); // May throw
30273 if (this.type === null || typeof this.type !== 'object')
30274 throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
30275 if (value === null || (this.repeated && value.length == 0))
30276 return 0; // Optional omitted
30277 var n = 0;
30278 try {
30279 if (this.repeated) {
30280 var i, ni;
30281 if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
30282 n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
30283 ni = 0;
30284 for (i=0; i<value.length; i++)
30285 ni += this.element.calculateLength(this.id, value[i]);
30286 n += ByteBuffer.calculateVarint32(ni);
30287 n += ni;
30288 } else {
30289 for (i=0; i<value.length; i++)
30290 n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType),
30291 n += this.element.calculateLength(this.id, value[i]);
30292 }
30293 } else if (this.map) {
30294 // Each map entry becomes a submessage.
30295 value.forEach(function(val, key, m) {
30296 // Compute the length of the submessage (key, val) pair.
30297 var length =
30298 ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
30299 this.keyElement.calculateLength(1, key) +
30300 ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
30301 this.element.calculateLength(2, val);
30302
30303 n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
30304 n += ByteBuffer.calculateVarint32(length);
30305 n += length;
30306 }, this);
30307 } else {
30308 if (this.hasWirePresence(value, message)) {
30309 n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType);
30310 n += this.element.calculateLength(this.id, value);
30311 }
30312 }
30313 } catch (e) {
30314 throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
30315 }
30316 return n;
30317 };
30318
30319 /**
30320 * Decode the field value from the specified buffer.
30321 * @param {number} wireType Leading wire type
30322 * @param {ByteBuffer} buffer ByteBuffer to decode from
30323 * @param {boolean=} skipRepeated Whether to skip the repeated check or not. Defaults to false.
30324 * @return {*} Decoded value: array for packed repeated fields, [key, value] for
30325 * map fields, or an individual value otherwise.
30326 * @throws {Error} If the field cannot be decoded
30327 * @expose
30328 */
30329 FieldPrototype.decode = function(wireType, buffer, skipRepeated) {
30330 var value, nBytes;
30331
30332 // We expect wireType to match the underlying type's wireType unless we see
30333 // a packed repeated field, or unless this is a map field.
30334 var wireTypeOK =
30335 (!this.map && wireType == this.type.wireType) ||
30336 (!skipRepeated && this.repeated && this.options["packed"] &&
30337 wireType == ProtoBuf.WIRE_TYPES.LDELIM) ||
30338 (this.map && wireType == ProtoBuf.WIRE_TYPES.LDELIM);
30339 if (!wireTypeOK)
30340 throw Error("Illegal wire type for field "+this.toString(true)+": "+wireType+" ("+this.type.wireType+" expected)");
30341
30342 // Handle packed repeated fields.
30343 if (wireType == ProtoBuf.WIRE_TYPES.LDELIM && this.repeated && this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
30344 if (!skipRepeated) {
30345 nBytes = buffer.readVarint32();
30346 nBytes = buffer.offset + nBytes; // Limit
30347 var values = [];
30348 while (buffer.offset < nBytes)
30349 values.push(this.decode(this.type.wireType, buffer, true));
30350 return values;
30351 }
30352 // Read the next value otherwise...
30353 }
30354
30355 // Handle maps.
30356 if (this.map) {
30357 // Read one (key, value) submessage, and return [key, value]
30358 var key = Element.defaultFieldValue(this.keyType);
30359 value = Element.defaultFieldValue(this.type);
30360
30361 // Read the length
30362 nBytes = buffer.readVarint32();
30363 if (buffer.remaining() < nBytes)
30364 throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
30365
30366 // Get a sub-buffer of this key/value submessage
30367 var msgbuf = buffer.clone();
30368 msgbuf.limit = msgbuf.offset + nBytes;
30369 buffer.offset += nBytes;
30370
30371 while (msgbuf.remaining() > 0) {
30372 var tag = msgbuf.readVarint32();
30373 wireType = tag & 0x07;
30374 var id = tag >>> 3;
30375 if (id === 1) {
30376 key = this.keyElement.decode(msgbuf, wireType, id);
30377 } else if (id === 2) {
30378 value = this.element.decode(msgbuf, wireType, id);
30379 } else {
30380 throw Error("Unexpected tag in map field key/value submessage");
30381 }
30382 }
30383
30384 return [key, value];
30385 }
30386
30387 // Handle singular and non-packed repeated field values.
30388 return this.element.decode(buffer, wireType, this.id);
30389 };
30390
30391 /**
30392 * @alias ProtoBuf.Reflect.Message.Field
30393 * @expose
30394 */
30395 Reflect.Message.Field = Field;
30396
30397 /**
30398 * Constructs a new Message ExtensionField.
30399 * @exports ProtoBuf.Reflect.Message.ExtensionField
30400 * @param {!ProtoBuf.Builder} builder Builder reference
30401 * @param {!ProtoBuf.Reflect.Message} message Message reference
30402 * @param {string} rule Rule, one of requried, optional, repeated
30403 * @param {string} type Data type, e.g. int32
30404 * @param {string} name Field name
30405 * @param {number} id Unique field id
30406 * @param {!Object.<string,*>=} options Options
30407 * @constructor
30408 * @extends ProtoBuf.Reflect.Message.Field
30409 */
30410 var ExtensionField = function(builder, message, rule, type, name, id, options) {
30411 Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options);
30412
30413 /**
30414 * Extension reference.
30415 * @type {!ProtoBuf.Reflect.Extension}
30416 * @expose
30417 */
30418 this.extension;
30419 };
30420
30421 // Extends Field
30422 ExtensionField.prototype = Object.create(Field.prototype);
30423
30424 /**
30425 * @alias ProtoBuf.Reflect.Message.ExtensionField
30426 * @expose
30427 */
30428 Reflect.Message.ExtensionField = ExtensionField;
30429
30430 /**
30431 * Constructs a new Message OneOf.
30432 * @exports ProtoBuf.Reflect.Message.OneOf
30433 * @param {!ProtoBuf.Builder} builder Builder reference
30434 * @param {!ProtoBuf.Reflect.Message} message Message reference
30435 * @param {string} name OneOf name
30436 * @constructor
30437 * @extends ProtoBuf.Reflect.T
30438 */
30439 var OneOf = function(builder, message, name) {
30440 T.call(this, builder, message, name);
30441
30442 /**
30443 * Enclosed fields.
30444 * @type {!Array.<!ProtoBuf.Reflect.Message.Field>}
30445 * @expose
30446 */
30447 this.fields = [];
30448 };
30449
30450 /**
30451 * @alias ProtoBuf.Reflect.Message.OneOf
30452 * @expose
30453 */
30454 Reflect.Message.OneOf = OneOf;
30455
30456 /**
30457 * Constructs a new Enum.
30458 * @exports ProtoBuf.Reflect.Enum
30459 * @param {!ProtoBuf.Builder} builder Builder reference
30460 * @param {!ProtoBuf.Reflect.T} parent Parent Reflect object
30461 * @param {string} name Enum name
30462 * @param {Object.<string,*>=} options Enum options
30463 * @param {string?} syntax The syntax level (e.g., proto3)
30464 * @constructor
30465 * @extends ProtoBuf.Reflect.Namespace
30466 */
30467 var Enum = function(builder, parent, name, options, syntax) {
30468 Namespace.call(this, builder, parent, name, options, syntax);
30469
30470 /**
30471 * @override
30472 */
30473 this.className = "Enum";
30474
30475 /**
30476 * Runtime enum object.
30477 * @type {Object.<string,number>|null}
30478 * @expose
30479 */
30480 this.object = null;
30481 };
30482
30483 /**
30484 * Gets the string name of an enum value.
30485 * @param {!ProtoBuf.Builder.Enum} enm Runtime enum
30486 * @param {number} value Enum value
30487 * @returns {?string} Name or `null` if not present
30488 * @expose
30489 */
30490 Enum.getName = function(enm, value) {
30491 var keys = Object.keys(enm);
30492 for (var i=0, key; i<keys.length; ++i)
30493 if (enm[key = keys[i]] === value)
30494 return key;
30495 return null;
30496 };
30497
30498 /**
30499 * @alias ProtoBuf.Reflect.Enum.prototype
30500 * @inner
30501 */
30502 var EnumPrototype = Enum.prototype = Object.create(Namespace.prototype);
30503
30504 /**
30505 * Builds this enum and returns the runtime counterpart.
30506 * @param {boolean} rebuild Whether to rebuild or not, defaults to false
30507 * @returns {!Object.<string,number>}
30508 * @expose
30509 */
30510 EnumPrototype.build = function(rebuild) {
30511 if (this.object && !rebuild)
30512 return this.object;
30513 var enm = new ProtoBuf.Builder.Enum(),
30514 values = this.getChildren(Enum.Value);
30515 for (var i=0, k=values.length; i<k; ++i)
30516 enm[values[i]['name']] = values[i]['id'];
30517 if (Object.defineProperty)
30518 Object.defineProperty(enm, '$options', {
30519 "value": this.buildOpt(),
30520 "enumerable": false
30521 });
30522 return this.object = enm;
30523 };
30524
30525 /**
30526 * @alias ProtoBuf.Reflect.Enum
30527 * @expose
30528 */
30529 Reflect.Enum = Enum;
30530
30531 /**
30532 * Constructs a new Enum Value.
30533 * @exports ProtoBuf.Reflect.Enum.Value
30534 * @param {!ProtoBuf.Builder} builder Builder reference
30535 * @param {!ProtoBuf.Reflect.Enum} enm Enum reference
30536 * @param {string} name Field name
30537 * @param {number} id Unique field id
30538 * @constructor
30539 * @extends ProtoBuf.Reflect.T
30540 */
30541 var Value = function(builder, enm, name, id) {
30542 T.call(this, builder, enm, name);
30543
30544 /**
30545 * @override
30546 */
30547 this.className = "Enum.Value";
30548
30549 /**
30550 * Unique enum value id.
30551 * @type {number}
30552 * @expose
30553 */
30554 this.id = id;
30555 };
30556
30557 // Extends T
30558 Value.prototype = Object.create(T.prototype);
30559
30560 /**
30561 * @alias ProtoBuf.Reflect.Enum.Value
30562 * @expose
30563 */
30564 Reflect.Enum.Value = Value;
30565
30566 /**
30567 * An extension (field).
30568 * @exports ProtoBuf.Reflect.Extension
30569 * @constructor
30570 * @param {!ProtoBuf.Builder} builder Builder reference
30571 * @param {!ProtoBuf.Reflect.T} parent Parent object
30572 * @param {string} name Object name
30573 * @param {!ProtoBuf.Reflect.Message.Field} field Extension field
30574 */
30575 var Extension = function(builder, parent, name, field) {
30576 T.call(this, builder, parent, name);
30577
30578 /**
30579 * Extended message field.
30580 * @type {!ProtoBuf.Reflect.Message.Field}
30581 * @expose
30582 */
30583 this.field = field;
30584 };
30585
30586 // Extends T
30587 Extension.prototype = Object.create(T.prototype);
30588
30589 /**
30590 * @alias ProtoBuf.Reflect.Extension
30591 * @expose
30592 */
30593 Reflect.Extension = Extension;
30594
30595 /**
30596 * Constructs a new Service.
30597 * @exports ProtoBuf.Reflect.Service
30598 * @param {!ProtoBuf.Builder} builder Builder reference
30599 * @param {!ProtoBuf.Reflect.Namespace} root Root
30600 * @param {string} name Service name
30601 * @param {Object.<string,*>=} options Options
30602 * @constructor
30603 * @extends ProtoBuf.Reflect.Namespace
30604 */
30605 var Service = function(builder, root, name, options) {
30606 Namespace.call(this, builder, root, name, options);
30607
30608 /**
30609 * @override
30610 */
30611 this.className = "Service";
30612
30613 /**
30614 * Built runtime service class.
30615 * @type {?function(new:ProtoBuf.Builder.Service)}
30616 */
30617 this.clazz = null;
30618 };
30619
30620 /**
30621 * @alias ProtoBuf.Reflect.Service.prototype
30622 * @inner
30623 */
30624 var ServicePrototype = Service.prototype = Object.create(Namespace.prototype);
30625
30626 /**
30627 * Builds the service and returns the runtime counterpart, which is a fully functional class.
30628 * @see ProtoBuf.Builder.Service
30629 * @param {boolean=} rebuild Whether to rebuild or not
30630 * @return {Function} Service class
30631 * @throws {Error} If the message cannot be built
30632 * @expose
30633 */
30634 ServicePrototype.build = function(rebuild) {
30635 if (this.clazz && !rebuild)
30636 return this.clazz;
30637
30638 // Create the runtime Service class in its own scope
30639 return this.clazz = (function(ProtoBuf, T) {
30640
30641 /**
30642 * Constructs a new runtime Service.
30643 * @name ProtoBuf.Builder.Service
30644 * @param {function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))=} rpcImpl RPC implementation receiving the method name and the message
30645 * @class Barebone of all runtime services.
30646 * @constructor
30647 * @throws {Error} If the service cannot be created
30648 */
30649 var Service = function(rpcImpl) {
30650 ProtoBuf.Builder.Service.call(this);
30651
30652 /**
30653 * Service implementation.
30654 * @name ProtoBuf.Builder.Service#rpcImpl
30655 * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))}
30656 * @expose
30657 */
30658 this.rpcImpl = rpcImpl || function(name, msg, callback) {
30659 // This is what a user has to implement: A function receiving the method name, the actual message to
30660 // send (type checked) and the callback that's either provided with the error as its first
30661 // argument or null and the actual response message.
30662 setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async!
30663 };
30664 };
30665
30666 /**
30667 * @alias ProtoBuf.Builder.Service.prototype
30668 * @inner
30669 */
30670 var ServicePrototype = Service.prototype = Object.create(ProtoBuf.Builder.Service.prototype);
30671
30672 /**
30673 * Asynchronously performs an RPC call using the given RPC implementation.
30674 * @name ProtoBuf.Builder.Service.[Method]
30675 * @function
30676 * @param {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} rpcImpl RPC implementation
30677 * @param {ProtoBuf.Builder.Message} req Request
30678 * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
30679 * the error if any and the response either as a pre-parsed message or as its raw bytes
30680 * @abstract
30681 */
30682
30683 /**
30684 * Asynchronously performs an RPC call using the instance's RPC implementation.
30685 * @name ProtoBuf.Builder.Service#[Method]
30686 * @function
30687 * @param {ProtoBuf.Builder.Message} req Request
30688 * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
30689 * the error if any and the response either as a pre-parsed message or as its raw bytes
30690 * @abstract
30691 */
30692
30693 var rpc = T.getChildren(ProtoBuf.Reflect.Service.RPCMethod);
30694 for (var i=0; i<rpc.length; i++) {
30695 (function(method) {
30696
30697 // service#Method(message, callback)
30698 ServicePrototype[method.name] = function(req, callback) {
30699 try {
30700 try {
30701 // If given as a buffer, decode the request. Will throw a TypeError if not a valid buffer.
30702 req = method.resolvedRequestType.clazz.decode(ByteBuffer.wrap(req));
30703 } catch (err) {
30704 if (!(err instanceof TypeError))
30705 throw err;
30706 }
30707 if (req === null || typeof req !== 'object')
30708 throw Error("Illegal arguments");
30709 if (!(req instanceof method.resolvedRequestType.clazz))
30710 req = new method.resolvedRequestType.clazz(req);
30711 this.rpcImpl(method.fqn(), req, function(err, res) { // Assumes that this is properly async
30712 if (err) {
30713 callback(err);
30714 return;
30715 }
30716 // Coalesce to empty string when service response has empty content
30717 if (res === null)
30718 res = ''
30719 try { res = method.resolvedResponseType.clazz.decode(res); } catch (notABuffer) {}
30720 if (!res || !(res instanceof method.resolvedResponseType.clazz)) {
30721 callback(Error("Illegal response type received in service method "+ T.name+"#"+method.name));
30722 return;
30723 }
30724 callback(null, res);
30725 });
30726 } catch (err) {
30727 setTimeout(callback.bind(this, err), 0);
30728 }
30729 };
30730
30731 // Service.Method(rpcImpl, message, callback)
30732 Service[method.name] = function(rpcImpl, req, callback) {
30733 new Service(rpcImpl)[method.name](req, callback);
30734 };
30735
30736 if (Object.defineProperty)
30737 Object.defineProperty(Service[method.name], "$options", { "value": method.buildOpt() }),
30738 Object.defineProperty(ServicePrototype[method.name], "$options", { "value": Service[method.name]["$options"] });
30739 })(rpc[i]);
30740 }
30741
30742 // Properties
30743
30744 /**
30745 * Service options.
30746 * @name ProtoBuf.Builder.Service.$options
30747 * @type {Object.<string,*>}
30748 * @expose
30749 */
30750 var $optionsS; // cc needs this
30751
30752 /**
30753 * Service options.
30754 * @name ProtoBuf.Builder.Service#$options
30755 * @type {Object.<string,*>}
30756 * @expose
30757 */
30758 var $options;
30759
30760 /**
30761 * Reflection type.
30762 * @name ProtoBuf.Builder.Service.$type
30763 * @type {!ProtoBuf.Reflect.Service}
30764 * @expose
30765 */
30766 var $typeS;
30767
30768 /**
30769 * Reflection type.
30770 * @name ProtoBuf.Builder.Service#$type
30771 * @type {!ProtoBuf.Reflect.Service}
30772 * @expose
30773 */
30774 var $type;
30775
30776 if (Object.defineProperty)
30777 Object.defineProperty(Service, "$options", { "value": T.buildOpt() }),
30778 Object.defineProperty(ServicePrototype, "$options", { "value": Service["$options"] }),
30779 Object.defineProperty(Service, "$type", { "value": T }),
30780 Object.defineProperty(ServicePrototype, "$type", { "value": T });
30781
30782 return Service;
30783
30784 })(ProtoBuf, this);
30785 };
30786
30787 /**
30788 * @alias ProtoBuf.Reflect.Service
30789 * @expose
30790 */
30791 Reflect.Service = Service;
30792
30793 /**
30794 * Abstract service method.
30795 * @exports ProtoBuf.Reflect.Service.Method
30796 * @param {!ProtoBuf.Builder} builder Builder reference
30797 * @param {!ProtoBuf.Reflect.Service} svc Service
30798 * @param {string} name Method name
30799 * @param {Object.<string,*>=} options Options
30800 * @constructor
30801 * @extends ProtoBuf.Reflect.T
30802 */
30803 var Method = function(builder, svc, name, options) {
30804 T.call(this, builder, svc, name);
30805
30806 /**
30807 * @override
30808 */
30809 this.className = "Service.Method";
30810
30811 /**
30812 * Options.
30813 * @type {Object.<string, *>}
30814 * @expose
30815 */
30816 this.options = options || {};
30817 };
30818
30819 /**
30820 * @alias ProtoBuf.Reflect.Service.Method.prototype
30821 * @inner
30822 */
30823 var MethodPrototype = Method.prototype = Object.create(T.prototype);
30824
30825 /**
30826 * Builds the method's '$options' property.
30827 * @name ProtoBuf.Reflect.Service.Method#buildOpt
30828 * @function
30829 * @return {Object.<string,*>}
30830 */
30831 MethodPrototype.buildOpt = NamespacePrototype.buildOpt;
30832
30833 /**
30834 * @alias ProtoBuf.Reflect.Service.Method
30835 * @expose
30836 */
30837 Reflect.Service.Method = Method;
30838
30839 /**
30840 * RPC service method.
30841 * @exports ProtoBuf.Reflect.Service.RPCMethod
30842 * @param {!ProtoBuf.Builder} builder Builder reference
30843 * @param {!ProtoBuf.Reflect.Service} svc Service
30844 * @param {string} name Method name
30845 * @param {string} request Request message name
30846 * @param {string} response Response message name
30847 * @param {boolean} request_stream Whether requests are streamed
30848 * @param {boolean} response_stream Whether responses are streamed
30849 * @param {Object.<string,*>=} options Options
30850 * @constructor
30851 * @extends ProtoBuf.Reflect.Service.Method
30852 */
30853 var RPCMethod = function(builder, svc, name, request, response, request_stream, response_stream, options) {
30854 Method.call(this, builder, svc, name, options);
30855
30856 /**
30857 * @override
30858 */
30859 this.className = "Service.RPCMethod";
30860
30861 /**
30862 * Request message name.
30863 * @type {string}
30864 * @expose
30865 */
30866 this.requestName = request;
30867
30868 /**
30869 * Response message name.
30870 * @type {string}
30871 * @expose
30872 */
30873 this.responseName = response;
30874
30875 /**
30876 * Whether requests are streamed
30877 * @type {bool}
30878 * @expose
30879 */
30880 this.requestStream = request_stream;
30881
30882 /**
30883 * Whether responses are streamed
30884 * @type {bool}
30885 * @expose
30886 */
30887 this.responseStream = response_stream;
30888
30889 /**
30890 * Resolved request message type.
30891 * @type {ProtoBuf.Reflect.Message}
30892 * @expose
30893 */
30894 this.resolvedRequestType = null;
30895
30896 /**
30897 * Resolved response message type.
30898 * @type {ProtoBuf.Reflect.Message}
30899 * @expose
30900 */
30901 this.resolvedResponseType = null;
30902 };
30903
30904 // Extends Method
30905 RPCMethod.prototype = Object.create(Method.prototype);
30906
30907 /**
30908 * @alias ProtoBuf.Reflect.Service.RPCMethod
30909 * @expose
30910 */
30911 Reflect.Service.RPCMethod = RPCMethod;
30912
30913 return Reflect;
30914
30915 })(ProtoBuf);
30916
30917 /**
30918 * @alias ProtoBuf.Builder
30919 * @expose
30920 */
30921 ProtoBuf.Builder = (function(ProtoBuf, Lang, Reflect) {
30922 "use strict";
30923
30924 /**
30925 * Constructs a new Builder.
30926 * @exports ProtoBuf.Builder
30927 * @class Provides the functionality to build protocol messages.
30928 * @param {Object.<string,*>=} options Options
30929 * @constructor
30930 */
30931 var Builder = function(options) {
30932
30933 /**
30934 * Namespace.
30935 * @type {ProtoBuf.Reflect.Namespace}
30936 * @expose
30937 */
30938 this.ns = new Reflect.Namespace(this, null, ""); // Global namespace
30939
30940 /**
30941 * Namespace pointer.
30942 * @type {ProtoBuf.Reflect.T}
30943 * @expose
30944 */
30945 this.ptr = this.ns;
30946
30947 /**
30948 * Resolved flag.
30949 * @type {boolean}
30950 * @expose
30951 */
30952 this.resolved = false;
30953
30954 /**
30955 * The current building result.
30956 * @type {Object.<string,ProtoBuf.Builder.Message|Object>|null}
30957 * @expose
30958 */
30959 this.result = null;
30960
30961 /**
30962 * Imported files.
30963 * @type {Array.<string>}
30964 * @expose
30965 */
30966 this.files = {};
30967
30968 /**
30969 * Import root override.
30970 * @type {?string}
30971 * @expose
30972 */
30973 this.importRoot = null;
30974
30975 /**
30976 * Options.
30977 * @type {!Object.<string, *>}
30978 * @expose
30979 */
30980 this.options = options || {};
30981 };
30982
30983 /**
30984 * @alias ProtoBuf.Builder.prototype
30985 * @inner
30986 */
30987 var BuilderPrototype = Builder.prototype;
30988
30989 // ----- Definition tests -----
30990
30991 /**
30992 * Tests if a definition most likely describes a message.
30993 * @param {!Object} def
30994 * @returns {boolean}
30995 * @expose
30996 */
30997 Builder.isMessage = function(def) {
30998 // Messages require a string name
30999 if (typeof def["name"] !== 'string')
31000 return false;
31001 // Messages do not contain values (enum) or rpc methods (service)
31002 if (typeof def["values"] !== 'undefined' || typeof def["rpc"] !== 'undefined')
31003 return false;
31004 return true;
31005 };
31006
31007 /**
31008 * Tests if a definition most likely describes a message field.
31009 * @param {!Object} def
31010 * @returns {boolean}
31011 * @expose
31012 */
31013 Builder.isMessageField = function(def) {
31014 // Message fields require a string rule, name and type and an id
31015 if (typeof def["rule"] !== 'string' || typeof def["name"] !== 'string' || typeof def["type"] !== 'string' || typeof def["id"] === 'undefined')
31016 return false;
31017 return true;
31018 };
31019
31020 /**
31021 * Tests if a definition most likely describes an enum.
31022 * @param {!Object} def
31023 * @returns {boolean}
31024 * @expose
31025 */
31026 Builder.isEnum = function(def) {
31027 // Enums require a string name
31028 if (typeof def["name"] !== 'string')
31029 return false;
31030 // Enums require at least one value
31031 if (typeof def["values"] === 'undefined' || !Array.isArray(def["values"]) || def["values"].length === 0)
31032 return false;
31033 return true;
31034 };
31035
31036 /**
31037 * Tests if a definition most likely describes a service.
31038 * @param {!Object} def
31039 * @returns {boolean}
31040 * @expose
31041 */
31042 Builder.isService = function(def) {
31043 // Services require a string name and an rpc object
31044 if (typeof def["name"] !== 'string' || typeof def["rpc"] !== 'object' || !def["rpc"])
31045 return false;
31046 return true;
31047 };
31048
31049 /**
31050 * Tests if a definition most likely describes an extended message
31051 * @param {!Object} def
31052 * @returns {boolean}
31053 * @expose
31054 */
31055 Builder.isExtend = function(def) {
31056 // Extends rquire a string ref
31057 if (typeof def["ref"] !== 'string')
31058 return false;
31059 return true;
31060 };
31061
31062 // ----- Building -----
31063
31064 /**
31065 * Resets the pointer to the root namespace.
31066 * @returns {!ProtoBuf.Builder} this
31067 * @expose
31068 */
31069 BuilderPrototype.reset = function() {
31070 this.ptr = this.ns;
31071 return this;
31072 };
31073
31074 /**
31075 * Defines a namespace on top of the current pointer position and places the pointer on it.
31076 * @param {string} namespace
31077 * @return {!ProtoBuf.Builder} this
31078 * @expose
31079 */
31080 BuilderPrototype.define = function(namespace) {
31081 if (typeof namespace !== 'string' || !Lang.TYPEREF.test(namespace))
31082 throw Error("illegal namespace: "+namespace);
31083 namespace.split(".").forEach(function(part) {
31084 var ns = this.ptr.getChild(part);
31085 if (ns === null) // Keep existing
31086 this.ptr.addChild(ns = new Reflect.Namespace(this, this.ptr, part));
31087 this.ptr = ns;
31088 }, this);
31089 return this;
31090 };
31091
31092 /**
31093 * Creates the specified definitions at the current pointer position.
31094 * @param {!Array.<!Object>} defs Messages, enums or services to create
31095 * @returns {!ProtoBuf.Builder} this
31096 * @throws {Error} If a message definition is invalid
31097 * @expose
31098 */
31099 BuilderPrototype.create = function(defs) {
31100 if (!defs)
31101 return this; // Nothing to create
31102 if (!Array.isArray(defs))
31103 defs = [defs];
31104 else {
31105 if (defs.length === 0)
31106 return this;
31107 defs = defs.slice();
31108 }
31109
31110 // It's quite hard to keep track of scopes and memory here, so let's do this iteratively.
31111 var stack = [defs];
31112 while (stack.length > 0) {
31113 defs = stack.pop();
31114
31115 if (!Array.isArray(defs)) // Stack always contains entire namespaces
31116 throw Error("not a valid namespace: "+JSON.stringify(defs));
31117
31118 while (defs.length > 0) {
31119 var def = defs.shift(); // Namespaces always contain an array of messages, enums and services
31120
31121 if (Builder.isMessage(def)) {
31122 var obj = new Reflect.Message(this, this.ptr, def["name"], def["options"], def["isGroup"], def["syntax"]);
31123
31124 // Create OneOfs
31125 var oneofs = {};
31126 if (def["oneofs"])
31127 Object.keys(def["oneofs"]).forEach(function(name) {
31128 obj.addChild(oneofs[name] = new Reflect.Message.OneOf(this, obj, name));
31129 }, this);
31130
31131 // Create fields
31132 if (def["fields"])
31133 def["fields"].forEach(function(fld) {
31134 if (obj.getChild(fld["id"]|0) !== null)
31135 throw Error("duplicate or invalid field id in "+obj.name+": "+fld['id']);
31136 if (fld["options"] && typeof fld["options"] !== 'object')
31137 throw Error("illegal field options in "+obj.name+"#"+fld["name"]);
31138 var oneof = null;
31139 if (typeof fld["oneof"] === 'string' && !(oneof = oneofs[fld["oneof"]]))
31140 throw Error("illegal oneof in "+obj.name+"#"+fld["name"]+": "+fld["oneof"]);
31141 fld = new Reflect.Message.Field(this, obj, fld["rule"], fld["keytype"], fld["type"], fld["name"], fld["id"], fld["options"], oneof, def["syntax"]);
31142 if (oneof)
31143 oneof.fields.push(fld);
31144 obj.addChild(fld);
31145 }, this);
31146
31147 // Push children to stack
31148 var subObj = [];
31149 if (def["enums"])
31150 def["enums"].forEach(function(enm) {
31151 subObj.push(enm);
31152 });
31153 if (def["messages"])
31154 def["messages"].forEach(function(msg) {
31155 subObj.push(msg);
31156 });
31157 if (def["services"])
31158 def["services"].forEach(function(svc) {
31159 subObj.push(svc);
31160 });
31161
31162 // Set extension ranges
31163 if (def["extensions"]) {
31164 if (typeof def["extensions"][0] === 'number') // pre 5.0.1
31165 obj.extensions = [ def["extensions"] ];
31166 else
31167 obj.extensions = def["extensions"];
31168 }
31169
31170 // Create on top of current namespace
31171 this.ptr.addChild(obj);
31172 if (subObj.length > 0) {
31173 stack.push(defs); // Push the current level back
31174 defs = subObj; // Continue processing sub level
31175 subObj = null;
31176 this.ptr = obj; // And move the pointer to this namespace
31177 obj = null;
31178 continue;
31179 }
31180 subObj = null;
31181
31182 } else if (Builder.isEnum(def)) {
31183
31184 obj = new Reflect.Enum(this, this.ptr, def["name"], def["options"], def["syntax"]);
31185 def["values"].forEach(function(val) {
31186 obj.addChild(new Reflect.Enum.Value(this, obj, val["name"], val["id"]));
31187 }, this);
31188 this.ptr.addChild(obj);
31189
31190 } else if (Builder.isService(def)) {
31191
31192 obj = new Reflect.Service(this, this.ptr, def["name"], def["options"]);
31193 Object.keys(def["rpc"]).forEach(function(name) {
31194 var mtd = def["rpc"][name];
31195 obj.addChild(new Reflect.Service.RPCMethod(this, obj, name, mtd["request"], mtd["response"], !!mtd["request_stream"], !!mtd["response_stream"], mtd["options"]));
31196 }, this);
31197 this.ptr.addChild(obj);
31198
31199 } else if (Builder.isExtend(def)) {
31200
31201 obj = this.ptr.resolve(def["ref"], true);
31202 if (obj) {
31203 def["fields"].forEach(function(fld) {
31204 if (obj.getChild(fld['id']|0) !== null)
31205 throw Error("duplicate extended field id in "+obj.name+": "+fld['id']);
31206 // Check if field id is allowed to be extended
31207 if (obj.extensions) {
31208 var valid = false;
31209 obj.extensions.forEach(function(range) {
31210 if (fld["id"] >= range[0] && fld["id"] <= range[1])
31211 valid = true;
31212 });
31213 if (!valid)
31214 throw Error("illegal extended field id in "+obj.name+": "+fld['id']+" (not within valid ranges)");
31215 }
31216 // Convert extension field names to camel case notation if the override is set
31217 var name = fld["name"];
31218 if (this.options['convertFieldsToCamelCase'])
31219 name = ProtoBuf.Util.toCamelCase(name);
31220 // see #161: Extensions use their fully qualified name as their runtime key and...
31221 var field = new Reflect.Message.ExtensionField(this, obj, fld["rule"], fld["type"], this.ptr.fqn()+'.'+name, fld["id"], fld["options"]);
31222 // ...are added on top of the current namespace as an extension which is used for
31223 // resolving their type later on (the extension always keeps the original name to
31224 // prevent naming collisions)
31225 var ext = new Reflect.Extension(this, this.ptr, fld["name"], field);
31226 field.extension = ext;
31227 this.ptr.addChild(ext);
31228 obj.addChild(field);
31229 }, this);
31230
31231 } else if (!/\.?google\.protobuf\./.test(def["ref"])) // Silently skip internal extensions
31232 throw Error("extended message "+def["ref"]+" is not defined");
31233
31234 } else
31235 throw Error("not a valid definition: "+JSON.stringify(def));
31236
31237 def = null;
31238 obj = null;
31239 }
31240 // Break goes here
31241 defs = null;
31242 this.ptr = this.ptr.parent; // Namespace done, continue at parent
31243 }
31244 this.resolved = false; // Require re-resolve
31245 this.result = null; // Require re-build
31246 return this;
31247 };
31248
31249 /**
31250 * Propagates syntax to all children.
31251 * @param {!Object} parent
31252 * @inner
31253 */
31254 function propagateSyntax(parent) {
31255 if (parent['messages']) {
31256 parent['messages'].forEach(function(child) {
31257 child["syntax"] = parent["syntax"];
31258 propagateSyntax(child);
31259 });
31260 }
31261 if (parent['enums']) {
31262 parent['enums'].forEach(function(child) {
31263 child["syntax"] = parent["syntax"];
31264 });
31265 }
31266 }
31267
31268 /**
31269 * Imports another definition into this builder.
31270 * @param {Object.<string,*>} json Parsed import
31271 * @param {(string|{root: string, file: string})=} filename Imported file name
31272 * @returns {!ProtoBuf.Builder} this
31273 * @throws {Error} If the definition or file cannot be imported
31274 * @expose
31275 */
31276 BuilderPrototype["import"] = function(json, filename) {
31277 var delim = '/';
31278
31279 // Make sure to skip duplicate imports
31280
31281 if (typeof filename === 'string') {
31282
31283 if (ProtoBuf.Util.IS_NODE)
31284 filename = __webpack_require__(77)['resolve'](filename);
31285 if (this.files[filename] === true)
31286 return this.reset();
31287 this.files[filename] = true;
31288
31289 } else if (typeof filename === 'object') { // Object with root, file.
31290
31291 var root = filename.root;
31292 if (ProtoBuf.Util.IS_NODE)
31293 root = __webpack_require__(77)['resolve'](root);
31294 if (root.indexOf("\\") >= 0 || filename.file.indexOf("\\") >= 0)
31295 delim = '\\';
31296 var fname;
31297 if (ProtoBuf.Util.IS_NODE)
31298 fname = __webpack_require__(77)['join'](root, filename.file);
31299 else
31300 fname = root + delim + filename.file;
31301 if (this.files[fname] === true)
31302 return this.reset();
31303 this.files[fname] = true;
31304 }
31305
31306 // Import imports
31307
31308 if (json['imports'] && json['imports'].length > 0) {
31309 var importRoot,
31310 resetRoot = false;
31311
31312 if (typeof filename === 'object') { // If an import root is specified, override
31313
31314 this.importRoot = filename["root"]; resetRoot = true; // ... and reset afterwards
31315 importRoot = this.importRoot;
31316 filename = filename["file"];
31317 if (importRoot.indexOf("\\") >= 0 || filename.indexOf("\\") >= 0)
31318 delim = '\\';
31319
31320 } else if (typeof filename === 'string') {
31321
31322 if (this.importRoot) // If import root is overridden, use it
31323 importRoot = this.importRoot;
31324 else { // Otherwise compute from filename
31325 if (filename.indexOf("/") >= 0) { // Unix
31326 importRoot = filename.replace(/\/[^\/]*$/, "");
31327 if (/* /file.proto */ importRoot === "")
31328 importRoot = "/";
31329 } else if (filename.indexOf("\\") >= 0) { // Windows
31330 importRoot = filename.replace(/\\[^\\]*$/, "");
31331 delim = '\\';
31332 } else
31333 importRoot = ".";
31334 }
31335
31336 } else
31337 importRoot = null;
31338
31339 for (var i=0; i<json['imports'].length; i++) {
31340 if (typeof json['imports'][i] === 'string') { // Import file
31341 if (!importRoot)
31342 throw Error("cannot determine import root");
31343 var importFilename = json['imports'][i];
31344 if (importFilename === "google/protobuf/descriptor.proto")
31345 continue; // Not needed and therefore not used
31346 if (ProtoBuf.Util.IS_NODE)
31347 importFilename = __webpack_require__(77)['join'](importRoot, importFilename);
31348 else
31349 importFilename = importRoot + delim + importFilename;
31350 if (this.files[importFilename] === true)
31351 continue; // Already imported
31352 if (/\.proto$/i.test(importFilename) && !ProtoBuf.DotProto) // If this is a light build
31353 importFilename = importFilename.replace(/\.proto$/, ".json"); // always load the JSON file
31354 var contents = ProtoBuf.Util.fetch(importFilename);
31355 if (contents === null)
31356 throw Error("failed to import '"+importFilename+"' in '"+filename+"': file not found");
31357 if (/\.json$/i.test(importFilename)) // Always possible
31358 this["import"](JSON.parse(contents+""), importFilename); // May throw
31359 else
31360 this["import"](ProtoBuf.DotProto.Parser.parse(contents), importFilename); // May throw
31361 } else // Import structure
31362 if (!filename)
31363 this["import"](json['imports'][i]);
31364 else if (/\.(\w+)$/.test(filename)) // With extension: Append _importN to the name portion to make it unique
31365 this["import"](json['imports'][i], filename.replace(/^(.+)\.(\w+)$/, function($0, $1, $2) { return $1+"_import"+i+"."+$2; }));
31366 else // Without extension: Append _importN to make it unique
31367 this["import"](json['imports'][i], filename+"_import"+i);
31368 }
31369 if (resetRoot) // Reset import root override when all imports are done
31370 this.importRoot = null;
31371 }
31372
31373 // Import structures
31374
31375 if (json['package'])
31376 this.define(json['package']);
31377 if (json['syntax'])
31378 propagateSyntax(json);
31379 var base = this.ptr;
31380 if (json['options'])
31381 Object.keys(json['options']).forEach(function(key) {
31382 base.options[key] = json['options'][key];
31383 });
31384 if (json['messages'])
31385 this.create(json['messages']),
31386 this.ptr = base;
31387 if (json['enums'])
31388 this.create(json['enums']),
31389 this.ptr = base;
31390 if (json['services'])
31391 this.create(json['services']),
31392 this.ptr = base;
31393 if (json['extends'])
31394 this.create(json['extends']);
31395
31396 return this.reset();
31397 };
31398
31399 /**
31400 * Resolves all namespace objects.
31401 * @throws {Error} If a type cannot be resolved
31402 * @returns {!ProtoBuf.Builder} this
31403 * @expose
31404 */
31405 BuilderPrototype.resolveAll = function() {
31406 // Resolve all reflected objects
31407 var res;
31408 if (this.ptr == null || typeof this.ptr.type === 'object')
31409 return this; // Done (already resolved)
31410
31411 if (this.ptr instanceof Reflect.Namespace) { // Resolve children
31412
31413 this.ptr.children.forEach(function(child) {
31414 this.ptr = child;
31415 this.resolveAll();
31416 }, this);
31417
31418 } else if (this.ptr instanceof Reflect.Message.Field) { // Resolve type
31419
31420 if (!Lang.TYPE.test(this.ptr.type)) {
31421 if (!Lang.TYPEREF.test(this.ptr.type))
31422 throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
31423 res = (this.ptr instanceof Reflect.Message.ExtensionField ? this.ptr.extension.parent : this.ptr.parent).resolve(this.ptr.type, true);
31424 if (!res)
31425 throw Error("unresolvable type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
31426 this.ptr.resolvedType = res;
31427 if (res instanceof Reflect.Enum) {
31428 this.ptr.type = ProtoBuf.TYPES["enum"];
31429 if (this.ptr.syntax === 'proto3' && res.syntax !== 'proto3')
31430 throw Error("proto3 message cannot reference proto2 enum");
31431 }
31432 else if (res instanceof Reflect.Message)
31433 this.ptr.type = res.isGroup ? ProtoBuf.TYPES["group"] : ProtoBuf.TYPES["message"];
31434 else
31435 throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
31436 } else
31437 this.ptr.type = ProtoBuf.TYPES[this.ptr.type];
31438
31439 // If it's a map field, also resolve the key type. The key type can be only a numeric, string, or bool type
31440 // (i.e., no enums or messages), so we don't need to resolve against the current namespace.
31441 if (this.ptr.map) {
31442 if (!Lang.TYPE.test(this.ptr.keyType))
31443 throw Error("illegal key type for map field in "+this.ptr.toString(true)+": "+this.ptr.keyType);
31444 this.ptr.keyType = ProtoBuf.TYPES[this.ptr.keyType];
31445 }
31446
31447 // If it's a repeated and packable field then proto3 mandates it should be packed by
31448 // default
31449 if (
31450 this.ptr.syntax === 'proto3' &&
31451 this.ptr.repeated && this.ptr.options.packed === undefined &&
31452 ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.ptr.type.wireType) !== -1
31453 ) {
31454 this.ptr.options.packed = true;
31455 }
31456
31457 } else if (this.ptr instanceof ProtoBuf.Reflect.Service.Method) {
31458
31459 if (this.ptr instanceof ProtoBuf.Reflect.Service.RPCMethod) {
31460 res = this.ptr.parent.resolve(this.ptr.requestName, true);
31461 if (!res || !(res instanceof ProtoBuf.Reflect.Message))
31462 throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.requestName);
31463 this.ptr.resolvedRequestType = res;
31464 res = this.ptr.parent.resolve(this.ptr.responseName, true);
31465 if (!res || !(res instanceof ProtoBuf.Reflect.Message))
31466 throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.responseName);
31467 this.ptr.resolvedResponseType = res;
31468 } else // Should not happen as nothing else is implemented
31469 throw Error("illegal service type in "+this.ptr.toString(true));
31470
31471 } else if (
31472 !(this.ptr instanceof ProtoBuf.Reflect.Message.OneOf) && // Not built
31473 !(this.ptr instanceof ProtoBuf.Reflect.Extension) && // Not built
31474 !(this.ptr instanceof ProtoBuf.Reflect.Enum.Value) // Built in enum
31475 )
31476 throw Error("illegal object in namespace: "+typeof(this.ptr)+": "+this.ptr);
31477
31478 return this.reset();
31479 };
31480
31481 /**
31482 * Builds the protocol. This will first try to resolve all definitions and, if this has been successful,
31483 * return the built package.
31484 * @param {(string|Array.<string>)=} path Specifies what to return. If omitted, the entire namespace will be returned.
31485 * @returns {!ProtoBuf.Builder.Message|!Object.<string,*>}
31486 * @throws {Error} If a type could not be resolved
31487 * @expose
31488 */
31489 BuilderPrototype.build = function(path) {
31490 this.reset();
31491 if (!this.resolved)
31492 this.resolveAll(),
31493 this.resolved = true,
31494 this.result = null; // Require re-build
31495 if (this.result === null) // (Re-)Build
31496 this.result = this.ns.build();
31497 if (!path)
31498 return this.result;
31499 var part = typeof path === 'string' ? path.split(".") : path,
31500 ptr = this.result; // Build namespace pointer (no hasChild etc.)
31501 for (var i=0; i<part.length; i++)
31502 if (ptr[part[i]])
31503 ptr = ptr[part[i]];
31504 else {
31505 ptr = null;
31506 break;
31507 }
31508 return ptr;
31509 };
31510
31511 /**
31512 * Similar to {@link ProtoBuf.Builder#build}, but looks up the internal reflection descriptor.
31513 * @param {string=} path Specifies what to return. If omitted, the entire namespace wiil be returned.
31514 * @param {boolean=} excludeNonNamespace Excludes non-namespace types like fields, defaults to `false`
31515 * @returns {?ProtoBuf.Reflect.T} Reflection descriptor or `null` if not found
31516 */
31517 BuilderPrototype.lookup = function(path, excludeNonNamespace) {
31518 return path ? this.ns.resolve(path, excludeNonNamespace) : this.ns;
31519 };
31520
31521 /**
31522 * Returns a string representation of this object.
31523 * @return {string} String representation as of "Builder"
31524 * @expose
31525 */
31526 BuilderPrototype.toString = function() {
31527 return "Builder";
31528 };
31529
31530 // ----- Base classes -----
31531 // Exist for the sole purpose of being able to "... instanceof ProtoBuf.Builder.Message" etc.
31532
31533 /**
31534 * @alias ProtoBuf.Builder.Message
31535 */
31536 Builder.Message = function() {};
31537
31538 /**
31539 * @alias ProtoBuf.Builder.Enum
31540 */
31541 Builder.Enum = function() {};
31542
31543 /**
31544 * @alias ProtoBuf.Builder.Message
31545 */
31546 Builder.Service = function() {};
31547
31548 return Builder;
31549
31550 })(ProtoBuf, ProtoBuf.Lang, ProtoBuf.Reflect);
31551
31552 /**
31553 * @alias ProtoBuf.Map
31554 * @expose
31555 */
31556 ProtoBuf.Map = (function(ProtoBuf, Reflect) {
31557 "use strict";
31558
31559 /**
31560 * Constructs a new Map. A Map is a container that is used to implement map
31561 * fields on message objects. It closely follows the ES6 Map API; however,
31562 * it is distinct because we do not want to depend on external polyfills or
31563 * on ES6 itself.
31564 *
31565 * @exports ProtoBuf.Map
31566 * @param {!ProtoBuf.Reflect.Field} field Map field
31567 * @param {Object.<string,*>=} contents Initial contents
31568 * @constructor
31569 */
31570 var Map = function(field, contents) {
31571 if (!field.map)
31572 throw Error("field is not a map");
31573
31574 /**
31575 * The field corresponding to this map.
31576 * @type {!ProtoBuf.Reflect.Field}
31577 */
31578 this.field = field;
31579
31580 /**
31581 * Element instance corresponding to key type.
31582 * @type {!ProtoBuf.Reflect.Element}
31583 */
31584 this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax);
31585
31586 /**
31587 * Element instance corresponding to value type.
31588 * @type {!ProtoBuf.Reflect.Element}
31589 */
31590 this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax);
31591
31592 /**
31593 * Internal map: stores mapping of (string form of key) -> (key, value)
31594 * pair.
31595 *
31596 * We provide map semantics for arbitrary key types, but we build on top
31597 * of an Object, which has only string keys. In order to avoid the need
31598 * to convert a string key back to its native type in many situations,
31599 * we store the native key value alongside the value. Thus, we only need
31600 * a one-way mapping from a key type to its string form that guarantees
31601 * uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1
31602 * === K2).
31603 *
31604 * @type {!Object<string, {key: *, value: *}>}
31605 */
31606 this.map = {};
31607
31608 /**
31609 * Returns the number of elements in the map.
31610 */
31611 Object.defineProperty(this, "size", {
31612 get: function() { return Object.keys(this.map).length; }
31613 });
31614
31615 // Fill initial contents from a raw object.
31616 if (contents) {
31617 var keys = Object.keys(contents);
31618 for (var i = 0; i < keys.length; i++) {
31619 var key = this.keyElem.valueFromString(keys[i]);
31620 var val = this.valueElem.verifyValue(contents[keys[i]]);
31621 this.map[this.keyElem.valueToString(key)] =
31622 { key: key, value: val };
31623 }
31624 }
31625 };
31626
31627 var MapPrototype = Map.prototype;
31628
31629 /**
31630 * Helper: return an iterator over an array.
31631 * @param {!Array<*>} arr the array
31632 * @returns {!Object} an iterator
31633 * @inner
31634 */
31635 function arrayIterator(arr) {
31636 var idx = 0;
31637 return {
31638 next: function() {
31639 if (idx < arr.length)
31640 return { done: false, value: arr[idx++] };
31641 return { done: true };
31642 }
31643 }
31644 }
31645
31646 /**
31647 * Clears the map.
31648 */
31649 MapPrototype.clear = function() {
31650 this.map = {};
31651 };
31652
31653 /**
31654 * Deletes a particular key from the map.
31655 * @returns {boolean} Whether any entry with this key was deleted.
31656 */
31657 MapPrototype["delete"] = function(key) {
31658 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
31659 var hadKey = keyValue in this.map;
31660 delete this.map[keyValue];
31661 return hadKey;
31662 };
31663
31664 /**
31665 * Returns an iterator over [key, value] pairs in the map.
31666 * @returns {Object} The iterator
31667 */
31668 MapPrototype.entries = function() {
31669 var entries = [];
31670 var strKeys = Object.keys(this.map);
31671 for (var i = 0, entry; i < strKeys.length; i++)
31672 entries.push([(entry=this.map[strKeys[i]]).key, entry.value]);
31673 return arrayIterator(entries);
31674 };
31675
31676 /**
31677 * Returns an iterator over keys in the map.
31678 * @returns {Object} The iterator
31679 */
31680 MapPrototype.keys = function() {
31681 var keys = [];
31682 var strKeys = Object.keys(this.map);
31683 for (var i = 0; i < strKeys.length; i++)
31684 keys.push(this.map[strKeys[i]].key);
31685 return arrayIterator(keys);
31686 };
31687
31688 /**
31689 * Returns an iterator over values in the map.
31690 * @returns {!Object} The iterator
31691 */
31692 MapPrototype.values = function() {
31693 var values = [];
31694 var strKeys = Object.keys(this.map);
31695 for (var i = 0; i < strKeys.length; i++)
31696 values.push(this.map[strKeys[i]].value);
31697 return arrayIterator(values);
31698 };
31699
31700 /**
31701 * Iterates over entries in the map, calling a function on each.
31702 * @param {function(this:*, *, *, *)} cb The callback to invoke with value, key, and map arguments.
31703 * @param {Object=} thisArg The `this` value for the callback
31704 */
31705 MapPrototype.forEach = function(cb, thisArg) {
31706 var strKeys = Object.keys(this.map);
31707 for (var i = 0, entry; i < strKeys.length; i++)
31708 cb.call(thisArg, (entry=this.map[strKeys[i]]).value, entry.key, this);
31709 };
31710
31711 /**
31712 * Sets a key in the map to the given value.
31713 * @param {*} key The key
31714 * @param {*} value The value
31715 * @returns {!ProtoBuf.Map} The map instance
31716 */
31717 MapPrototype.set = function(key, value) {
31718 var keyValue = this.keyElem.verifyValue(key);
31719 var valValue = this.valueElem.verifyValue(value);
31720 this.map[this.keyElem.valueToString(keyValue)] =
31721 { key: keyValue, value: valValue };
31722 return this;
31723 };
31724
31725 /**
31726 * Gets the value corresponding to a key in the map.
31727 * @param {*} key The key
31728 * @returns {*|undefined} The value, or `undefined` if key not present
31729 */
31730 MapPrototype.get = function(key) {
31731 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
31732 if (!(keyValue in this.map))
31733 return undefined;
31734 return this.map[keyValue].value;
31735 };
31736
31737 /**
31738 * Determines whether the given key is present in the map.
31739 * @param {*} key The key
31740 * @returns {boolean} `true` if the key is present
31741 */
31742 MapPrototype.has = function(key) {
31743 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
31744 return (keyValue in this.map);
31745 };
31746
31747 return Map;
31748 })(ProtoBuf, ProtoBuf.Reflect);
31749
31750
31751 /**
31752 * Constructs a new empty Builder.
31753 * @param {Object.<string,*>=} options Builder options, defaults to global options set on ProtoBuf
31754 * @return {!ProtoBuf.Builder} Builder
31755 * @expose
31756 */
31757 ProtoBuf.newBuilder = function(options) {
31758 options = options || {};
31759 if (typeof options['convertFieldsToCamelCase'] === 'undefined')
31760 options['convertFieldsToCamelCase'] = ProtoBuf.convertFieldsToCamelCase;
31761 if (typeof options['populateAccessors'] === 'undefined')
31762 options['populateAccessors'] = ProtoBuf.populateAccessors;
31763 return new ProtoBuf.Builder(options);
31764 };
31765
31766 /**
31767 * Loads a .json definition and returns the Builder.
31768 * @param {!*|string} json JSON definition
31769 * @param {(ProtoBuf.Builder|string|{root: string, file: string})=} builder Builder to append to. Will create a new one if omitted.
31770 * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
31771 * @return {ProtoBuf.Builder} Builder to create new messages
31772 * @throws {Error} If the definition cannot be parsed or built
31773 * @expose
31774 */
31775 ProtoBuf.loadJson = function(json, builder, filename) {
31776 if (typeof builder === 'string' || (builder && typeof builder["file"] === 'string' && typeof builder["root"] === 'string'))
31777 filename = builder,
31778 builder = null;
31779 if (!builder || typeof builder !== 'object')
31780 builder = ProtoBuf.newBuilder();
31781 if (typeof json === 'string')
31782 json = JSON.parse(json);
31783 builder["import"](json, filename);
31784 builder.resolveAll();
31785 return builder;
31786 };
31787
31788 /**
31789 * Loads a .json file and returns the Builder.
31790 * @param {string|!{root: string, file: string}} filename Path to json file or an object specifying 'file' with
31791 * an overridden 'root' path for all imported files.
31792 * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
31793 * the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
31794 * file will be read synchronously and this function will return the Builder.
31795 * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
31796 * @return {?ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
31797 * request has failed), else undefined
31798 * @expose
31799 */
31800 ProtoBuf.loadJsonFile = function(filename, callback, builder) {
31801 if (callback && typeof callback === 'object')
31802 builder = callback,
31803 callback = null;
31804 else if (!callback || typeof callback !== 'function')
31805 callback = null;
31806 if (callback)
31807 return ProtoBuf.Util.fetch(typeof filename === 'string' ? filename : filename["root"]+"/"+filename["file"], function(contents) {
31808 if (contents === null) {
31809 callback(Error("Failed to fetch file"));
31810 return;
31811 }
31812 try {
31813 callback(null, ProtoBuf.loadJson(JSON.parse(contents), builder, filename));
31814 } catch (e) {
31815 callback(e);
31816 }
31817 });
31818 var contents = ProtoBuf.Util.fetch(typeof filename === 'object' ? filename["root"]+"/"+filename["file"] : filename);
31819 return contents === null ? null : ProtoBuf.loadJson(JSON.parse(contents), builder, filename);
31820 };
31821
31822 return ProtoBuf;
31823});
31824
31825
31826/***/ }),
31827/* 410 */
31828/***/ (function(module, exports, __webpack_require__) {
31829
31830var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*
31831 Copyright 2013-2014 Daniel Wirtz <dcode@dcode.io>
31832
31833 Licensed under the Apache License, Version 2.0 (the "License");
31834 you may not use this file except in compliance with the License.
31835 You may obtain a copy of the License at
31836
31837 http://www.apache.org/licenses/LICENSE-2.0
31838
31839 Unless required by applicable law or agreed to in writing, software
31840 distributed under the License is distributed on an "AS IS" BASIS,
31841 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31842 See the License for the specific language governing permissions and
31843 limitations under the License.
31844 */
31845
31846/**
31847 * @license bytebuffer.js (c) 2015 Daniel Wirtz <dcode@dcode.io>
31848 * Backing buffer: ArrayBuffer, Accessor: Uint8Array
31849 * Released under the Apache License, Version 2.0
31850 * see: https://github.com/dcodeIO/bytebuffer.js for details
31851 */
31852(function(global, factory) {
31853
31854 /* AMD */ if (true)
31855 !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(411)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
31856 __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
31857 (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
31858 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
31859 /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
31860 module['exports'] = (function() {
31861 var Long; try { Long = require("long"); } catch (e) {}
31862 return factory(Long);
31863 })();
31864 /* Global */ else
31865 (global["dcodeIO"] = global["dcodeIO"] || {})["ByteBuffer"] = factory(global["dcodeIO"]["Long"]);
31866
31867})(this, function(Long) {
31868 "use strict";
31869
31870 /**
31871 * Constructs a new ByteBuffer.
31872 * @class The swiss army knife for binary data in JavaScript.
31873 * @exports ByteBuffer
31874 * @constructor
31875 * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
31876 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
31877 * {@link ByteBuffer.DEFAULT_ENDIAN}.
31878 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
31879 * {@link ByteBuffer.DEFAULT_NOASSERT}.
31880 * @expose
31881 */
31882 var ByteBuffer = function(capacity, littleEndian, noAssert) {
31883 if (typeof capacity === 'undefined')
31884 capacity = ByteBuffer.DEFAULT_CAPACITY;
31885 if (typeof littleEndian === 'undefined')
31886 littleEndian = ByteBuffer.DEFAULT_ENDIAN;
31887 if (typeof noAssert === 'undefined')
31888 noAssert = ByteBuffer.DEFAULT_NOASSERT;
31889 if (!noAssert) {
31890 capacity = capacity | 0;
31891 if (capacity < 0)
31892 throw RangeError("Illegal capacity");
31893 littleEndian = !!littleEndian;
31894 noAssert = !!noAssert;
31895 }
31896
31897 /**
31898 * Backing ArrayBuffer.
31899 * @type {!ArrayBuffer}
31900 * @expose
31901 */
31902 this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity);
31903
31904 /**
31905 * Uint8Array utilized to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`.
31906 * @type {?Uint8Array}
31907 * @expose
31908 */
31909 this.view = capacity === 0 ? null : new Uint8Array(this.buffer);
31910
31911 /**
31912 * Absolute read/write offset.
31913 * @type {number}
31914 * @expose
31915 * @see ByteBuffer#flip
31916 * @see ByteBuffer#clear
31917 */
31918 this.offset = 0;
31919
31920 /**
31921 * Marked offset.
31922 * @type {number}
31923 * @expose
31924 * @see ByteBuffer#mark
31925 * @see ByteBuffer#reset
31926 */
31927 this.markedOffset = -1;
31928
31929 /**
31930 * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation.
31931 * @type {number}
31932 * @expose
31933 * @see ByteBuffer#flip
31934 * @see ByteBuffer#clear
31935 */
31936 this.limit = capacity;
31937
31938 /**
31939 * Whether to use little endian byte order, defaults to `false` for big endian.
31940 * @type {boolean}
31941 * @expose
31942 */
31943 this.littleEndian = littleEndian;
31944
31945 /**
31946 * Whether to skip assertions of offsets and values, defaults to `false`.
31947 * @type {boolean}
31948 * @expose
31949 */
31950 this.noAssert = noAssert;
31951 };
31952
31953 /**
31954 * ByteBuffer version.
31955 * @type {string}
31956 * @const
31957 * @expose
31958 */
31959 ByteBuffer.VERSION = "5.0.1";
31960
31961 /**
31962 * Little endian constant that can be used instead of its boolean value. Evaluates to `true`.
31963 * @type {boolean}
31964 * @const
31965 * @expose
31966 */
31967 ByteBuffer.LITTLE_ENDIAN = true;
31968
31969 /**
31970 * Big endian constant that can be used instead of its boolean value. Evaluates to `false`.
31971 * @type {boolean}
31972 * @const
31973 * @expose
31974 */
31975 ByteBuffer.BIG_ENDIAN = false;
31976
31977 /**
31978 * Default initial capacity of `16`.
31979 * @type {number}
31980 * @expose
31981 */
31982 ByteBuffer.DEFAULT_CAPACITY = 16;
31983
31984 /**
31985 * Default endianess of `false` for big endian.
31986 * @type {boolean}
31987 * @expose
31988 */
31989 ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN;
31990
31991 /**
31992 * Default no assertions flag of `false`.
31993 * @type {boolean}
31994 * @expose
31995 */
31996 ByteBuffer.DEFAULT_NOASSERT = false;
31997
31998 /**
31999 * A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded
32000 * and int64 support is not available.
32001 * @type {?Long}
32002 * @const
32003 * @see https://github.com/dcodeIO/long.js
32004 * @expose
32005 */
32006 ByteBuffer.Long = Long || null;
32007
32008 /**
32009 * @alias ByteBuffer.prototype
32010 * @inner
32011 */
32012 var ByteBufferPrototype = ByteBuffer.prototype;
32013
32014 /**
32015 * An indicator used to reliably determine if an object is a ByteBuffer or not.
32016 * @type {boolean}
32017 * @const
32018 * @expose
32019 * @private
32020 */
32021 ByteBufferPrototype.__isByteBuffer__;
32022
32023 Object.defineProperty(ByteBufferPrototype, "__isByteBuffer__", {
32024 value: true,
32025 enumerable: false,
32026 configurable: false
32027 });
32028
32029 // helpers
32030
32031 /**
32032 * @type {!ArrayBuffer}
32033 * @inner
32034 */
32035 var EMPTY_BUFFER = new ArrayBuffer(0);
32036
32037 /**
32038 * String.fromCharCode reference for compile-time renaming.
32039 * @type {function(...number):string}
32040 * @inner
32041 */
32042 var stringFromCharCode = String.fromCharCode;
32043
32044 /**
32045 * Creates a source function for a string.
32046 * @param {string} s String to read from
32047 * @returns {function():number|null} Source function returning the next char code respectively `null` if there are
32048 * no more characters left.
32049 * @throws {TypeError} If the argument is invalid
32050 * @inner
32051 */
32052 function stringSource(s) {
32053 var i=0; return function() {
32054 return i < s.length ? s.charCodeAt(i++) : null;
32055 };
32056 }
32057
32058 /**
32059 * Creates a destination function for a string.
32060 * @returns {function(number=):undefined|string} Destination function successively called with the next char code.
32061 * Returns the final string when called without arguments.
32062 * @inner
32063 */
32064 function stringDestination() {
32065 var cs = [], ps = []; return function() {
32066 if (arguments.length === 0)
32067 return ps.join('')+stringFromCharCode.apply(String, cs);
32068 if (cs.length + arguments.length > 1024)
32069 ps.push(stringFromCharCode.apply(String, cs)),
32070 cs.length = 0;
32071 Array.prototype.push.apply(cs, arguments);
32072 };
32073 }
32074
32075 /**
32076 * Gets the accessor type.
32077 * @returns {Function} `Buffer` under node.js, `Uint8Array` respectively `DataView` in the browser (classes)
32078 * @expose
32079 */
32080 ByteBuffer.accessor = function() {
32081 return Uint8Array;
32082 };
32083 /**
32084 * Allocates a new ByteBuffer backed by a buffer of the specified capacity.
32085 * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
32086 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
32087 * {@link ByteBuffer.DEFAULT_ENDIAN}.
32088 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
32089 * {@link ByteBuffer.DEFAULT_NOASSERT}.
32090 * @returns {!ByteBuffer}
32091 * @expose
32092 */
32093 ByteBuffer.allocate = function(capacity, littleEndian, noAssert) {
32094 return new ByteBuffer(capacity, littleEndian, noAssert);
32095 };
32096
32097 /**
32098 * Concatenates multiple ByteBuffers into one.
32099 * @param {!Array.<!ByteBuffer|!ArrayBuffer|!Uint8Array|string>} buffers Buffers to concatenate
32100 * @param {(string|boolean)=} encoding String encoding if `buffers` contains a string ("base64", "hex", "binary",
32101 * defaults to "utf8")
32102 * @param {boolean=} littleEndian Whether to use little or big endian byte order for the resulting ByteBuffer. Defaults
32103 * to {@link ByteBuffer.DEFAULT_ENDIAN}.
32104 * @param {boolean=} noAssert Whether to skip assertions of offsets and values for the resulting ByteBuffer. Defaults to
32105 * {@link ByteBuffer.DEFAULT_NOASSERT}.
32106 * @returns {!ByteBuffer} Concatenated ByteBuffer
32107 * @expose
32108 */
32109 ByteBuffer.concat = function(buffers, encoding, littleEndian, noAssert) {
32110 if (typeof encoding === 'boolean' || typeof encoding !== 'string') {
32111 noAssert = littleEndian;
32112 littleEndian = encoding;
32113 encoding = undefined;
32114 }
32115 var capacity = 0;
32116 for (var i=0, k=buffers.length, length; i<k; ++i) {
32117 if (!ByteBuffer.isByteBuffer(buffers[i]))
32118 buffers[i] = ByteBuffer.wrap(buffers[i], encoding);
32119 length = buffers[i].limit - buffers[i].offset;
32120 if (length > 0) capacity += length;
32121 }
32122 if (capacity === 0)
32123 return new ByteBuffer(0, littleEndian, noAssert);
32124 var bb = new ByteBuffer(capacity, littleEndian, noAssert),
32125 bi;
32126 i=0; while (i<k) {
32127 bi = buffers[i++];
32128 length = bi.limit - bi.offset;
32129 if (length <= 0) continue;
32130 bb.view.set(bi.view.subarray(bi.offset, bi.limit), bb.offset);
32131 bb.offset += length;
32132 }
32133 bb.limit = bb.offset;
32134 bb.offset = 0;
32135 return bb;
32136 };
32137
32138 /**
32139 * Tests if the specified type is a ByteBuffer.
32140 * @param {*} bb ByteBuffer to test
32141 * @returns {boolean} `true` if it is a ByteBuffer, otherwise `false`
32142 * @expose
32143 */
32144 ByteBuffer.isByteBuffer = function(bb) {
32145 return (bb && bb["__isByteBuffer__"]) === true;
32146 };
32147 /**
32148 * Gets the backing buffer type.
32149 * @returns {Function} `Buffer` under node.js, `ArrayBuffer` in the browser (classes)
32150 * @expose
32151 */
32152 ByteBuffer.type = function() {
32153 return ArrayBuffer;
32154 };
32155 /**
32156 * Wraps a buffer or a string. Sets the allocated ByteBuffer's {@link ByteBuffer#offset} to `0` and its
32157 * {@link ByteBuffer#limit} to the length of the wrapped data.
32158 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string|!Array.<number>} buffer Anything that can be wrapped
32159 * @param {(string|boolean)=} encoding String encoding if `buffer` is a string ("base64", "hex", "binary", defaults to
32160 * "utf8")
32161 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
32162 * {@link ByteBuffer.DEFAULT_ENDIAN}.
32163 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
32164 * {@link ByteBuffer.DEFAULT_NOASSERT}.
32165 * @returns {!ByteBuffer} A ByteBuffer wrapping `buffer`
32166 * @expose
32167 */
32168 ByteBuffer.wrap = function(buffer, encoding, littleEndian, noAssert) {
32169 if (typeof encoding !== 'string') {
32170 noAssert = littleEndian;
32171 littleEndian = encoding;
32172 encoding = undefined;
32173 }
32174 if (typeof buffer === 'string') {
32175 if (typeof encoding === 'undefined')
32176 encoding = "utf8";
32177 switch (encoding) {
32178 case "base64":
32179 return ByteBuffer.fromBase64(buffer, littleEndian);
32180 case "hex":
32181 return ByteBuffer.fromHex(buffer, littleEndian);
32182 case "binary":
32183 return ByteBuffer.fromBinary(buffer, littleEndian);
32184 case "utf8":
32185 return ByteBuffer.fromUTF8(buffer, littleEndian);
32186 case "debug":
32187 return ByteBuffer.fromDebug(buffer, littleEndian);
32188 default:
32189 throw Error("Unsupported encoding: "+encoding);
32190 }
32191 }
32192 if (buffer === null || typeof buffer !== 'object')
32193 throw TypeError("Illegal buffer");
32194 var bb;
32195 if (ByteBuffer.isByteBuffer(buffer)) {
32196 bb = ByteBufferPrototype.clone.call(buffer);
32197 bb.markedOffset = -1;
32198 return bb;
32199 }
32200 if (buffer instanceof Uint8Array) { // Extract ArrayBuffer from Uint8Array
32201 bb = new ByteBuffer(0, littleEndian, noAssert);
32202 if (buffer.length > 0) { // Avoid references to more than one EMPTY_BUFFER
32203 bb.buffer = buffer.buffer;
32204 bb.offset = buffer.byteOffset;
32205 bb.limit = buffer.byteOffset + buffer.byteLength;
32206 bb.view = new Uint8Array(buffer.buffer);
32207 }
32208 } else if (buffer instanceof ArrayBuffer) { // Reuse ArrayBuffer
32209 bb = new ByteBuffer(0, littleEndian, noAssert);
32210 if (buffer.byteLength > 0) {
32211 bb.buffer = buffer;
32212 bb.offset = 0;
32213 bb.limit = buffer.byteLength;
32214 bb.view = buffer.byteLength > 0 ? new Uint8Array(buffer) : null;
32215 }
32216 } else if (Object.prototype.toString.call(buffer) === "[object Array]") { // Create from octets
32217 bb = new ByteBuffer(buffer.length, littleEndian, noAssert);
32218 bb.limit = buffer.length;
32219 for (var i=0; i<buffer.length; ++i)
32220 bb.view[i] = buffer[i];
32221 } else
32222 throw TypeError("Illegal buffer"); // Otherwise fail
32223 return bb;
32224 };
32225
32226 /**
32227 * Writes the array as a bitset.
32228 * @param {Array<boolean>} value Array of booleans to write
32229 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
32230 * @returns {!ByteBuffer}
32231 * @expose
32232 */
32233 ByteBufferPrototype.writeBitSet = function(value, offset) {
32234 var relative = typeof offset === 'undefined';
32235 if (relative) offset = this.offset;
32236 if (!this.noAssert) {
32237 if (!(value instanceof Array))
32238 throw TypeError("Illegal BitSet: Not an array");
32239 if (typeof offset !== 'number' || offset % 1 !== 0)
32240 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32241 offset >>>= 0;
32242 if (offset < 0 || offset + 0 > this.buffer.byteLength)
32243 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
32244 }
32245
32246 var start = offset,
32247 bits = value.length,
32248 bytes = (bits >> 3),
32249 bit = 0,
32250 k;
32251
32252 offset += this.writeVarint32(bits,offset);
32253
32254 while(bytes--) {
32255 k = (!!value[bit++] & 1) |
32256 ((!!value[bit++] & 1) << 1) |
32257 ((!!value[bit++] & 1) << 2) |
32258 ((!!value[bit++] & 1) << 3) |
32259 ((!!value[bit++] & 1) << 4) |
32260 ((!!value[bit++] & 1) << 5) |
32261 ((!!value[bit++] & 1) << 6) |
32262 ((!!value[bit++] & 1) << 7);
32263 this.writeByte(k,offset++);
32264 }
32265
32266 if(bit < bits) {
32267 var m = 0; k = 0;
32268 while(bit < bits) k = k | ((!!value[bit++] & 1) << (m++));
32269 this.writeByte(k,offset++);
32270 }
32271
32272 if (relative) {
32273 this.offset = offset;
32274 return this;
32275 }
32276 return offset - start;
32277 }
32278
32279 /**
32280 * Reads a BitSet as an array of booleans.
32281 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
32282 * @returns {Array<boolean>
32283 * @expose
32284 */
32285 ByteBufferPrototype.readBitSet = function(offset) {
32286 var relative = typeof offset === 'undefined';
32287 if (relative) offset = this.offset;
32288
32289 var ret = this.readVarint32(offset),
32290 bits = ret.value,
32291 bytes = (bits >> 3),
32292 bit = 0,
32293 value = [],
32294 k;
32295
32296 offset += ret.length;
32297
32298 while(bytes--) {
32299 k = this.readByte(offset++);
32300 value[bit++] = !!(k & 0x01);
32301 value[bit++] = !!(k & 0x02);
32302 value[bit++] = !!(k & 0x04);
32303 value[bit++] = !!(k & 0x08);
32304 value[bit++] = !!(k & 0x10);
32305 value[bit++] = !!(k & 0x20);
32306 value[bit++] = !!(k & 0x40);
32307 value[bit++] = !!(k & 0x80);
32308 }
32309
32310 if(bit < bits) {
32311 var m = 0;
32312 k = this.readByte(offset++);
32313 while(bit < bits) value[bit++] = !!((k >> (m++)) & 1);
32314 }
32315
32316 if (relative) {
32317 this.offset = offset;
32318 }
32319 return value;
32320 }
32321 /**
32322 * Reads the specified number of bytes.
32323 * @param {number} length Number of bytes to read
32324 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
32325 * @returns {!ByteBuffer}
32326 * @expose
32327 */
32328 ByteBufferPrototype.readBytes = function(length, offset) {
32329 var relative = typeof offset === 'undefined';
32330 if (relative) offset = this.offset;
32331 if (!this.noAssert) {
32332 if (typeof offset !== 'number' || offset % 1 !== 0)
32333 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32334 offset >>>= 0;
32335 if (offset < 0 || offset + length > this.buffer.byteLength)
32336 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
32337 }
32338 var slice = this.slice(offset, offset + length);
32339 if (relative) this.offset += length;
32340 return slice;
32341 };
32342
32343 /**
32344 * Writes a payload of bytes. This is an alias of {@link ByteBuffer#append}.
32345 * @function
32346 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to write. If `source` is a ByteBuffer, its offsets
32347 * will be modified according to the performed read operation.
32348 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
32349 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
32350 * written if omitted.
32351 * @returns {!ByteBuffer} this
32352 * @expose
32353 */
32354 ByteBufferPrototype.writeBytes = ByteBufferPrototype.append;
32355
32356 // types/ints/int8
32357
32358 /**
32359 * Writes an 8bit signed integer.
32360 * @param {number} value Value to write
32361 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
32362 * @returns {!ByteBuffer} this
32363 * @expose
32364 */
32365 ByteBufferPrototype.writeInt8 = function(value, offset) {
32366 var relative = typeof offset === 'undefined';
32367 if (relative) offset = this.offset;
32368 if (!this.noAssert) {
32369 if (typeof value !== 'number' || value % 1 !== 0)
32370 throw TypeError("Illegal value: "+value+" (not an integer)");
32371 value |= 0;
32372 if (typeof offset !== 'number' || offset % 1 !== 0)
32373 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32374 offset >>>= 0;
32375 if (offset < 0 || offset + 0 > this.buffer.byteLength)
32376 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
32377 }
32378 offset += 1;
32379 var capacity0 = this.buffer.byteLength;
32380 if (offset > capacity0)
32381 this.resize((capacity0 *= 2) > offset ? capacity0 : offset);
32382 offset -= 1;
32383 this.view[offset] = value;
32384 if (relative) this.offset += 1;
32385 return this;
32386 };
32387
32388 /**
32389 * Writes an 8bit signed integer. This is an alias of {@link ByteBuffer#writeInt8}.
32390 * @function
32391 * @param {number} value Value to write
32392 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
32393 * @returns {!ByteBuffer} this
32394 * @expose
32395 */
32396 ByteBufferPrototype.writeByte = ByteBufferPrototype.writeInt8;
32397
32398 /**
32399 * Reads an 8bit signed integer.
32400 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
32401 * @returns {number} Value read
32402 * @expose
32403 */
32404 ByteBufferPrototype.readInt8 = function(offset) {
32405 var relative = typeof offset === 'undefined';
32406 if (relative) offset = this.offset;
32407 if (!this.noAssert) {
32408 if (typeof offset !== 'number' || offset % 1 !== 0)
32409 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32410 offset >>>= 0;
32411 if (offset < 0 || offset + 1 > this.buffer.byteLength)
32412 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
32413 }
32414 var value = this.view[offset];
32415 if ((value & 0x80) === 0x80) value = -(0xFF - value + 1); // Cast to signed
32416 if (relative) this.offset += 1;
32417 return value;
32418 };
32419
32420 /**
32421 * Reads an 8bit signed integer. This is an alias of {@link ByteBuffer#readInt8}.
32422 * @function
32423 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
32424 * @returns {number} Value read
32425 * @expose
32426 */
32427 ByteBufferPrototype.readByte = ByteBufferPrototype.readInt8;
32428
32429 /**
32430 * Writes an 8bit unsigned integer.
32431 * @param {number} value Value to write
32432 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
32433 * @returns {!ByteBuffer} this
32434 * @expose
32435 */
32436 ByteBufferPrototype.writeUint8 = function(value, offset) {
32437 var relative = typeof offset === 'undefined';
32438 if (relative) offset = this.offset;
32439 if (!this.noAssert) {
32440 if (typeof value !== 'number' || value % 1 !== 0)
32441 throw TypeError("Illegal value: "+value+" (not an integer)");
32442 value >>>= 0;
32443 if (typeof offset !== 'number' || offset % 1 !== 0)
32444 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32445 offset >>>= 0;
32446 if (offset < 0 || offset + 0 > this.buffer.byteLength)
32447 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
32448 }
32449 offset += 1;
32450 var capacity1 = this.buffer.byteLength;
32451 if (offset > capacity1)
32452 this.resize((capacity1 *= 2) > offset ? capacity1 : offset);
32453 offset -= 1;
32454 this.view[offset] = value;
32455 if (relative) this.offset += 1;
32456 return this;
32457 };
32458
32459 /**
32460 * Writes an 8bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint8}.
32461 * @function
32462 * @param {number} value Value to write
32463 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
32464 * @returns {!ByteBuffer} this
32465 * @expose
32466 */
32467 ByteBufferPrototype.writeUInt8 = ByteBufferPrototype.writeUint8;
32468
32469 /**
32470 * Reads an 8bit unsigned integer.
32471 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
32472 * @returns {number} Value read
32473 * @expose
32474 */
32475 ByteBufferPrototype.readUint8 = function(offset) {
32476 var relative = typeof offset === 'undefined';
32477 if (relative) offset = this.offset;
32478 if (!this.noAssert) {
32479 if (typeof offset !== 'number' || offset % 1 !== 0)
32480 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32481 offset >>>= 0;
32482 if (offset < 0 || offset + 1 > this.buffer.byteLength)
32483 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
32484 }
32485 var value = this.view[offset];
32486 if (relative) this.offset += 1;
32487 return value;
32488 };
32489
32490 /**
32491 * Reads an 8bit unsigned integer. This is an alias of {@link ByteBuffer#readUint8}.
32492 * @function
32493 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
32494 * @returns {number} Value read
32495 * @expose
32496 */
32497 ByteBufferPrototype.readUInt8 = ByteBufferPrototype.readUint8;
32498
32499 // types/ints/int16
32500
32501 /**
32502 * Writes a 16bit signed integer.
32503 * @param {number} value Value to write
32504 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
32505 * @throws {TypeError} If `offset` or `value` is not a valid number
32506 * @throws {RangeError} If `offset` is out of bounds
32507 * @expose
32508 */
32509 ByteBufferPrototype.writeInt16 = function(value, offset) {
32510 var relative = typeof offset === 'undefined';
32511 if (relative) offset = this.offset;
32512 if (!this.noAssert) {
32513 if (typeof value !== 'number' || value % 1 !== 0)
32514 throw TypeError("Illegal value: "+value+" (not an integer)");
32515 value |= 0;
32516 if (typeof offset !== 'number' || offset % 1 !== 0)
32517 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32518 offset >>>= 0;
32519 if (offset < 0 || offset + 0 > this.buffer.byteLength)
32520 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
32521 }
32522 offset += 2;
32523 var capacity2 = this.buffer.byteLength;
32524 if (offset > capacity2)
32525 this.resize((capacity2 *= 2) > offset ? capacity2 : offset);
32526 offset -= 2;
32527 if (this.littleEndian) {
32528 this.view[offset+1] = (value & 0xFF00) >>> 8;
32529 this.view[offset ] = value & 0x00FF;
32530 } else {
32531 this.view[offset] = (value & 0xFF00) >>> 8;
32532 this.view[offset+1] = value & 0x00FF;
32533 }
32534 if (relative) this.offset += 2;
32535 return this;
32536 };
32537
32538 /**
32539 * Writes a 16bit signed integer. This is an alias of {@link ByteBuffer#writeInt16}.
32540 * @function
32541 * @param {number} value Value to write
32542 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
32543 * @throws {TypeError} If `offset` or `value` is not a valid number
32544 * @throws {RangeError} If `offset` is out of bounds
32545 * @expose
32546 */
32547 ByteBufferPrototype.writeShort = ByteBufferPrototype.writeInt16;
32548
32549 /**
32550 * Reads a 16bit signed integer.
32551 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
32552 * @returns {number} Value read
32553 * @throws {TypeError} If `offset` is not a valid number
32554 * @throws {RangeError} If `offset` is out of bounds
32555 * @expose
32556 */
32557 ByteBufferPrototype.readInt16 = function(offset) {
32558 var relative = typeof offset === 'undefined';
32559 if (relative) offset = this.offset;
32560 if (!this.noAssert) {
32561 if (typeof offset !== 'number' || offset % 1 !== 0)
32562 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32563 offset >>>= 0;
32564 if (offset < 0 || offset + 2 > this.buffer.byteLength)
32565 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
32566 }
32567 var value = 0;
32568 if (this.littleEndian) {
32569 value = this.view[offset ];
32570 value |= this.view[offset+1] << 8;
32571 } else {
32572 value = this.view[offset ] << 8;
32573 value |= this.view[offset+1];
32574 }
32575 if ((value & 0x8000) === 0x8000) value = -(0xFFFF - value + 1); // Cast to signed
32576 if (relative) this.offset += 2;
32577 return value;
32578 };
32579
32580 /**
32581 * Reads a 16bit signed integer. This is an alias of {@link ByteBuffer#readInt16}.
32582 * @function
32583 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
32584 * @returns {number} Value read
32585 * @throws {TypeError} If `offset` is not a valid number
32586 * @throws {RangeError} If `offset` is out of bounds
32587 * @expose
32588 */
32589 ByteBufferPrototype.readShort = ByteBufferPrototype.readInt16;
32590
32591 /**
32592 * Writes a 16bit unsigned integer.
32593 * @param {number} value Value to write
32594 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
32595 * @throws {TypeError} If `offset` or `value` is not a valid number
32596 * @throws {RangeError} If `offset` is out of bounds
32597 * @expose
32598 */
32599 ByteBufferPrototype.writeUint16 = function(value, offset) {
32600 var relative = typeof offset === 'undefined';
32601 if (relative) offset = this.offset;
32602 if (!this.noAssert) {
32603 if (typeof value !== 'number' || value % 1 !== 0)
32604 throw TypeError("Illegal value: "+value+" (not an integer)");
32605 value >>>= 0;
32606 if (typeof offset !== 'number' || offset % 1 !== 0)
32607 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32608 offset >>>= 0;
32609 if (offset < 0 || offset + 0 > this.buffer.byteLength)
32610 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
32611 }
32612 offset += 2;
32613 var capacity3 = this.buffer.byteLength;
32614 if (offset > capacity3)
32615 this.resize((capacity3 *= 2) > offset ? capacity3 : offset);
32616 offset -= 2;
32617 if (this.littleEndian) {
32618 this.view[offset+1] = (value & 0xFF00) >>> 8;
32619 this.view[offset ] = value & 0x00FF;
32620 } else {
32621 this.view[offset] = (value & 0xFF00) >>> 8;
32622 this.view[offset+1] = value & 0x00FF;
32623 }
32624 if (relative) this.offset += 2;
32625 return this;
32626 };
32627
32628 /**
32629 * Writes a 16bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint16}.
32630 * @function
32631 * @param {number} value Value to write
32632 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
32633 * @throws {TypeError} If `offset` or `value` is not a valid number
32634 * @throws {RangeError} If `offset` is out of bounds
32635 * @expose
32636 */
32637 ByteBufferPrototype.writeUInt16 = ByteBufferPrototype.writeUint16;
32638
32639 /**
32640 * Reads a 16bit unsigned integer.
32641 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
32642 * @returns {number} Value read
32643 * @throws {TypeError} If `offset` is not a valid number
32644 * @throws {RangeError} If `offset` is out of bounds
32645 * @expose
32646 */
32647 ByteBufferPrototype.readUint16 = function(offset) {
32648 var relative = typeof offset === 'undefined';
32649 if (relative) offset = this.offset;
32650 if (!this.noAssert) {
32651 if (typeof offset !== 'number' || offset % 1 !== 0)
32652 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32653 offset >>>= 0;
32654 if (offset < 0 || offset + 2 > this.buffer.byteLength)
32655 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
32656 }
32657 var value = 0;
32658 if (this.littleEndian) {
32659 value = this.view[offset ];
32660 value |= this.view[offset+1] << 8;
32661 } else {
32662 value = this.view[offset ] << 8;
32663 value |= this.view[offset+1];
32664 }
32665 if (relative) this.offset += 2;
32666 return value;
32667 };
32668
32669 /**
32670 * Reads a 16bit unsigned integer. This is an alias of {@link ByteBuffer#readUint16}.
32671 * @function
32672 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
32673 * @returns {number} Value read
32674 * @throws {TypeError} If `offset` is not a valid number
32675 * @throws {RangeError} If `offset` is out of bounds
32676 * @expose
32677 */
32678 ByteBufferPrototype.readUInt16 = ByteBufferPrototype.readUint16;
32679
32680 // types/ints/int32
32681
32682 /**
32683 * Writes a 32bit signed integer.
32684 * @param {number} value Value to write
32685 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
32686 * @expose
32687 */
32688 ByteBufferPrototype.writeInt32 = function(value, offset) {
32689 var relative = typeof offset === 'undefined';
32690 if (relative) offset = this.offset;
32691 if (!this.noAssert) {
32692 if (typeof value !== 'number' || value % 1 !== 0)
32693 throw TypeError("Illegal value: "+value+" (not an integer)");
32694 value |= 0;
32695 if (typeof offset !== 'number' || offset % 1 !== 0)
32696 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32697 offset >>>= 0;
32698 if (offset < 0 || offset + 0 > this.buffer.byteLength)
32699 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
32700 }
32701 offset += 4;
32702 var capacity4 = this.buffer.byteLength;
32703 if (offset > capacity4)
32704 this.resize((capacity4 *= 2) > offset ? capacity4 : offset);
32705 offset -= 4;
32706 if (this.littleEndian) {
32707 this.view[offset+3] = (value >>> 24) & 0xFF;
32708 this.view[offset+2] = (value >>> 16) & 0xFF;
32709 this.view[offset+1] = (value >>> 8) & 0xFF;
32710 this.view[offset ] = value & 0xFF;
32711 } else {
32712 this.view[offset ] = (value >>> 24) & 0xFF;
32713 this.view[offset+1] = (value >>> 16) & 0xFF;
32714 this.view[offset+2] = (value >>> 8) & 0xFF;
32715 this.view[offset+3] = value & 0xFF;
32716 }
32717 if (relative) this.offset += 4;
32718 return this;
32719 };
32720
32721 /**
32722 * Writes a 32bit signed integer. This is an alias of {@link ByteBuffer#writeInt32}.
32723 * @param {number} value Value to write
32724 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
32725 * @expose
32726 */
32727 ByteBufferPrototype.writeInt = ByteBufferPrototype.writeInt32;
32728
32729 /**
32730 * Reads a 32bit signed integer.
32731 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
32732 * @returns {number} Value read
32733 * @expose
32734 */
32735 ByteBufferPrototype.readInt32 = function(offset) {
32736 var relative = typeof offset === 'undefined';
32737 if (relative) offset = this.offset;
32738 if (!this.noAssert) {
32739 if (typeof offset !== 'number' || offset % 1 !== 0)
32740 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32741 offset >>>= 0;
32742 if (offset < 0 || offset + 4 > this.buffer.byteLength)
32743 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
32744 }
32745 var value = 0;
32746 if (this.littleEndian) {
32747 value = this.view[offset+2] << 16;
32748 value |= this.view[offset+1] << 8;
32749 value |= this.view[offset ];
32750 value += this.view[offset+3] << 24 >>> 0;
32751 } else {
32752 value = this.view[offset+1] << 16;
32753 value |= this.view[offset+2] << 8;
32754 value |= this.view[offset+3];
32755 value += this.view[offset ] << 24 >>> 0;
32756 }
32757 value |= 0; // Cast to signed
32758 if (relative) this.offset += 4;
32759 return value;
32760 };
32761
32762 /**
32763 * Reads a 32bit signed integer. This is an alias of {@link ByteBuffer#readInt32}.
32764 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `4` if omitted.
32765 * @returns {number} Value read
32766 * @expose
32767 */
32768 ByteBufferPrototype.readInt = ByteBufferPrototype.readInt32;
32769
32770 /**
32771 * Writes a 32bit unsigned integer.
32772 * @param {number} value Value to write
32773 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
32774 * @expose
32775 */
32776 ByteBufferPrototype.writeUint32 = function(value, offset) {
32777 var relative = typeof offset === 'undefined';
32778 if (relative) offset = this.offset;
32779 if (!this.noAssert) {
32780 if (typeof value !== 'number' || value % 1 !== 0)
32781 throw TypeError("Illegal value: "+value+" (not an integer)");
32782 value >>>= 0;
32783 if (typeof offset !== 'number' || offset % 1 !== 0)
32784 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32785 offset >>>= 0;
32786 if (offset < 0 || offset + 0 > this.buffer.byteLength)
32787 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
32788 }
32789 offset += 4;
32790 var capacity5 = this.buffer.byteLength;
32791 if (offset > capacity5)
32792 this.resize((capacity5 *= 2) > offset ? capacity5 : offset);
32793 offset -= 4;
32794 if (this.littleEndian) {
32795 this.view[offset+3] = (value >>> 24) & 0xFF;
32796 this.view[offset+2] = (value >>> 16) & 0xFF;
32797 this.view[offset+1] = (value >>> 8) & 0xFF;
32798 this.view[offset ] = value & 0xFF;
32799 } else {
32800 this.view[offset ] = (value >>> 24) & 0xFF;
32801 this.view[offset+1] = (value >>> 16) & 0xFF;
32802 this.view[offset+2] = (value >>> 8) & 0xFF;
32803 this.view[offset+3] = value & 0xFF;
32804 }
32805 if (relative) this.offset += 4;
32806 return this;
32807 };
32808
32809 /**
32810 * Writes a 32bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint32}.
32811 * @function
32812 * @param {number} value Value to write
32813 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
32814 * @expose
32815 */
32816 ByteBufferPrototype.writeUInt32 = ByteBufferPrototype.writeUint32;
32817
32818 /**
32819 * Reads a 32bit unsigned integer.
32820 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
32821 * @returns {number} Value read
32822 * @expose
32823 */
32824 ByteBufferPrototype.readUint32 = function(offset) {
32825 var relative = typeof offset === 'undefined';
32826 if (relative) offset = this.offset;
32827 if (!this.noAssert) {
32828 if (typeof offset !== 'number' || offset % 1 !== 0)
32829 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32830 offset >>>= 0;
32831 if (offset < 0 || offset + 4 > this.buffer.byteLength)
32832 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
32833 }
32834 var value = 0;
32835 if (this.littleEndian) {
32836 value = this.view[offset+2] << 16;
32837 value |= this.view[offset+1] << 8;
32838 value |= this.view[offset ];
32839 value += this.view[offset+3] << 24 >>> 0;
32840 } else {
32841 value = this.view[offset+1] << 16;
32842 value |= this.view[offset+2] << 8;
32843 value |= this.view[offset+3];
32844 value += this.view[offset ] << 24 >>> 0;
32845 }
32846 if (relative) this.offset += 4;
32847 return value;
32848 };
32849
32850 /**
32851 * Reads a 32bit unsigned integer. This is an alias of {@link ByteBuffer#readUint32}.
32852 * @function
32853 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
32854 * @returns {number} Value read
32855 * @expose
32856 */
32857 ByteBufferPrototype.readUInt32 = ByteBufferPrototype.readUint32;
32858
32859 // types/ints/int64
32860
32861 if (Long) {
32862
32863 /**
32864 * Writes a 64bit signed integer.
32865 * @param {number|!Long} value Value to write
32866 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
32867 * @returns {!ByteBuffer} this
32868 * @expose
32869 */
32870 ByteBufferPrototype.writeInt64 = function(value, offset) {
32871 var relative = typeof offset === 'undefined';
32872 if (relative) offset = this.offset;
32873 if (!this.noAssert) {
32874 if (typeof value === 'number')
32875 value = Long.fromNumber(value);
32876 else if (typeof value === 'string')
32877 value = Long.fromString(value);
32878 else if (!(value && value instanceof Long))
32879 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
32880 if (typeof offset !== 'number' || offset % 1 !== 0)
32881 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32882 offset >>>= 0;
32883 if (offset < 0 || offset + 0 > this.buffer.byteLength)
32884 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
32885 }
32886 if (typeof value === 'number')
32887 value = Long.fromNumber(value);
32888 else if (typeof value === 'string')
32889 value = Long.fromString(value);
32890 offset += 8;
32891 var capacity6 = this.buffer.byteLength;
32892 if (offset > capacity6)
32893 this.resize((capacity6 *= 2) > offset ? capacity6 : offset);
32894 offset -= 8;
32895 var lo = value.low,
32896 hi = value.high;
32897 if (this.littleEndian) {
32898 this.view[offset+3] = (lo >>> 24) & 0xFF;
32899 this.view[offset+2] = (lo >>> 16) & 0xFF;
32900 this.view[offset+1] = (lo >>> 8) & 0xFF;
32901 this.view[offset ] = lo & 0xFF;
32902 offset += 4;
32903 this.view[offset+3] = (hi >>> 24) & 0xFF;
32904 this.view[offset+2] = (hi >>> 16) & 0xFF;
32905 this.view[offset+1] = (hi >>> 8) & 0xFF;
32906 this.view[offset ] = hi & 0xFF;
32907 } else {
32908 this.view[offset ] = (hi >>> 24) & 0xFF;
32909 this.view[offset+1] = (hi >>> 16) & 0xFF;
32910 this.view[offset+2] = (hi >>> 8) & 0xFF;
32911 this.view[offset+3] = hi & 0xFF;
32912 offset += 4;
32913 this.view[offset ] = (lo >>> 24) & 0xFF;
32914 this.view[offset+1] = (lo >>> 16) & 0xFF;
32915 this.view[offset+2] = (lo >>> 8) & 0xFF;
32916 this.view[offset+3] = lo & 0xFF;
32917 }
32918 if (relative) this.offset += 8;
32919 return this;
32920 };
32921
32922 /**
32923 * Writes a 64bit signed integer. This is an alias of {@link ByteBuffer#writeInt64}.
32924 * @param {number|!Long} value Value to write
32925 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
32926 * @returns {!ByteBuffer} this
32927 * @expose
32928 */
32929 ByteBufferPrototype.writeLong = ByteBufferPrototype.writeInt64;
32930
32931 /**
32932 * Reads a 64bit signed integer.
32933 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
32934 * @returns {!Long}
32935 * @expose
32936 */
32937 ByteBufferPrototype.readInt64 = function(offset) {
32938 var relative = typeof offset === 'undefined';
32939 if (relative) offset = this.offset;
32940 if (!this.noAssert) {
32941 if (typeof offset !== 'number' || offset % 1 !== 0)
32942 throw TypeError("Illegal offset: "+offset+" (not an integer)");
32943 offset >>>= 0;
32944 if (offset < 0 || offset + 8 > this.buffer.byteLength)
32945 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
32946 }
32947 var lo = 0,
32948 hi = 0;
32949 if (this.littleEndian) {
32950 lo = this.view[offset+2] << 16;
32951 lo |= this.view[offset+1] << 8;
32952 lo |= this.view[offset ];
32953 lo += this.view[offset+3] << 24 >>> 0;
32954 offset += 4;
32955 hi = this.view[offset+2] << 16;
32956 hi |= this.view[offset+1] << 8;
32957 hi |= this.view[offset ];
32958 hi += this.view[offset+3] << 24 >>> 0;
32959 } else {
32960 hi = this.view[offset+1] << 16;
32961 hi |= this.view[offset+2] << 8;
32962 hi |= this.view[offset+3];
32963 hi += this.view[offset ] << 24 >>> 0;
32964 offset += 4;
32965 lo = this.view[offset+1] << 16;
32966 lo |= this.view[offset+2] << 8;
32967 lo |= this.view[offset+3];
32968 lo += this.view[offset ] << 24 >>> 0;
32969 }
32970 var value = new Long(lo, hi, false);
32971 if (relative) this.offset += 8;
32972 return value;
32973 };
32974
32975 /**
32976 * Reads a 64bit signed integer. This is an alias of {@link ByteBuffer#readInt64}.
32977 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
32978 * @returns {!Long}
32979 * @expose
32980 */
32981 ByteBufferPrototype.readLong = ByteBufferPrototype.readInt64;
32982
32983 /**
32984 * Writes a 64bit unsigned integer.
32985 * @param {number|!Long} value Value to write
32986 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
32987 * @returns {!ByteBuffer} this
32988 * @expose
32989 */
32990 ByteBufferPrototype.writeUint64 = function(value, offset) {
32991 var relative = typeof offset === 'undefined';
32992 if (relative) offset = this.offset;
32993 if (!this.noAssert) {
32994 if (typeof value === 'number')
32995 value = Long.fromNumber(value);
32996 else if (typeof value === 'string')
32997 value = Long.fromString(value);
32998 else if (!(value && value instanceof Long))
32999 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
33000 if (typeof offset !== 'number' || offset % 1 !== 0)
33001 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33002 offset >>>= 0;
33003 if (offset < 0 || offset + 0 > this.buffer.byteLength)
33004 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
33005 }
33006 if (typeof value === 'number')
33007 value = Long.fromNumber(value);
33008 else if (typeof value === 'string')
33009 value = Long.fromString(value);
33010 offset += 8;
33011 var capacity7 = this.buffer.byteLength;
33012 if (offset > capacity7)
33013 this.resize((capacity7 *= 2) > offset ? capacity7 : offset);
33014 offset -= 8;
33015 var lo = value.low,
33016 hi = value.high;
33017 if (this.littleEndian) {
33018 this.view[offset+3] = (lo >>> 24) & 0xFF;
33019 this.view[offset+2] = (lo >>> 16) & 0xFF;
33020 this.view[offset+1] = (lo >>> 8) & 0xFF;
33021 this.view[offset ] = lo & 0xFF;
33022 offset += 4;
33023 this.view[offset+3] = (hi >>> 24) & 0xFF;
33024 this.view[offset+2] = (hi >>> 16) & 0xFF;
33025 this.view[offset+1] = (hi >>> 8) & 0xFF;
33026 this.view[offset ] = hi & 0xFF;
33027 } else {
33028 this.view[offset ] = (hi >>> 24) & 0xFF;
33029 this.view[offset+1] = (hi >>> 16) & 0xFF;
33030 this.view[offset+2] = (hi >>> 8) & 0xFF;
33031 this.view[offset+3] = hi & 0xFF;
33032 offset += 4;
33033 this.view[offset ] = (lo >>> 24) & 0xFF;
33034 this.view[offset+1] = (lo >>> 16) & 0xFF;
33035 this.view[offset+2] = (lo >>> 8) & 0xFF;
33036 this.view[offset+3] = lo & 0xFF;
33037 }
33038 if (relative) this.offset += 8;
33039 return this;
33040 };
33041
33042 /**
33043 * Writes a 64bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint64}.
33044 * @function
33045 * @param {number|!Long} value Value to write
33046 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
33047 * @returns {!ByteBuffer} this
33048 * @expose
33049 */
33050 ByteBufferPrototype.writeUInt64 = ByteBufferPrototype.writeUint64;
33051
33052 /**
33053 * Reads a 64bit unsigned integer.
33054 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
33055 * @returns {!Long}
33056 * @expose
33057 */
33058 ByteBufferPrototype.readUint64 = function(offset) {
33059 var relative = typeof offset === 'undefined';
33060 if (relative) offset = this.offset;
33061 if (!this.noAssert) {
33062 if (typeof offset !== 'number' || offset % 1 !== 0)
33063 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33064 offset >>>= 0;
33065 if (offset < 0 || offset + 8 > this.buffer.byteLength)
33066 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
33067 }
33068 var lo = 0,
33069 hi = 0;
33070 if (this.littleEndian) {
33071 lo = this.view[offset+2] << 16;
33072 lo |= this.view[offset+1] << 8;
33073 lo |= this.view[offset ];
33074 lo += this.view[offset+3] << 24 >>> 0;
33075 offset += 4;
33076 hi = this.view[offset+2] << 16;
33077 hi |= this.view[offset+1] << 8;
33078 hi |= this.view[offset ];
33079 hi += this.view[offset+3] << 24 >>> 0;
33080 } else {
33081 hi = this.view[offset+1] << 16;
33082 hi |= this.view[offset+2] << 8;
33083 hi |= this.view[offset+3];
33084 hi += this.view[offset ] << 24 >>> 0;
33085 offset += 4;
33086 lo = this.view[offset+1] << 16;
33087 lo |= this.view[offset+2] << 8;
33088 lo |= this.view[offset+3];
33089 lo += this.view[offset ] << 24 >>> 0;
33090 }
33091 var value = new Long(lo, hi, true);
33092 if (relative) this.offset += 8;
33093 return value;
33094 };
33095
33096 /**
33097 * Reads a 64bit unsigned integer. This is an alias of {@link ByteBuffer#readUint64}.
33098 * @function
33099 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
33100 * @returns {!Long}
33101 * @expose
33102 */
33103 ByteBufferPrototype.readUInt64 = ByteBufferPrototype.readUint64;
33104
33105 } // Long
33106
33107
33108 // types/floats/float32
33109
33110 /*
33111 ieee754 - https://github.com/feross/ieee754
33112
33113 The MIT License (MIT)
33114
33115 Copyright (c) Feross Aboukhadijeh
33116
33117 Permission is hereby granted, free of charge, to any person obtaining a copy
33118 of this software and associated documentation files (the "Software"), to deal
33119 in the Software without restriction, including without limitation the rights
33120 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
33121 copies of the Software, and to permit persons to whom the Software is
33122 furnished to do so, subject to the following conditions:
33123
33124 The above copyright notice and this permission notice shall be included in
33125 all copies or substantial portions of the Software.
33126
33127 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
33128 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
33129 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
33130 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33131 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
33132 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
33133 THE SOFTWARE.
33134 */
33135
33136 /**
33137 * Reads an IEEE754 float from a byte array.
33138 * @param {!Array} buffer
33139 * @param {number} offset
33140 * @param {boolean} isLE
33141 * @param {number} mLen
33142 * @param {number} nBytes
33143 * @returns {number}
33144 * @inner
33145 */
33146 function ieee754_read(buffer, offset, isLE, mLen, nBytes) {
33147 var e, m,
33148 eLen = nBytes * 8 - mLen - 1,
33149 eMax = (1 << eLen) - 1,
33150 eBias = eMax >> 1,
33151 nBits = -7,
33152 i = isLE ? (nBytes - 1) : 0,
33153 d = isLE ? -1 : 1,
33154 s = buffer[offset + i];
33155
33156 i += d;
33157
33158 e = s & ((1 << (-nBits)) - 1);
33159 s >>= (-nBits);
33160 nBits += eLen;
33161 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
33162
33163 m = e & ((1 << (-nBits)) - 1);
33164 e >>= (-nBits);
33165 nBits += mLen;
33166 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
33167
33168 if (e === 0) {
33169 e = 1 - eBias;
33170 } else if (e === eMax) {
33171 return m ? NaN : ((s ? -1 : 1) * Infinity);
33172 } else {
33173 m = m + Math.pow(2, mLen);
33174 e = e - eBias;
33175 }
33176 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
33177 }
33178
33179 /**
33180 * Writes an IEEE754 float to a byte array.
33181 * @param {!Array} buffer
33182 * @param {number} value
33183 * @param {number} offset
33184 * @param {boolean} isLE
33185 * @param {number} mLen
33186 * @param {number} nBytes
33187 * @inner
33188 */
33189 function ieee754_write(buffer, value, offset, isLE, mLen, nBytes) {
33190 var e, m, c,
33191 eLen = nBytes * 8 - mLen - 1,
33192 eMax = (1 << eLen) - 1,
33193 eBias = eMax >> 1,
33194 rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
33195 i = isLE ? 0 : (nBytes - 1),
33196 d = isLE ? 1 : -1,
33197 s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
33198
33199 value = Math.abs(value);
33200
33201 if (isNaN(value) || value === Infinity) {
33202 m = isNaN(value) ? 1 : 0;
33203 e = eMax;
33204 } else {
33205 e = Math.floor(Math.log(value) / Math.LN2);
33206 if (value * (c = Math.pow(2, -e)) < 1) {
33207 e--;
33208 c *= 2;
33209 }
33210 if (e + eBias >= 1) {
33211 value += rt / c;
33212 } else {
33213 value += rt * Math.pow(2, 1 - eBias);
33214 }
33215 if (value * c >= 2) {
33216 e++;
33217 c /= 2;
33218 }
33219
33220 if (e + eBias >= eMax) {
33221 m = 0;
33222 e = eMax;
33223 } else if (e + eBias >= 1) {
33224 m = (value * c - 1) * Math.pow(2, mLen);
33225 e = e + eBias;
33226 } else {
33227 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
33228 e = 0;
33229 }
33230 }
33231
33232 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
33233
33234 e = (e << mLen) | m;
33235 eLen += mLen;
33236 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
33237
33238 buffer[offset + i - d] |= s * 128;
33239 }
33240
33241 /**
33242 * Writes a 32bit float.
33243 * @param {number} value Value to write
33244 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
33245 * @returns {!ByteBuffer} this
33246 * @expose
33247 */
33248 ByteBufferPrototype.writeFloat32 = function(value, offset) {
33249 var relative = typeof offset === 'undefined';
33250 if (relative) offset = this.offset;
33251 if (!this.noAssert) {
33252 if (typeof value !== 'number')
33253 throw TypeError("Illegal value: "+value+" (not a number)");
33254 if (typeof offset !== 'number' || offset % 1 !== 0)
33255 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33256 offset >>>= 0;
33257 if (offset < 0 || offset + 0 > this.buffer.byteLength)
33258 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
33259 }
33260 offset += 4;
33261 var capacity8 = this.buffer.byteLength;
33262 if (offset > capacity8)
33263 this.resize((capacity8 *= 2) > offset ? capacity8 : offset);
33264 offset -= 4;
33265 ieee754_write(this.view, value, offset, this.littleEndian, 23, 4);
33266 if (relative) this.offset += 4;
33267 return this;
33268 };
33269
33270 /**
33271 * Writes a 32bit float. This is an alias of {@link ByteBuffer#writeFloat32}.
33272 * @function
33273 * @param {number} value Value to write
33274 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
33275 * @returns {!ByteBuffer} this
33276 * @expose
33277 */
33278 ByteBufferPrototype.writeFloat = ByteBufferPrototype.writeFloat32;
33279
33280 /**
33281 * Reads a 32bit float.
33282 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
33283 * @returns {number}
33284 * @expose
33285 */
33286 ByteBufferPrototype.readFloat32 = function(offset) {
33287 var relative = typeof offset === 'undefined';
33288 if (relative) offset = this.offset;
33289 if (!this.noAssert) {
33290 if (typeof offset !== 'number' || offset % 1 !== 0)
33291 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33292 offset >>>= 0;
33293 if (offset < 0 || offset + 4 > this.buffer.byteLength)
33294 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
33295 }
33296 var value = ieee754_read(this.view, offset, this.littleEndian, 23, 4);
33297 if (relative) this.offset += 4;
33298 return value;
33299 };
33300
33301 /**
33302 * Reads a 32bit float. This is an alias of {@link ByteBuffer#readFloat32}.
33303 * @function
33304 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
33305 * @returns {number}
33306 * @expose
33307 */
33308 ByteBufferPrototype.readFloat = ByteBufferPrototype.readFloat32;
33309
33310 // types/floats/float64
33311
33312 /**
33313 * Writes a 64bit float.
33314 * @param {number} value Value to write
33315 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
33316 * @returns {!ByteBuffer} this
33317 * @expose
33318 */
33319 ByteBufferPrototype.writeFloat64 = function(value, offset) {
33320 var relative = typeof offset === 'undefined';
33321 if (relative) offset = this.offset;
33322 if (!this.noAssert) {
33323 if (typeof value !== 'number')
33324 throw TypeError("Illegal value: "+value+" (not a number)");
33325 if (typeof offset !== 'number' || offset % 1 !== 0)
33326 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33327 offset >>>= 0;
33328 if (offset < 0 || offset + 0 > this.buffer.byteLength)
33329 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
33330 }
33331 offset += 8;
33332 var capacity9 = this.buffer.byteLength;
33333 if (offset > capacity9)
33334 this.resize((capacity9 *= 2) > offset ? capacity9 : offset);
33335 offset -= 8;
33336 ieee754_write(this.view, value, offset, this.littleEndian, 52, 8);
33337 if (relative) this.offset += 8;
33338 return this;
33339 };
33340
33341 /**
33342 * Writes a 64bit float. This is an alias of {@link ByteBuffer#writeFloat64}.
33343 * @function
33344 * @param {number} value Value to write
33345 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
33346 * @returns {!ByteBuffer} this
33347 * @expose
33348 */
33349 ByteBufferPrototype.writeDouble = ByteBufferPrototype.writeFloat64;
33350
33351 /**
33352 * Reads a 64bit float.
33353 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
33354 * @returns {number}
33355 * @expose
33356 */
33357 ByteBufferPrototype.readFloat64 = function(offset) {
33358 var relative = typeof offset === 'undefined';
33359 if (relative) offset = this.offset;
33360 if (!this.noAssert) {
33361 if (typeof offset !== 'number' || offset % 1 !== 0)
33362 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33363 offset >>>= 0;
33364 if (offset < 0 || offset + 8 > this.buffer.byteLength)
33365 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
33366 }
33367 var value = ieee754_read(this.view, offset, this.littleEndian, 52, 8);
33368 if (relative) this.offset += 8;
33369 return value;
33370 };
33371
33372 /**
33373 * Reads a 64bit float. This is an alias of {@link ByteBuffer#readFloat64}.
33374 * @function
33375 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
33376 * @returns {number}
33377 * @expose
33378 */
33379 ByteBufferPrototype.readDouble = ByteBufferPrototype.readFloat64;
33380
33381
33382 // types/varints/varint32
33383
33384 /**
33385 * Maximum number of bytes required to store a 32bit base 128 variable-length integer.
33386 * @type {number}
33387 * @const
33388 * @expose
33389 */
33390 ByteBuffer.MAX_VARINT32_BYTES = 5;
33391
33392 /**
33393 * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer.
33394 * @param {number} value Value to encode
33395 * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT32_BYTES}
33396 * @expose
33397 */
33398 ByteBuffer.calculateVarint32 = function(value) {
33399 // ref: src/google/protobuf/io/coded_stream.cc
33400 value = value >>> 0;
33401 if (value < 1 << 7 ) return 1;
33402 else if (value < 1 << 14) return 2;
33403 else if (value < 1 << 21) return 3;
33404 else if (value < 1 << 28) return 4;
33405 else return 5;
33406 };
33407
33408 /**
33409 * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding.
33410 * @param {number} n Signed 32bit integer
33411 * @returns {number} Unsigned zigzag encoded 32bit integer
33412 * @expose
33413 */
33414 ByteBuffer.zigZagEncode32 = function(n) {
33415 return (((n |= 0) << 1) ^ (n >> 31)) >>> 0; // ref: src/google/protobuf/wire_format_lite.h
33416 };
33417
33418 /**
33419 * Decodes a zigzag encoded signed 32bit integer.
33420 * @param {number} n Unsigned zigzag encoded 32bit integer
33421 * @returns {number} Signed 32bit integer
33422 * @expose
33423 */
33424 ByteBuffer.zigZagDecode32 = function(n) {
33425 return ((n >>> 1) ^ -(n & 1)) | 0; // // ref: src/google/protobuf/wire_format_lite.h
33426 };
33427
33428 /**
33429 * Writes a 32bit base 128 variable-length integer.
33430 * @param {number} value Value to write
33431 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
33432 * written if omitted.
33433 * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
33434 * @expose
33435 */
33436 ByteBufferPrototype.writeVarint32 = function(value, offset) {
33437 var relative = typeof offset === 'undefined';
33438 if (relative) offset = this.offset;
33439 if (!this.noAssert) {
33440 if (typeof value !== 'number' || value % 1 !== 0)
33441 throw TypeError("Illegal value: "+value+" (not an integer)");
33442 value |= 0;
33443 if (typeof offset !== 'number' || offset % 1 !== 0)
33444 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33445 offset >>>= 0;
33446 if (offset < 0 || offset + 0 > this.buffer.byteLength)
33447 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
33448 }
33449 var size = ByteBuffer.calculateVarint32(value),
33450 b;
33451 offset += size;
33452 var capacity10 = this.buffer.byteLength;
33453 if (offset > capacity10)
33454 this.resize((capacity10 *= 2) > offset ? capacity10 : offset);
33455 offset -= size;
33456 value >>>= 0;
33457 while (value >= 0x80) {
33458 b = (value & 0x7f) | 0x80;
33459 this.view[offset++] = b;
33460 value >>>= 7;
33461 }
33462 this.view[offset++] = value;
33463 if (relative) {
33464 this.offset = offset;
33465 return this;
33466 }
33467 return size;
33468 };
33469
33470 /**
33471 * Writes a zig-zag encoded (signed) 32bit base 128 variable-length integer.
33472 * @param {number} value Value to write
33473 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
33474 * written if omitted.
33475 * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
33476 * @expose
33477 */
33478 ByteBufferPrototype.writeVarint32ZigZag = function(value, offset) {
33479 return this.writeVarint32(ByteBuffer.zigZagEncode32(value), offset);
33480 };
33481
33482 /**
33483 * Reads a 32bit base 128 variable-length integer.
33484 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
33485 * written if omitted.
33486 * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
33487 * and the actual number of bytes read.
33488 * @throws {Error} If it's not a valid varint. Has a property `truncated = true` if there is not enough data available
33489 * to fully decode the varint.
33490 * @expose
33491 */
33492 ByteBufferPrototype.readVarint32 = function(offset) {
33493 var relative = typeof offset === 'undefined';
33494 if (relative) offset = this.offset;
33495 if (!this.noAssert) {
33496 if (typeof offset !== 'number' || offset % 1 !== 0)
33497 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33498 offset >>>= 0;
33499 if (offset < 0 || offset + 1 > this.buffer.byteLength)
33500 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
33501 }
33502 var c = 0,
33503 value = 0 >>> 0,
33504 b;
33505 do {
33506 if (!this.noAssert && offset > this.limit) {
33507 var err = Error("Truncated");
33508 err['truncated'] = true;
33509 throw err;
33510 }
33511 b = this.view[offset++];
33512 if (c < 5)
33513 value |= (b & 0x7f) << (7*c);
33514 ++c;
33515 } while ((b & 0x80) !== 0);
33516 value |= 0;
33517 if (relative) {
33518 this.offset = offset;
33519 return value;
33520 }
33521 return {
33522 "value": value,
33523 "length": c
33524 };
33525 };
33526
33527 /**
33528 * Reads a zig-zag encoded (signed) 32bit base 128 variable-length integer.
33529 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
33530 * written if omitted.
33531 * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
33532 * and the actual number of bytes read.
33533 * @throws {Error} If it's not a valid varint
33534 * @expose
33535 */
33536 ByteBufferPrototype.readVarint32ZigZag = function(offset) {
33537 var val = this.readVarint32(offset);
33538 if (typeof val === 'object')
33539 val["value"] = ByteBuffer.zigZagDecode32(val["value"]);
33540 else
33541 val = ByteBuffer.zigZagDecode32(val);
33542 return val;
33543 };
33544
33545 // types/varints/varint64
33546
33547 if (Long) {
33548
33549 /**
33550 * Maximum number of bytes required to store a 64bit base 128 variable-length integer.
33551 * @type {number}
33552 * @const
33553 * @expose
33554 */
33555 ByteBuffer.MAX_VARINT64_BYTES = 10;
33556
33557 /**
33558 * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer.
33559 * @param {number|!Long} value Value to encode
33560 * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT64_BYTES}
33561 * @expose
33562 */
33563 ByteBuffer.calculateVarint64 = function(value) {
33564 if (typeof value === 'number')
33565 value = Long.fromNumber(value);
33566 else if (typeof value === 'string')
33567 value = Long.fromString(value);
33568 // ref: src/google/protobuf/io/coded_stream.cc
33569 var part0 = value.toInt() >>> 0,
33570 part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
33571 part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
33572 if (part2 == 0) {
33573 if (part1 == 0) {
33574 if (part0 < 1 << 14)
33575 return part0 < 1 << 7 ? 1 : 2;
33576 else
33577 return part0 < 1 << 21 ? 3 : 4;
33578 } else {
33579 if (part1 < 1 << 14)
33580 return part1 < 1 << 7 ? 5 : 6;
33581 else
33582 return part1 < 1 << 21 ? 7 : 8;
33583 }
33584 } else
33585 return part2 < 1 << 7 ? 9 : 10;
33586 };
33587
33588 /**
33589 * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding.
33590 * @param {number|!Long} value Signed long
33591 * @returns {!Long} Unsigned zigzag encoded long
33592 * @expose
33593 */
33594 ByteBuffer.zigZagEncode64 = function(value) {
33595 if (typeof value === 'number')
33596 value = Long.fromNumber(value, false);
33597 else if (typeof value === 'string')
33598 value = Long.fromString(value, false);
33599 else if (value.unsigned !== false) value = value.toSigned();
33600 // ref: src/google/protobuf/wire_format_lite.h
33601 return value.shiftLeft(1).xor(value.shiftRight(63)).toUnsigned();
33602 };
33603
33604 /**
33605 * Decodes a zigzag encoded signed 64bit integer.
33606 * @param {!Long|number} value Unsigned zigzag encoded long or JavaScript number
33607 * @returns {!Long} Signed long
33608 * @expose
33609 */
33610 ByteBuffer.zigZagDecode64 = function(value) {
33611 if (typeof value === 'number')
33612 value = Long.fromNumber(value, false);
33613 else if (typeof value === 'string')
33614 value = Long.fromString(value, false);
33615 else if (value.unsigned !== false) value = value.toSigned();
33616 // ref: src/google/protobuf/wire_format_lite.h
33617 return value.shiftRightUnsigned(1).xor(value.and(Long.ONE).toSigned().negate()).toSigned();
33618 };
33619
33620 /**
33621 * Writes a 64bit base 128 variable-length integer.
33622 * @param {number|Long} value Value to write
33623 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
33624 * written if omitted.
33625 * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
33626 * @expose
33627 */
33628 ByteBufferPrototype.writeVarint64 = function(value, offset) {
33629 var relative = typeof offset === 'undefined';
33630 if (relative) offset = this.offset;
33631 if (!this.noAssert) {
33632 if (typeof value === 'number')
33633 value = Long.fromNumber(value);
33634 else if (typeof value === 'string')
33635 value = Long.fromString(value);
33636 else if (!(value && value instanceof Long))
33637 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
33638 if (typeof offset !== 'number' || offset % 1 !== 0)
33639 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33640 offset >>>= 0;
33641 if (offset < 0 || offset + 0 > this.buffer.byteLength)
33642 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
33643 }
33644 if (typeof value === 'number')
33645 value = Long.fromNumber(value, false);
33646 else if (typeof value === 'string')
33647 value = Long.fromString(value, false);
33648 else if (value.unsigned !== false) value = value.toSigned();
33649 var size = ByteBuffer.calculateVarint64(value),
33650 part0 = value.toInt() >>> 0,
33651 part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
33652 part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
33653 offset += size;
33654 var capacity11 = this.buffer.byteLength;
33655 if (offset > capacity11)
33656 this.resize((capacity11 *= 2) > offset ? capacity11 : offset);
33657 offset -= size;
33658 switch (size) {
33659 case 10: this.view[offset+9] = (part2 >>> 7) & 0x01;
33660 case 9 : this.view[offset+8] = size !== 9 ? (part2 ) | 0x80 : (part2 ) & 0x7F;
33661 case 8 : this.view[offset+7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F;
33662 case 7 : this.view[offset+6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F;
33663 case 6 : this.view[offset+5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F;
33664 case 5 : this.view[offset+4] = size !== 5 ? (part1 ) | 0x80 : (part1 ) & 0x7F;
33665 case 4 : this.view[offset+3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F;
33666 case 3 : this.view[offset+2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F;
33667 case 2 : this.view[offset+1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F;
33668 case 1 : this.view[offset ] = size !== 1 ? (part0 ) | 0x80 : (part0 ) & 0x7F;
33669 }
33670 if (relative) {
33671 this.offset += size;
33672 return this;
33673 } else {
33674 return size;
33675 }
33676 };
33677
33678 /**
33679 * Writes a zig-zag encoded 64bit base 128 variable-length integer.
33680 * @param {number|Long} value Value to write
33681 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
33682 * written if omitted.
33683 * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
33684 * @expose
33685 */
33686 ByteBufferPrototype.writeVarint64ZigZag = function(value, offset) {
33687 return this.writeVarint64(ByteBuffer.zigZagEncode64(value), offset);
33688 };
33689
33690 /**
33691 * Reads a 64bit base 128 variable-length integer. Requires Long.js.
33692 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
33693 * read if omitted.
33694 * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
33695 * the actual number of bytes read.
33696 * @throws {Error} If it's not a valid varint
33697 * @expose
33698 */
33699 ByteBufferPrototype.readVarint64 = function(offset) {
33700 var relative = typeof offset === 'undefined';
33701 if (relative) offset = this.offset;
33702 if (!this.noAssert) {
33703 if (typeof offset !== 'number' || offset % 1 !== 0)
33704 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33705 offset >>>= 0;
33706 if (offset < 0 || offset + 1 > this.buffer.byteLength)
33707 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
33708 }
33709 // ref: src/google/protobuf/io/coded_stream.cc
33710 var start = offset,
33711 part0 = 0,
33712 part1 = 0,
33713 part2 = 0,
33714 b = 0;
33715 b = this.view[offset++]; part0 = (b & 0x7F) ; if ( b & 0x80 ) {
33716 b = this.view[offset++]; part0 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
33717 b = this.view[offset++]; part0 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
33718 b = this.view[offset++]; part0 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
33719 b = this.view[offset++]; part1 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
33720 b = this.view[offset++]; part1 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
33721 b = this.view[offset++]; part1 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
33722 b = this.view[offset++]; part1 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
33723 b = this.view[offset++]; part2 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
33724 b = this.view[offset++]; part2 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
33725 throw Error("Buffer overrun"); }}}}}}}}}}
33726 var value = Long.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2) << 24, false);
33727 if (relative) {
33728 this.offset = offset;
33729 return value;
33730 } else {
33731 return {
33732 'value': value,
33733 'length': offset-start
33734 };
33735 }
33736 };
33737
33738 /**
33739 * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js.
33740 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
33741 * read if omitted.
33742 * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
33743 * the actual number of bytes read.
33744 * @throws {Error} If it's not a valid varint
33745 * @expose
33746 */
33747 ByteBufferPrototype.readVarint64ZigZag = function(offset) {
33748 var val = this.readVarint64(offset);
33749 if (val && val['value'] instanceof Long)
33750 val["value"] = ByteBuffer.zigZagDecode64(val["value"]);
33751 else
33752 val = ByteBuffer.zigZagDecode64(val);
33753 return val;
33754 };
33755
33756 } // Long
33757
33758
33759 // types/strings/cstring
33760
33761 /**
33762 * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL
33763 * characters itself.
33764 * @param {string} str String to write
33765 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
33766 * contained in `str` + 1 if omitted.
33767 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written
33768 * @expose
33769 */
33770 ByteBufferPrototype.writeCString = function(str, offset) {
33771 var relative = typeof offset === 'undefined';
33772 if (relative) offset = this.offset;
33773 var i,
33774 k = str.length;
33775 if (!this.noAssert) {
33776 if (typeof str !== 'string')
33777 throw TypeError("Illegal str: Not a string");
33778 for (i=0; i<k; ++i) {
33779 if (str.charCodeAt(i) === 0)
33780 throw RangeError("Illegal str: Contains NULL-characters");
33781 }
33782 if (typeof offset !== 'number' || offset % 1 !== 0)
33783 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33784 offset >>>= 0;
33785 if (offset < 0 || offset + 0 > this.buffer.byteLength)
33786 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
33787 }
33788 // UTF8 strings do not contain zero bytes in between except for the zero character, so:
33789 k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
33790 offset += k+1;
33791 var capacity12 = this.buffer.byteLength;
33792 if (offset > capacity12)
33793 this.resize((capacity12 *= 2) > offset ? capacity12 : offset);
33794 offset -= k+1;
33795 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
33796 this.view[offset++] = b;
33797 }.bind(this));
33798 this.view[offset++] = 0;
33799 if (relative) {
33800 this.offset = offset;
33801 return this;
33802 }
33803 return k;
33804 };
33805
33806 /**
33807 * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters
33808 * itself.
33809 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
33810 * read if omitted.
33811 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
33812 * read and the actual number of bytes read.
33813 * @expose
33814 */
33815 ByteBufferPrototype.readCString = function(offset) {
33816 var relative = typeof offset === 'undefined';
33817 if (relative) offset = this.offset;
33818 if (!this.noAssert) {
33819 if (typeof offset !== 'number' || offset % 1 !== 0)
33820 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33821 offset >>>= 0;
33822 if (offset < 0 || offset + 1 > this.buffer.byteLength)
33823 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
33824 }
33825 var start = offset,
33826 temp;
33827 // UTF8 strings do not contain zero bytes in between except for the zero character itself, so:
33828 var sd, b = -1;
33829 utfx.decodeUTF8toUTF16(function() {
33830 if (b === 0) return null;
33831 if (offset >= this.limit)
33832 throw RangeError("Illegal range: Truncated data, "+offset+" < "+this.limit);
33833 b = this.view[offset++];
33834 return b === 0 ? null : b;
33835 }.bind(this), sd = stringDestination(), true);
33836 if (relative) {
33837 this.offset = offset;
33838 return sd();
33839 } else {
33840 return {
33841 "string": sd(),
33842 "length": offset - start
33843 };
33844 }
33845 };
33846
33847 // types/strings/istring
33848
33849 /**
33850 * Writes a length as uint32 prefixed UTF8 encoded string.
33851 * @param {string} str String to write
33852 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
33853 * written if omitted.
33854 * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
33855 * @expose
33856 * @see ByteBuffer#writeVarint32
33857 */
33858 ByteBufferPrototype.writeIString = function(str, offset) {
33859 var relative = typeof offset === 'undefined';
33860 if (relative) offset = this.offset;
33861 if (!this.noAssert) {
33862 if (typeof str !== 'string')
33863 throw TypeError("Illegal str: Not a string");
33864 if (typeof offset !== 'number' || offset % 1 !== 0)
33865 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33866 offset >>>= 0;
33867 if (offset < 0 || offset + 0 > this.buffer.byteLength)
33868 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
33869 }
33870 var start = offset,
33871 k;
33872 k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
33873 offset += 4+k;
33874 var capacity13 = this.buffer.byteLength;
33875 if (offset > capacity13)
33876 this.resize((capacity13 *= 2) > offset ? capacity13 : offset);
33877 offset -= 4+k;
33878 if (this.littleEndian) {
33879 this.view[offset+3] = (k >>> 24) & 0xFF;
33880 this.view[offset+2] = (k >>> 16) & 0xFF;
33881 this.view[offset+1] = (k >>> 8) & 0xFF;
33882 this.view[offset ] = k & 0xFF;
33883 } else {
33884 this.view[offset ] = (k >>> 24) & 0xFF;
33885 this.view[offset+1] = (k >>> 16) & 0xFF;
33886 this.view[offset+2] = (k >>> 8) & 0xFF;
33887 this.view[offset+3] = k & 0xFF;
33888 }
33889 offset += 4;
33890 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
33891 this.view[offset++] = b;
33892 }.bind(this));
33893 if (offset !== start + 4 + k)
33894 throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+4+k));
33895 if (relative) {
33896 this.offset = offset;
33897 return this;
33898 }
33899 return offset - start;
33900 };
33901
33902 /**
33903 * Reads a length as uint32 prefixed UTF8 encoded string.
33904 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
33905 * read if omitted.
33906 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
33907 * read and the actual number of bytes read.
33908 * @expose
33909 * @see ByteBuffer#readVarint32
33910 */
33911 ByteBufferPrototype.readIString = function(offset) {
33912 var relative = typeof offset === 'undefined';
33913 if (relative) offset = this.offset;
33914 if (!this.noAssert) {
33915 if (typeof offset !== 'number' || offset % 1 !== 0)
33916 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33917 offset >>>= 0;
33918 if (offset < 0 || offset + 4 > this.buffer.byteLength)
33919 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
33920 }
33921 var start = offset;
33922 var len = this.readUint32(offset);
33923 var str = this.readUTF8String(len, ByteBuffer.METRICS_BYTES, offset += 4);
33924 offset += str['length'];
33925 if (relative) {
33926 this.offset = offset;
33927 return str['string'];
33928 } else {
33929 return {
33930 'string': str['string'],
33931 'length': offset - start
33932 };
33933 }
33934 };
33935
33936 // types/strings/utf8string
33937
33938 /**
33939 * Metrics representing number of UTF8 characters. Evaluates to `c`.
33940 * @type {string}
33941 * @const
33942 * @expose
33943 */
33944 ByteBuffer.METRICS_CHARS = 'c';
33945
33946 /**
33947 * Metrics representing number of bytes. Evaluates to `b`.
33948 * @type {string}
33949 * @const
33950 * @expose
33951 */
33952 ByteBuffer.METRICS_BYTES = 'b';
33953
33954 /**
33955 * Writes an UTF8 encoded string.
33956 * @param {string} str String to write
33957 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
33958 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
33959 * @expose
33960 */
33961 ByteBufferPrototype.writeUTF8String = function(str, offset) {
33962 var relative = typeof offset === 'undefined';
33963 if (relative) offset = this.offset;
33964 if (!this.noAssert) {
33965 if (typeof offset !== 'number' || offset % 1 !== 0)
33966 throw TypeError("Illegal offset: "+offset+" (not an integer)");
33967 offset >>>= 0;
33968 if (offset < 0 || offset + 0 > this.buffer.byteLength)
33969 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
33970 }
33971 var k;
33972 var start = offset;
33973 k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
33974 offset += k;
33975 var capacity14 = this.buffer.byteLength;
33976 if (offset > capacity14)
33977 this.resize((capacity14 *= 2) > offset ? capacity14 : offset);
33978 offset -= k;
33979 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
33980 this.view[offset++] = b;
33981 }.bind(this));
33982 if (relative) {
33983 this.offset = offset;
33984 return this;
33985 }
33986 return offset - start;
33987 };
33988
33989 /**
33990 * Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}.
33991 * @function
33992 * @param {string} str String to write
33993 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
33994 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
33995 * @expose
33996 */
33997 ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String;
33998
33999 /**
34000 * Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's
34001 * `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
34002 * @param {string} str String to calculate
34003 * @returns {number} Number of UTF8 characters
34004 * @expose
34005 */
34006 ByteBuffer.calculateUTF8Chars = function(str) {
34007 return utfx.calculateUTF16asUTF8(stringSource(str))[0];
34008 };
34009
34010 /**
34011 * Calculates the number of UTF8 bytes of a string.
34012 * @param {string} str String to calculate
34013 * @returns {number} Number of UTF8 bytes
34014 * @expose
34015 */
34016 ByteBuffer.calculateUTF8Bytes = function(str) {
34017 return utfx.calculateUTF16asUTF8(stringSource(str))[1];
34018 };
34019
34020 /**
34021 * Calculates the number of UTF8 bytes of a string. This is an alias of {@link ByteBuffer.calculateUTF8Bytes}.
34022 * @function
34023 * @param {string} str String to calculate
34024 * @returns {number} Number of UTF8 bytes
34025 * @expose
34026 */
34027 ByteBuffer.calculateString = ByteBuffer.calculateUTF8Bytes;
34028
34029 /**
34030 * Reads an UTF8 encoded string.
34031 * @param {number} length Number of characters or bytes to read.
34032 * @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to
34033 * {@link ByteBuffer.METRICS_CHARS}.
34034 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
34035 * read if omitted.
34036 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
34037 * read and the actual number of bytes read.
34038 * @expose
34039 */
34040 ByteBufferPrototype.readUTF8String = function(length, metrics, offset) {
34041 if (typeof metrics === 'number') {
34042 offset = metrics;
34043 metrics = undefined;
34044 }
34045 var relative = typeof offset === 'undefined';
34046 if (relative) offset = this.offset;
34047 if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS;
34048 if (!this.noAssert) {
34049 if (typeof length !== 'number' || length % 1 !== 0)
34050 throw TypeError("Illegal length: "+length+" (not an integer)");
34051 length |= 0;
34052 if (typeof offset !== 'number' || offset % 1 !== 0)
34053 throw TypeError("Illegal offset: "+offset+" (not an integer)");
34054 offset >>>= 0;
34055 if (offset < 0 || offset + 0 > this.buffer.byteLength)
34056 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
34057 }
34058 var i = 0,
34059 start = offset,
34060 sd;
34061 if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser
34062 sd = stringDestination();
34063 utfx.decodeUTF8(function() {
34064 return i < length && offset < this.limit ? this.view[offset++] : null;
34065 }.bind(this), function(cp) {
34066 ++i; utfx.UTF8toUTF16(cp, sd);
34067 });
34068 if (i !== length)
34069 throw RangeError("Illegal range: Truncated data, "+i+" == "+length);
34070 if (relative) {
34071 this.offset = offset;
34072 return sd();
34073 } else {
34074 return {
34075 "string": sd(),
34076 "length": offset - start
34077 };
34078 }
34079 } else if (metrics === ByteBuffer.METRICS_BYTES) {
34080 if (!this.noAssert) {
34081 if (typeof offset !== 'number' || offset % 1 !== 0)
34082 throw TypeError("Illegal offset: "+offset+" (not an integer)");
34083 offset >>>= 0;
34084 if (offset < 0 || offset + length > this.buffer.byteLength)
34085 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
34086 }
34087 var k = offset + length;
34088 utfx.decodeUTF8toUTF16(function() {
34089 return offset < k ? this.view[offset++] : null;
34090 }.bind(this), sd = stringDestination(), this.noAssert);
34091 if (offset !== k)
34092 throw RangeError("Illegal range: Truncated data, "+offset+" == "+k);
34093 if (relative) {
34094 this.offset = offset;
34095 return sd();
34096 } else {
34097 return {
34098 'string': sd(),
34099 'length': offset - start
34100 };
34101 }
34102 } else
34103 throw TypeError("Unsupported metrics: "+metrics);
34104 };
34105
34106 /**
34107 * Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}.
34108 * @function
34109 * @param {number} length Number of characters or bytes to read
34110 * @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to
34111 * {@link ByteBuffer.METRICS_CHARS}.
34112 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
34113 * read if omitted.
34114 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
34115 * read and the actual number of bytes read.
34116 * @expose
34117 */
34118 ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String;
34119
34120 // types/strings/vstring
34121
34122 /**
34123 * Writes a length as varint32 prefixed UTF8 encoded string.
34124 * @param {string} str String to write
34125 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
34126 * written if omitted.
34127 * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
34128 * @expose
34129 * @see ByteBuffer#writeVarint32
34130 */
34131 ByteBufferPrototype.writeVString = function(str, offset) {
34132 var relative = typeof offset === 'undefined';
34133 if (relative) offset = this.offset;
34134 if (!this.noAssert) {
34135 if (typeof str !== 'string')
34136 throw TypeError("Illegal str: Not a string");
34137 if (typeof offset !== 'number' || offset % 1 !== 0)
34138 throw TypeError("Illegal offset: "+offset+" (not an integer)");
34139 offset >>>= 0;
34140 if (offset < 0 || offset + 0 > this.buffer.byteLength)
34141 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
34142 }
34143 var start = offset,
34144 k, l;
34145 k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
34146 l = ByteBuffer.calculateVarint32(k);
34147 offset += l+k;
34148 var capacity15 = this.buffer.byteLength;
34149 if (offset > capacity15)
34150 this.resize((capacity15 *= 2) > offset ? capacity15 : offset);
34151 offset -= l+k;
34152 offset += this.writeVarint32(k, offset);
34153 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
34154 this.view[offset++] = b;
34155 }.bind(this));
34156 if (offset !== start+k+l)
34157 throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+k+l));
34158 if (relative) {
34159 this.offset = offset;
34160 return this;
34161 }
34162 return offset - start;
34163 };
34164
34165 /**
34166 * Reads a length as varint32 prefixed UTF8 encoded string.
34167 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
34168 * read if omitted.
34169 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
34170 * read and the actual number of bytes read.
34171 * @expose
34172 * @see ByteBuffer#readVarint32
34173 */
34174 ByteBufferPrototype.readVString = function(offset) {
34175 var relative = typeof offset === 'undefined';
34176 if (relative) offset = this.offset;
34177 if (!this.noAssert) {
34178 if (typeof offset !== 'number' || offset % 1 !== 0)
34179 throw TypeError("Illegal offset: "+offset+" (not an integer)");
34180 offset >>>= 0;
34181 if (offset < 0 || offset + 1 > this.buffer.byteLength)
34182 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
34183 }
34184 var start = offset;
34185 var len = this.readVarint32(offset);
34186 var str = this.readUTF8String(len['value'], ByteBuffer.METRICS_BYTES, offset += len['length']);
34187 offset += str['length'];
34188 if (relative) {
34189 this.offset = offset;
34190 return str['string'];
34191 } else {
34192 return {
34193 'string': str['string'],
34194 'length': offset - start
34195 };
34196 }
34197 };
34198
34199
34200 /**
34201 * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended
34202 * data's length.
34203 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to append. If `source` is a ByteBuffer, its offsets
34204 * will be modified according to the performed read operation.
34205 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
34206 * @param {number=} offset Offset to append at. Will use and increase {@link ByteBuffer#offset} by the number of bytes
34207 * written if omitted.
34208 * @returns {!ByteBuffer} this
34209 * @expose
34210 * @example A relative `<01 02>03.append(<04 05>)` will result in `<01 02 04 05>, 04 05|`
34211 * @example An absolute `<01 02>03.append(04 05>, 1)` will result in `<01 04>05, 04 05|`
34212 */
34213 ByteBufferPrototype.append = function(source, encoding, offset) {
34214 if (typeof encoding === 'number' || typeof encoding !== 'string') {
34215 offset = encoding;
34216 encoding = undefined;
34217 }
34218 var relative = typeof offset === 'undefined';
34219 if (relative) offset = this.offset;
34220 if (!this.noAssert) {
34221 if (typeof offset !== 'number' || offset % 1 !== 0)
34222 throw TypeError("Illegal offset: "+offset+" (not an integer)");
34223 offset >>>= 0;
34224 if (offset < 0 || offset + 0 > this.buffer.byteLength)
34225 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
34226 }
34227 if (!(source instanceof ByteBuffer))
34228 source = ByteBuffer.wrap(source, encoding);
34229 var length = source.limit - source.offset;
34230 if (length <= 0) return this; // Nothing to append
34231 offset += length;
34232 var capacity16 = this.buffer.byteLength;
34233 if (offset > capacity16)
34234 this.resize((capacity16 *= 2) > offset ? capacity16 : offset);
34235 offset -= length;
34236 this.view.set(source.view.subarray(source.offset, source.limit), offset);
34237 source.offset += length;
34238 if (relative) this.offset += length;
34239 return this;
34240 };
34241
34242 /**
34243 * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents at and after the
34244 specified offset up to the length of this ByteBuffer's data.
34245 * @param {!ByteBuffer} target Target ByteBuffer
34246 * @param {number=} offset Offset to append to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
34247 * read if omitted.
34248 * @returns {!ByteBuffer} this
34249 * @expose
34250 * @see ByteBuffer#append
34251 */
34252 ByteBufferPrototype.appendTo = function(target, offset) {
34253 target.append(this, offset);
34254 return this;
34255 };
34256
34257 /**
34258 * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to
34259 * disable them if your code already makes sure that everything is valid.
34260 * @param {boolean} assert `true` to enable assertions, otherwise `false`
34261 * @returns {!ByteBuffer} this
34262 * @expose
34263 */
34264 ByteBufferPrototype.assert = function(assert) {
34265 this.noAssert = !assert;
34266 return this;
34267 };
34268
34269 /**
34270 * Gets the capacity of this ByteBuffer's backing buffer.
34271 * @returns {number} Capacity of the backing buffer
34272 * @expose
34273 */
34274 ByteBufferPrototype.capacity = function() {
34275 return this.buffer.byteLength;
34276 };
34277 /**
34278 * Clears this ByteBuffer's offsets by setting {@link ByteBuffer#offset} to `0` and {@link ByteBuffer#limit} to the
34279 * backing buffer's capacity. Discards {@link ByteBuffer#markedOffset}.
34280 * @returns {!ByteBuffer} this
34281 * @expose
34282 */
34283 ByteBufferPrototype.clear = function() {
34284 this.offset = 0;
34285 this.limit = this.buffer.byteLength;
34286 this.markedOffset = -1;
34287 return this;
34288 };
34289
34290 /**
34291 * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for {@link ByteBuffer#offset},
34292 * {@link ByteBuffer#markedOffset} and {@link ByteBuffer#limit}.
34293 * @param {boolean=} copy Whether to copy the backing buffer or to return another view on the same, defaults to `false`
34294 * @returns {!ByteBuffer} Cloned instance
34295 * @expose
34296 */
34297 ByteBufferPrototype.clone = function(copy) {
34298 var bb = new ByteBuffer(0, this.littleEndian, this.noAssert);
34299 if (copy) {
34300 bb.buffer = new ArrayBuffer(this.buffer.byteLength);
34301 bb.view = new Uint8Array(bb.buffer);
34302 } else {
34303 bb.buffer = this.buffer;
34304 bb.view = this.view;
34305 }
34306 bb.offset = this.offset;
34307 bb.markedOffset = this.markedOffset;
34308 bb.limit = this.limit;
34309 return bb;
34310 };
34311
34312 /**
34313 * Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes
34314 * between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and
34315 * adapt {@link ByteBuffer#markedOffset} to the same relative position if set.
34316 * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
34317 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
34318 * @returns {!ByteBuffer} this
34319 * @expose
34320 */
34321 ByteBufferPrototype.compact = function(begin, end) {
34322 if (typeof begin === 'undefined') begin = this.offset;
34323 if (typeof end === 'undefined') end = this.limit;
34324 if (!this.noAssert) {
34325 if (typeof begin !== 'number' || begin % 1 !== 0)
34326 throw TypeError("Illegal begin: Not an integer");
34327 begin >>>= 0;
34328 if (typeof end !== 'number' || end % 1 !== 0)
34329 throw TypeError("Illegal end: Not an integer");
34330 end >>>= 0;
34331 if (begin < 0 || begin > end || end > this.buffer.byteLength)
34332 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
34333 }
34334 if (begin === 0 && end === this.buffer.byteLength)
34335 return this; // Already compacted
34336 var len = end - begin;
34337 if (len === 0) {
34338 this.buffer = EMPTY_BUFFER;
34339 this.view = null;
34340 if (this.markedOffset >= 0) this.markedOffset -= begin;
34341 this.offset = 0;
34342 this.limit = 0;
34343 return this;
34344 }
34345 var buffer = new ArrayBuffer(len);
34346 var view = new Uint8Array(buffer);
34347 view.set(this.view.subarray(begin, end));
34348 this.buffer = buffer;
34349 this.view = view;
34350 if (this.markedOffset >= 0) this.markedOffset -= begin;
34351 this.offset = 0;
34352 this.limit = len;
34353 return this;
34354 };
34355
34356 /**
34357 * Creates a copy of this ByteBuffer's contents. Contents are the bytes between {@link ByteBuffer#offset} and
34358 * {@link ByteBuffer#limit}.
34359 * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
34360 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
34361 * @returns {!ByteBuffer} Copy
34362 * @expose
34363 */
34364 ByteBufferPrototype.copy = function(begin, end) {
34365 if (typeof begin === 'undefined') begin = this.offset;
34366 if (typeof end === 'undefined') end = this.limit;
34367 if (!this.noAssert) {
34368 if (typeof begin !== 'number' || begin % 1 !== 0)
34369 throw TypeError("Illegal begin: Not an integer");
34370 begin >>>= 0;
34371 if (typeof end !== 'number' || end % 1 !== 0)
34372 throw TypeError("Illegal end: Not an integer");
34373 end >>>= 0;
34374 if (begin < 0 || begin > end || end > this.buffer.byteLength)
34375 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
34376 }
34377 if (begin === end)
34378 return new ByteBuffer(0, this.littleEndian, this.noAssert);
34379 var capacity = end - begin,
34380 bb = new ByteBuffer(capacity, this.littleEndian, this.noAssert);
34381 bb.offset = 0;
34382 bb.limit = capacity;
34383 if (bb.markedOffset >= 0) bb.markedOffset -= begin;
34384 this.copyTo(bb, 0, begin, end);
34385 return bb;
34386 };
34387
34388 /**
34389 * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between {@link ByteBuffer#offset} and
34390 * {@link ByteBuffer#limit}.
34391 * @param {!ByteBuffer} target Target ByteBuffer
34392 * @param {number=} targetOffset Offset to copy to. Will use and increase the target's {@link ByteBuffer#offset}
34393 * by the number of bytes copied if omitted.
34394 * @param {number=} sourceOffset Offset to start copying from. Will use and increase {@link ByteBuffer#offset} by the
34395 * number of bytes copied if omitted.
34396 * @param {number=} sourceLimit Offset to end copying from, defaults to {@link ByteBuffer#limit}
34397 * @returns {!ByteBuffer} this
34398 * @expose
34399 */
34400 ByteBufferPrototype.copyTo = function(target, targetOffset, sourceOffset, sourceLimit) {
34401 var relative,
34402 targetRelative;
34403 if (!this.noAssert) {
34404 if (!ByteBuffer.isByteBuffer(target))
34405 throw TypeError("Illegal target: Not a ByteBuffer");
34406 }
34407 targetOffset = (targetRelative = typeof targetOffset === 'undefined') ? target.offset : targetOffset | 0;
34408 sourceOffset = (relative = typeof sourceOffset === 'undefined') ? this.offset : sourceOffset | 0;
34409 sourceLimit = typeof sourceLimit === 'undefined' ? this.limit : sourceLimit | 0;
34410
34411 if (targetOffset < 0 || targetOffset > target.buffer.byteLength)
34412 throw RangeError("Illegal target range: 0 <= "+targetOffset+" <= "+target.buffer.byteLength);
34413 if (sourceOffset < 0 || sourceLimit > this.buffer.byteLength)
34414 throw RangeError("Illegal source range: 0 <= "+sourceOffset+" <= "+this.buffer.byteLength);
34415
34416 var len = sourceLimit - sourceOffset;
34417 if (len === 0)
34418 return target; // Nothing to copy
34419
34420 target.ensureCapacity(targetOffset + len);
34421
34422 target.view.set(this.view.subarray(sourceOffset, sourceLimit), targetOffset);
34423
34424 if (relative) this.offset += len;
34425 if (targetRelative) target.offset += len;
34426
34427 return this;
34428 };
34429
34430 /**
34431 * Makes sure that this ByteBuffer is backed by a {@link ByteBuffer#buffer} of at least the specified capacity. If the
34432 * current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity,
34433 * the required capacity will be used instead.
34434 * @param {number} capacity Required capacity
34435 * @returns {!ByteBuffer} this
34436 * @expose
34437 */
34438 ByteBufferPrototype.ensureCapacity = function(capacity) {
34439 var current = this.buffer.byteLength;
34440 if (current < capacity)
34441 return this.resize((current *= 2) > capacity ? current : capacity);
34442 return this;
34443 };
34444
34445 /**
34446 * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between
34447 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
34448 * @param {number|string} value Byte value to fill with. If given as a string, the first character is used.
34449 * @param {number=} begin Begin offset. Will use and increase {@link ByteBuffer#offset} by the number of bytes
34450 * written if omitted. defaults to {@link ByteBuffer#offset}.
34451 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
34452 * @returns {!ByteBuffer} this
34453 * @expose
34454 * @example `someByteBuffer.clear().fill(0)` fills the entire backing buffer with zeroes
34455 */
34456 ByteBufferPrototype.fill = function(value, begin, end) {
34457 var relative = typeof begin === 'undefined';
34458 if (relative) begin = this.offset;
34459 if (typeof value === 'string' && value.length > 0)
34460 value = value.charCodeAt(0);
34461 if (typeof begin === 'undefined') begin = this.offset;
34462 if (typeof end === 'undefined') end = this.limit;
34463 if (!this.noAssert) {
34464 if (typeof value !== 'number' || value % 1 !== 0)
34465 throw TypeError("Illegal value: "+value+" (not an integer)");
34466 value |= 0;
34467 if (typeof begin !== 'number' || begin % 1 !== 0)
34468 throw TypeError("Illegal begin: Not an integer");
34469 begin >>>= 0;
34470 if (typeof end !== 'number' || end % 1 !== 0)
34471 throw TypeError("Illegal end: Not an integer");
34472 end >>>= 0;
34473 if (begin < 0 || begin > end || end > this.buffer.byteLength)
34474 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
34475 }
34476 if (begin >= end)
34477 return this; // Nothing to fill
34478 while (begin < end) this.view[begin++] = value;
34479 if (relative) this.offset = begin;
34480 return this;
34481 };
34482
34483 /**
34484 * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets `limit = offset` and
34485 * `offset = 0`. Make sure always to flip a ByteBuffer when all relative read or write operations are complete.
34486 * @returns {!ByteBuffer} this
34487 * @expose
34488 */
34489 ByteBufferPrototype.flip = function() {
34490 this.limit = this.offset;
34491 this.offset = 0;
34492 return this;
34493 };
34494 /**
34495 * Marks an offset on this ByteBuffer to be used later.
34496 * @param {number=} offset Offset to mark. Defaults to {@link ByteBuffer#offset}.
34497 * @returns {!ByteBuffer} this
34498 * @throws {TypeError} If `offset` is not a valid number
34499 * @throws {RangeError} If `offset` is out of bounds
34500 * @see ByteBuffer#reset
34501 * @expose
34502 */
34503 ByteBufferPrototype.mark = function(offset) {
34504 offset = typeof offset === 'undefined' ? this.offset : offset;
34505 if (!this.noAssert) {
34506 if (typeof offset !== 'number' || offset % 1 !== 0)
34507 throw TypeError("Illegal offset: "+offset+" (not an integer)");
34508 offset >>>= 0;
34509 if (offset < 0 || offset + 0 > this.buffer.byteLength)
34510 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
34511 }
34512 this.markedOffset = offset;
34513 return this;
34514 };
34515 /**
34516 * Sets the byte order.
34517 * @param {boolean} littleEndian `true` for little endian byte order, `false` for big endian
34518 * @returns {!ByteBuffer} this
34519 * @expose
34520 */
34521 ByteBufferPrototype.order = function(littleEndian) {
34522 if (!this.noAssert) {
34523 if (typeof littleEndian !== 'boolean')
34524 throw TypeError("Illegal littleEndian: Not a boolean");
34525 }
34526 this.littleEndian = !!littleEndian;
34527 return this;
34528 };
34529
34530 /**
34531 * Switches (to) little endian byte order.
34532 * @param {boolean=} littleEndian Defaults to `true`, otherwise uses big endian
34533 * @returns {!ByteBuffer} this
34534 * @expose
34535 */
34536 ByteBufferPrototype.LE = function(littleEndian) {
34537 this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : true;
34538 return this;
34539 };
34540
34541 /**
34542 * Switches (to) big endian byte order.
34543 * @param {boolean=} bigEndian Defaults to `true`, otherwise uses little endian
34544 * @returns {!ByteBuffer} this
34545 * @expose
34546 */
34547 ByteBufferPrototype.BE = function(bigEndian) {
34548 this.littleEndian = typeof bigEndian !== 'undefined' ? !bigEndian : false;
34549 return this;
34550 };
34551 /**
34552 * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the
34553 * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
34554 * will be resized and its contents moved accordingly.
34555 * @param {!ByteBuffer|string|!ArrayBuffer} source Data to prepend. If `source` is a ByteBuffer, its offset will be
34556 * modified according to the performed read operation.
34557 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
34558 * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
34559 * prepended if omitted.
34560 * @returns {!ByteBuffer} this
34561 * @expose
34562 * @example A relative `00<01 02 03>.prepend(<04 05>)` results in `<04 05 01 02 03>, 04 05|`
34563 * @example An absolute `00<01 02 03>.prepend(<04 05>, 2)` results in `04<05 02 03>, 04 05|`
34564 */
34565 ByteBufferPrototype.prepend = function(source, encoding, offset) {
34566 if (typeof encoding === 'number' || typeof encoding !== 'string') {
34567 offset = encoding;
34568 encoding = undefined;
34569 }
34570 var relative = typeof offset === 'undefined';
34571 if (relative) offset = this.offset;
34572 if (!this.noAssert) {
34573 if (typeof offset !== 'number' || offset % 1 !== 0)
34574 throw TypeError("Illegal offset: "+offset+" (not an integer)");
34575 offset >>>= 0;
34576 if (offset < 0 || offset + 0 > this.buffer.byteLength)
34577 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
34578 }
34579 if (!(source instanceof ByteBuffer))
34580 source = ByteBuffer.wrap(source, encoding);
34581 var len = source.limit - source.offset;
34582 if (len <= 0) return this; // Nothing to prepend
34583 var diff = len - offset;
34584 if (diff > 0) { // Not enough space before offset, so resize + move
34585 var buffer = new ArrayBuffer(this.buffer.byteLength + diff);
34586 var view = new Uint8Array(buffer);
34587 view.set(this.view.subarray(offset, this.buffer.byteLength), len);
34588 this.buffer = buffer;
34589 this.view = view;
34590 this.offset += diff;
34591 if (this.markedOffset >= 0) this.markedOffset += diff;
34592 this.limit += diff;
34593 offset += diff;
34594 } else {
34595 var arrayView = new Uint8Array(this.buffer);
34596 }
34597 this.view.set(source.view.subarray(source.offset, source.limit), offset - len);
34598
34599 source.offset = source.limit;
34600 if (relative)
34601 this.offset -= len;
34602 return this;
34603 };
34604
34605 /**
34606 * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the
34607 * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
34608 * will be resized and its contents moved accordingly.
34609 * @param {!ByteBuffer} target Target ByteBuffer
34610 * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
34611 * prepended if omitted.
34612 * @returns {!ByteBuffer} this
34613 * @expose
34614 * @see ByteBuffer#prepend
34615 */
34616 ByteBufferPrototype.prependTo = function(target, offset) {
34617 target.prepend(this, offset);
34618 return this;
34619 };
34620 /**
34621 * Prints debug information about this ByteBuffer's contents.
34622 * @param {function(string)=} out Output function to call, defaults to console.log
34623 * @expose
34624 */
34625 ByteBufferPrototype.printDebug = function(out) {
34626 if (typeof out !== 'function') out = console.log.bind(console);
34627 out(
34628 this.toString()+"\n"+
34629 "-------------------------------------------------------------------\n"+
34630 this.toDebug(/* columns */ true)
34631 );
34632 };
34633
34634 /**
34635 * Gets the number of remaining readable bytes. Contents are the bytes between {@link ByteBuffer#offset} and
34636 * {@link ByteBuffer#limit}, so this returns `limit - offset`.
34637 * @returns {number} Remaining readable bytes. May be negative if `offset > limit`.
34638 * @expose
34639 */
34640 ByteBufferPrototype.remaining = function() {
34641 return this.limit - this.offset;
34642 };
34643 /**
34644 * Resets this ByteBuffer's {@link ByteBuffer#offset}. If an offset has been marked through {@link ByteBuffer#mark}
34645 * before, `offset` will be set to {@link ByteBuffer#markedOffset}, which will then be discarded. If no offset has been
34646 * marked, sets `offset = 0`.
34647 * @returns {!ByteBuffer} this
34648 * @see ByteBuffer#mark
34649 * @expose
34650 */
34651 ByteBufferPrototype.reset = function() {
34652 if (this.markedOffset >= 0) {
34653 this.offset = this.markedOffset;
34654 this.markedOffset = -1;
34655 } else {
34656 this.offset = 0;
34657 }
34658 return this;
34659 };
34660 /**
34661 * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that
34662 * large or larger.
34663 * @param {number} capacity Capacity required
34664 * @returns {!ByteBuffer} this
34665 * @throws {TypeError} If `capacity` is not a number
34666 * @throws {RangeError} If `capacity < 0`
34667 * @expose
34668 */
34669 ByteBufferPrototype.resize = function(capacity) {
34670 if (!this.noAssert) {
34671 if (typeof capacity !== 'number' || capacity % 1 !== 0)
34672 throw TypeError("Illegal capacity: "+capacity+" (not an integer)");
34673 capacity |= 0;
34674 if (capacity < 0)
34675 throw RangeError("Illegal capacity: 0 <= "+capacity);
34676 }
34677 if (this.buffer.byteLength < capacity) {
34678 var buffer = new ArrayBuffer(capacity);
34679 var view = new Uint8Array(buffer);
34680 view.set(this.view);
34681 this.buffer = buffer;
34682 this.view = view;
34683 }
34684 return this;
34685 };
34686 /**
34687 * Reverses this ByteBuffer's contents.
34688 * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
34689 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
34690 * @returns {!ByteBuffer} this
34691 * @expose
34692 */
34693 ByteBufferPrototype.reverse = function(begin, end) {
34694 if (typeof begin === 'undefined') begin = this.offset;
34695 if (typeof end === 'undefined') end = this.limit;
34696 if (!this.noAssert) {
34697 if (typeof begin !== 'number' || begin % 1 !== 0)
34698 throw TypeError("Illegal begin: Not an integer");
34699 begin >>>= 0;
34700 if (typeof end !== 'number' || end % 1 !== 0)
34701 throw TypeError("Illegal end: Not an integer");
34702 end >>>= 0;
34703 if (begin < 0 || begin > end || end > this.buffer.byteLength)
34704 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
34705 }
34706 if (begin === end)
34707 return this; // Nothing to reverse
34708 Array.prototype.reverse.call(this.view.subarray(begin, end));
34709 return this;
34710 };
34711 /**
34712 * Skips the next `length` bytes. This will just advance
34713 * @param {number} length Number of bytes to skip. May also be negative to move the offset back.
34714 * @returns {!ByteBuffer} this
34715 * @expose
34716 */
34717 ByteBufferPrototype.skip = function(length) {
34718 if (!this.noAssert) {
34719 if (typeof length !== 'number' || length % 1 !== 0)
34720 throw TypeError("Illegal length: "+length+" (not an integer)");
34721 length |= 0;
34722 }
34723 var offset = this.offset + length;
34724 if (!this.noAssert) {
34725 if (offset < 0 || offset > this.buffer.byteLength)
34726 throw RangeError("Illegal length: 0 <= "+this.offset+" + "+length+" <= "+this.buffer.byteLength);
34727 }
34728 this.offset = offset;
34729 return this;
34730 };
34731
34732 /**
34733 * Slices this ByteBuffer by creating a cloned instance with `offset = begin` and `limit = end`.
34734 * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
34735 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
34736 * @returns {!ByteBuffer} Clone of this ByteBuffer with slicing applied, backed by the same {@link ByteBuffer#buffer}
34737 * @expose
34738 */
34739 ByteBufferPrototype.slice = function(begin, end) {
34740 if (typeof begin === 'undefined') begin = this.offset;
34741 if (typeof end === 'undefined') end = this.limit;
34742 if (!this.noAssert) {
34743 if (typeof begin !== 'number' || begin % 1 !== 0)
34744 throw TypeError("Illegal begin: Not an integer");
34745 begin >>>= 0;
34746 if (typeof end !== 'number' || end % 1 !== 0)
34747 throw TypeError("Illegal end: Not an integer");
34748 end >>>= 0;
34749 if (begin < 0 || begin > end || end > this.buffer.byteLength)
34750 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
34751 }
34752 var bb = this.clone();
34753 bb.offset = begin;
34754 bb.limit = end;
34755 return bb;
34756 };
34757 /**
34758 * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between
34759 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
34760 * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if
34761 * possible. Defaults to `false`
34762 * @returns {!ArrayBuffer} Contents as an ArrayBuffer
34763 * @expose
34764 */
34765 ByteBufferPrototype.toBuffer = function(forceCopy) {
34766 var offset = this.offset,
34767 limit = this.limit;
34768 if (!this.noAssert) {
34769 if (typeof offset !== 'number' || offset % 1 !== 0)
34770 throw TypeError("Illegal offset: Not an integer");
34771 offset >>>= 0;
34772 if (typeof limit !== 'number' || limit % 1 !== 0)
34773 throw TypeError("Illegal limit: Not an integer");
34774 limit >>>= 0;
34775 if (offset < 0 || offset > limit || limit > this.buffer.byteLength)
34776 throw RangeError("Illegal range: 0 <= "+offset+" <= "+limit+" <= "+this.buffer.byteLength);
34777 }
34778 // NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is
34779 // possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So:
34780 if (!forceCopy && offset === 0 && limit === this.buffer.byteLength)
34781 return this.buffer;
34782 if (offset === limit)
34783 return EMPTY_BUFFER;
34784 var buffer = new ArrayBuffer(limit - offset);
34785 new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0);
34786 return buffer;
34787 };
34788
34789 /**
34790 * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between
34791 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}.
34792 * @function
34793 * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory.
34794 * Defaults to `false`
34795 * @returns {!ArrayBuffer} Contents as an ArrayBuffer
34796 * @expose
34797 */
34798 ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer;
34799
34800 /**
34801 * Converts the ByteBuffer's contents to a string.
34802 * @param {string=} encoding Output encoding. Returns an informative string representation if omitted but also allows
34803 * direct conversion to "utf8", "hex", "base64" and "binary" encoding. "debug" returns a hex representation with
34804 * highlighted offsets.
34805 * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}
34806 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
34807 * @returns {string} String representation
34808 * @throws {Error} If `encoding` is invalid
34809 * @expose
34810 */
34811 ByteBufferPrototype.toString = function(encoding, begin, end) {
34812 if (typeof encoding === 'undefined')
34813 return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";
34814 if (typeof encoding === 'number')
34815 encoding = "utf8",
34816 begin = encoding,
34817 end = begin;
34818 switch (encoding) {
34819 case "utf8":
34820 return this.toUTF8(begin, end);
34821 case "base64":
34822 return this.toBase64(begin, end);
34823 case "hex":
34824 return this.toHex(begin, end);
34825 case "binary":
34826 return this.toBinary(begin, end);
34827 case "debug":
34828 return this.toDebug();
34829 case "columns":
34830 return this.toColumns();
34831 default:
34832 throw Error("Unsupported encoding: "+encoding);
34833 }
34834 };
34835
34836 // lxiv-embeddable
34837
34838 /**
34839 * lxiv-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
34840 * Released under the Apache License, Version 2.0
34841 * see: https://github.com/dcodeIO/lxiv for details
34842 */
34843 var lxiv = function() {
34844 "use strict";
34845
34846 /**
34847 * lxiv namespace.
34848 * @type {!Object.<string,*>}
34849 * @exports lxiv
34850 */
34851 var lxiv = {};
34852
34853 /**
34854 * Character codes for output.
34855 * @type {!Array.<number>}
34856 * @inner
34857 */
34858 var aout = [
34859 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
34860 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102,
34861 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
34862 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47
34863 ];
34864
34865 /**
34866 * Character codes for input.
34867 * @type {!Array.<number>}
34868 * @inner
34869 */
34870 var ain = [];
34871 for (var i=0, k=aout.length; i<k; ++i)
34872 ain[aout[i]] = i;
34873
34874 /**
34875 * Encodes bytes to base64 char codes.
34876 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if
34877 * there are no more bytes left.
34878 * @param {!function(number)} dst Characters destination as a function successively called with each encoded char
34879 * code.
34880 */
34881 lxiv.encode = function(src, dst) {
34882 var b, t;
34883 while ((b = src()) !== null) {
34884 dst(aout[(b>>2)&0x3f]);
34885 t = (b&0x3)<<4;
34886 if ((b = src()) !== null) {
34887 t |= (b>>4)&0xf;
34888 dst(aout[(t|((b>>4)&0xf))&0x3f]);
34889 t = (b&0xf)<<2;
34890 if ((b = src()) !== null)
34891 dst(aout[(t|((b>>6)&0x3))&0x3f]),
34892 dst(aout[b&0x3f]);
34893 else
34894 dst(aout[t&0x3f]),
34895 dst(61);
34896 } else
34897 dst(aout[t&0x3f]),
34898 dst(61),
34899 dst(61);
34900 }
34901 };
34902
34903 /**
34904 * Decodes base64 char codes to bytes.
34905 * @param {!function():number|null} src Characters source as a function returning the next char code respectively
34906 * `null` if there are no more characters left.
34907 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
34908 * @throws {Error} If a character code is invalid
34909 */
34910 lxiv.decode = function(src, dst) {
34911 var c, t1, t2;
34912 function fail(c) {
34913 throw Error("Illegal character code: "+c);
34914 }
34915 while ((c = src()) !== null) {
34916 t1 = ain[c];
34917 if (typeof t1 === 'undefined') fail(c);
34918 if ((c = src()) !== null) {
34919 t2 = ain[c];
34920 if (typeof t2 === 'undefined') fail(c);
34921 dst((t1<<2)>>>0|(t2&0x30)>>4);
34922 if ((c = src()) !== null) {
34923 t1 = ain[c];
34924 if (typeof t1 === 'undefined')
34925 if (c === 61) break; else fail(c);
34926 dst(((t2&0xf)<<4)>>>0|(t1&0x3c)>>2);
34927 if ((c = src()) !== null) {
34928 t2 = ain[c];
34929 if (typeof t2 === 'undefined')
34930 if (c === 61) break; else fail(c);
34931 dst(((t1&0x3)<<6)>>>0|t2);
34932 }
34933 }
34934 }
34935 }
34936 };
34937
34938 /**
34939 * Tests if a string is valid base64.
34940 * @param {string} str String to test
34941 * @returns {boolean} `true` if valid, otherwise `false`
34942 */
34943 lxiv.test = function(str) {
34944 return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str);
34945 };
34946
34947 return lxiv;
34948 }();
34949
34950 // encodings/base64
34951
34952 /**
34953 * Encodes this ByteBuffer's contents to a base64 encoded string.
34954 * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}.
34955 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}.
34956 * @returns {string} Base64 encoded string
34957 * @throws {RangeError} If `begin` or `end` is out of bounds
34958 * @expose
34959 */
34960 ByteBufferPrototype.toBase64 = function(begin, end) {
34961 if (typeof begin === 'undefined')
34962 begin = this.offset;
34963 if (typeof end === 'undefined')
34964 end = this.limit;
34965 begin = begin | 0; end = end | 0;
34966 if (begin < 0 || end > this.capacity || begin > end)
34967 throw RangeError("begin, end");
34968 var sd; lxiv.encode(function() {
34969 return begin < end ? this.view[begin++] : null;
34970 }.bind(this), sd = stringDestination());
34971 return sd();
34972 };
34973
34974 /**
34975 * Decodes a base64 encoded string to a ByteBuffer.
34976 * @param {string} str String to decode
34977 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
34978 * {@link ByteBuffer.DEFAULT_ENDIAN}.
34979 * @returns {!ByteBuffer} ByteBuffer
34980 * @expose
34981 */
34982 ByteBuffer.fromBase64 = function(str, littleEndian) {
34983 if (typeof str !== 'string')
34984 throw TypeError("str");
34985 var bb = new ByteBuffer(str.length/4*3, littleEndian),
34986 i = 0;
34987 lxiv.decode(stringSource(str), function(b) {
34988 bb.view[i++] = b;
34989 });
34990 bb.limit = i;
34991 return bb;
34992 };
34993
34994 /**
34995 * Encodes a binary string to base64 like `window.btoa` does.
34996 * @param {string} str Binary string
34997 * @returns {string} Base64 encoded string
34998 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa
34999 * @expose
35000 */
35001 ByteBuffer.btoa = function(str) {
35002 return ByteBuffer.fromBinary(str).toBase64();
35003 };
35004
35005 /**
35006 * Decodes a base64 encoded string to binary like `window.atob` does.
35007 * @param {string} b64 Base64 encoded string
35008 * @returns {string} Binary string
35009 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.atob
35010 * @expose
35011 */
35012 ByteBuffer.atob = function(b64) {
35013 return ByteBuffer.fromBase64(b64).toBinary();
35014 };
35015
35016 // encodings/binary
35017
35018 /**
35019 * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes.
35020 * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
35021 * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
35022 * @returns {string} Binary encoded string
35023 * @throws {RangeError} If `offset > limit`
35024 * @expose
35025 */
35026 ByteBufferPrototype.toBinary = function(begin, end) {
35027 if (typeof begin === 'undefined')
35028 begin = this.offset;
35029 if (typeof end === 'undefined')
35030 end = this.limit;
35031 begin |= 0; end |= 0;
35032 if (begin < 0 || end > this.capacity() || begin > end)
35033 throw RangeError("begin, end");
35034 if (begin === end)
35035 return "";
35036 var chars = [],
35037 parts = [];
35038 while (begin < end) {
35039 chars.push(this.view[begin++]);
35040 if (chars.length >= 1024)
35041 parts.push(String.fromCharCode.apply(String, chars)),
35042 chars = [];
35043 }
35044 return parts.join('') + String.fromCharCode.apply(String, chars);
35045 };
35046
35047 /**
35048 * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer.
35049 * @param {string} str String to decode
35050 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
35051 * {@link ByteBuffer.DEFAULT_ENDIAN}.
35052 * @returns {!ByteBuffer} ByteBuffer
35053 * @expose
35054 */
35055 ByteBuffer.fromBinary = function(str, littleEndian) {
35056 if (typeof str !== 'string')
35057 throw TypeError("str");
35058 var i = 0,
35059 k = str.length,
35060 charCode,
35061 bb = new ByteBuffer(k, littleEndian);
35062 while (i<k) {
35063 charCode = str.charCodeAt(i);
35064 if (charCode > 0xff)
35065 throw RangeError("illegal char code: "+charCode);
35066 bb.view[i++] = charCode;
35067 }
35068 bb.limit = k;
35069 return bb;
35070 };
35071
35072 // encodings/debug
35073
35074 /**
35075 * Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
35076 * * `<` : offset,
35077 * * `'` : markedOffset,
35078 * * `>` : limit,
35079 * * `|` : offset and limit,
35080 * * `[` : offset and markedOffset,
35081 * * `]` : markedOffset and limit,
35082 * * `!` : offset, markedOffset and limit
35083 * @param {boolean=} columns If `true` returns two columns hex + ascii, defaults to `false`
35084 * @returns {string|!Array.<string>} Debug string or array of lines if `asArray = true`
35085 * @expose
35086 * @example `>00'01 02<03` contains four bytes with `limit=0, markedOffset=1, offset=3`
35087 * @example `00[01 02 03>` contains four bytes with `offset=markedOffset=1, limit=4`
35088 * @example `00|01 02 03` contains four bytes with `offset=limit=1, markedOffset=-1`
35089 * @example `|` contains zero bytes with `offset=limit=0, markedOffset=-1`
35090 */
35091 ByteBufferPrototype.toDebug = function(columns) {
35092 var i = -1,
35093 k = this.buffer.byteLength,
35094 b,
35095 hex = "",
35096 asc = "",
35097 out = "";
35098 while (i<k) {
35099 if (i !== -1) {
35100 b = this.view[i];
35101 if (b < 0x10) hex += "0"+b.toString(16).toUpperCase();
35102 else hex += b.toString(16).toUpperCase();
35103 if (columns)
35104 asc += b > 32 && b < 127 ? String.fromCharCode(b) : '.';
35105 }
35106 ++i;
35107 if (columns) {
35108 if (i > 0 && i % 16 === 0 && i !== k) {
35109 while (hex.length < 3*16+3) hex += " ";
35110 out += hex+asc+"\n";
35111 hex = asc = "";
35112 }
35113 }
35114 if (i === this.offset && i === this.limit)
35115 hex += i === this.markedOffset ? "!" : "|";
35116 else if (i === this.offset)
35117 hex += i === this.markedOffset ? "[" : "<";
35118 else if (i === this.limit)
35119 hex += i === this.markedOffset ? "]" : ">";
35120 else
35121 hex += i === this.markedOffset ? "'" : (columns || (i !== 0 && i !== k) ? " " : "");
35122 }
35123 if (columns && hex !== " ") {
35124 while (hex.length < 3*16+3)
35125 hex += " ";
35126 out += hex + asc + "\n";
35127 }
35128 return columns ? out : hex;
35129 };
35130
35131 /**
35132 * Decodes a hex encoded string with marked offsets to a ByteBuffer.
35133 * @param {string} str Debug string to decode (not be generated with `columns = true`)
35134 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
35135 * {@link ByteBuffer.DEFAULT_ENDIAN}.
35136 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
35137 * {@link ByteBuffer.DEFAULT_NOASSERT}.
35138 * @returns {!ByteBuffer} ByteBuffer
35139 * @expose
35140 * @see ByteBuffer#toDebug
35141 */
35142 ByteBuffer.fromDebug = function(str, littleEndian, noAssert) {
35143 var k = str.length,
35144 bb = new ByteBuffer(((k+1)/3)|0, littleEndian, noAssert);
35145 var i = 0, j = 0, ch, b,
35146 rs = false, // Require symbol next
35147 ho = false, hm = false, hl = false, // Already has offset (ho), markedOffset (hm), limit (hl)?
35148 fail = false;
35149 while (i<k) {
35150 switch (ch = str.charAt(i++)) {
35151 case '!':
35152 if (!noAssert) {
35153 if (ho || hm || hl) {
35154 fail = true;
35155 break;
35156 }
35157 ho = hm = hl = true;
35158 }
35159 bb.offset = bb.markedOffset = bb.limit = j;
35160 rs = false;
35161 break;
35162 case '|':
35163 if (!noAssert) {
35164 if (ho || hl) {
35165 fail = true;
35166 break;
35167 }
35168 ho = hl = true;
35169 }
35170 bb.offset = bb.limit = j;
35171 rs = false;
35172 break;
35173 case '[':
35174 if (!noAssert) {
35175 if (ho || hm) {
35176 fail = true;
35177 break;
35178 }
35179 ho = hm = true;
35180 }
35181 bb.offset = bb.markedOffset = j;
35182 rs = false;
35183 break;
35184 case '<':
35185 if (!noAssert) {
35186 if (ho) {
35187 fail = true;
35188 break;
35189 }
35190 ho = true;
35191 }
35192 bb.offset = j;
35193 rs = false;
35194 break;
35195 case ']':
35196 if (!noAssert) {
35197 if (hl || hm) {
35198 fail = true;
35199 break;
35200 }
35201 hl = hm = true;
35202 }
35203 bb.limit = bb.markedOffset = j;
35204 rs = false;
35205 break;
35206 case '>':
35207 if (!noAssert) {
35208 if (hl) {
35209 fail = true;
35210 break;
35211 }
35212 hl = true;
35213 }
35214 bb.limit = j;
35215 rs = false;
35216 break;
35217 case "'":
35218 if (!noAssert) {
35219 if (hm) {
35220 fail = true;
35221 break;
35222 }
35223 hm = true;
35224 }
35225 bb.markedOffset = j;
35226 rs = false;
35227 break;
35228 case ' ':
35229 rs = false;
35230 break;
35231 default:
35232 if (!noAssert) {
35233 if (rs) {
35234 fail = true;
35235 break;
35236 }
35237 }
35238 b = parseInt(ch+str.charAt(i++), 16);
35239 if (!noAssert) {
35240 if (isNaN(b) || b < 0 || b > 255)
35241 throw TypeError("Illegal str: Not a debug encoded string");
35242 }
35243 bb.view[j++] = b;
35244 rs = true;
35245 }
35246 if (fail)
35247 throw TypeError("Illegal str: Invalid symbol at "+i);
35248 }
35249 if (!noAssert) {
35250 if (!ho || !hl)
35251 throw TypeError("Illegal str: Missing offset or limit");
35252 if (j<bb.buffer.byteLength)
35253 throw TypeError("Illegal str: Not a debug encoded string (is it hex?) "+j+" < "+k);
35254 }
35255 return bb;
35256 };
35257
35258 // encodings/hex
35259
35260 /**
35261 * Encodes this ByteBuffer's contents to a hex encoded string.
35262 * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
35263 * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
35264 * @returns {string} Hex encoded string
35265 * @expose
35266 */
35267 ByteBufferPrototype.toHex = function(begin, end) {
35268 begin = typeof begin === 'undefined' ? this.offset : begin;
35269 end = typeof end === 'undefined' ? this.limit : end;
35270 if (!this.noAssert) {
35271 if (typeof begin !== 'number' || begin % 1 !== 0)
35272 throw TypeError("Illegal begin: Not an integer");
35273 begin >>>= 0;
35274 if (typeof end !== 'number' || end % 1 !== 0)
35275 throw TypeError("Illegal end: Not an integer");
35276 end >>>= 0;
35277 if (begin < 0 || begin > end || end > this.buffer.byteLength)
35278 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
35279 }
35280 var out = new Array(end - begin),
35281 b;
35282 while (begin < end) {
35283 b = this.view[begin++];
35284 if (b < 0x10)
35285 out.push("0", b.toString(16));
35286 else out.push(b.toString(16));
35287 }
35288 return out.join('');
35289 };
35290
35291 /**
35292 * Decodes a hex encoded string to a ByteBuffer.
35293 * @param {string} str String to decode
35294 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
35295 * {@link ByteBuffer.DEFAULT_ENDIAN}.
35296 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
35297 * {@link ByteBuffer.DEFAULT_NOASSERT}.
35298 * @returns {!ByteBuffer} ByteBuffer
35299 * @expose
35300 */
35301 ByteBuffer.fromHex = function(str, littleEndian, noAssert) {
35302 if (!noAssert) {
35303 if (typeof str !== 'string')
35304 throw TypeError("Illegal str: Not a string");
35305 if (str.length % 2 !== 0)
35306 throw TypeError("Illegal str: Length not a multiple of 2");
35307 }
35308 var k = str.length,
35309 bb = new ByteBuffer((k / 2) | 0, littleEndian),
35310 b;
35311 for (var i=0, j=0; i<k; i+=2) {
35312 b = parseInt(str.substring(i, i+2), 16);
35313 if (!noAssert)
35314 if (!isFinite(b) || b < 0 || b > 255)
35315 throw TypeError("Illegal str: Contains non-hex characters");
35316 bb.view[j++] = b;
35317 }
35318 bb.limit = j;
35319 return bb;
35320 };
35321
35322 // utfx-embeddable
35323
35324 /**
35325 * utfx-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
35326 * Released under the Apache License, Version 2.0
35327 * see: https://github.com/dcodeIO/utfx for details
35328 */
35329 var utfx = function() {
35330 "use strict";
35331
35332 /**
35333 * utfx namespace.
35334 * @inner
35335 * @type {!Object.<string,*>}
35336 */
35337 var utfx = {};
35338
35339 /**
35340 * Maximum valid code point.
35341 * @type {number}
35342 * @const
35343 */
35344 utfx.MAX_CODEPOINT = 0x10FFFF;
35345
35346 /**
35347 * Encodes UTF8 code points to UTF8 bytes.
35348 * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
35349 * respectively `null` if there are no more code points left or a single numeric code point.
35350 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte
35351 */
35352 utfx.encodeUTF8 = function(src, dst) {
35353 var cp = null;
35354 if (typeof src === 'number')
35355 cp = src,
35356 src = function() { return null; };
35357 while (cp !== null || (cp = src()) !== null) {
35358 if (cp < 0x80)
35359 dst(cp&0x7F);
35360 else if (cp < 0x800)
35361 dst(((cp>>6)&0x1F)|0xC0),
35362 dst((cp&0x3F)|0x80);
35363 else if (cp < 0x10000)
35364 dst(((cp>>12)&0x0F)|0xE0),
35365 dst(((cp>>6)&0x3F)|0x80),
35366 dst((cp&0x3F)|0x80);
35367 else
35368 dst(((cp>>18)&0x07)|0xF0),
35369 dst(((cp>>12)&0x3F)|0x80),
35370 dst(((cp>>6)&0x3F)|0x80),
35371 dst((cp&0x3F)|0x80);
35372 cp = null;
35373 }
35374 };
35375
35376 /**
35377 * Decodes UTF8 bytes to UTF8 code points.
35378 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
35379 * are no more bytes left.
35380 * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point.
35381 * @throws {RangeError} If a starting byte is invalid in UTF8
35382 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the
35383 * remaining bytes.
35384 */
35385 utfx.decodeUTF8 = function(src, dst) {
35386 var a, b, c, d, fail = function(b) {
35387 b = b.slice(0, b.indexOf(null));
35388 var err = Error(b.toString());
35389 err.name = "TruncatedError";
35390 err['bytes'] = b;
35391 throw err;
35392 };
35393 while ((a = src()) !== null) {
35394 if ((a&0x80) === 0)
35395 dst(a);
35396 else if ((a&0xE0) === 0xC0)
35397 ((b = src()) === null) && fail([a, b]),
35398 dst(((a&0x1F)<<6) | (b&0x3F));
35399 else if ((a&0xF0) === 0xE0)
35400 ((b=src()) === null || (c=src()) === null) && fail([a, b, c]),
35401 dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F));
35402 else if ((a&0xF8) === 0xF0)
35403 ((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]),
35404 dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F));
35405 else throw RangeError("Illegal starting byte: "+a);
35406 }
35407 };
35408
35409 /**
35410 * Converts UTF16 characters to UTF8 code points.
35411 * @param {!function():number|null} src Characters source as a function returning the next char code respectively
35412 * `null` if there are no more characters left.
35413 * @param {!function(number)} dst Code points destination as a function successively called with each converted code
35414 * point.
35415 */
35416 utfx.UTF16toUTF8 = function(src, dst) {
35417 var c1, c2 = null;
35418 while (true) {
35419 if ((c1 = c2 !== null ? c2 : src()) === null)
35420 break;
35421 if (c1 >= 0xD800 && c1 <= 0xDFFF) {
35422 if ((c2 = src()) !== null) {
35423 if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
35424 dst((c1-0xD800)*0x400+c2-0xDC00+0x10000);
35425 c2 = null; continue;
35426 }
35427 }
35428 }
35429 dst(c1);
35430 }
35431 if (c2 !== null) dst(c2);
35432 };
35433
35434 /**
35435 * Converts UTF8 code points to UTF16 characters.
35436 * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
35437 * respectively `null` if there are no more code points left or a single numeric code point.
35438 * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
35439 * @throws {RangeError} If a code point is out of range
35440 */
35441 utfx.UTF8toUTF16 = function(src, dst) {
35442 var cp = null;
35443 if (typeof src === 'number')
35444 cp = src, src = function() { return null; };
35445 while (cp !== null || (cp = src()) !== null) {
35446 if (cp <= 0xFFFF)
35447 dst(cp);
35448 else
35449 cp -= 0x10000,
35450 dst((cp>>10)+0xD800),
35451 dst((cp%0x400)+0xDC00);
35452 cp = null;
35453 }
35454 };
35455
35456 /**
35457 * Converts and encodes UTF16 characters to UTF8 bytes.
35458 * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null`
35459 * if there are no more characters left.
35460 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
35461 */
35462 utfx.encodeUTF16toUTF8 = function(src, dst) {
35463 utfx.UTF16toUTF8(src, function(cp) {
35464 utfx.encodeUTF8(cp, dst);
35465 });
35466 };
35467
35468 /**
35469 * Decodes and converts UTF8 bytes to UTF16 characters.
35470 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
35471 * are no more bytes left.
35472 * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
35473 * @throws {RangeError} If a starting byte is invalid in UTF8
35474 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes.
35475 */
35476 utfx.decodeUTF8toUTF16 = function(src, dst) {
35477 utfx.decodeUTF8(src, function(cp) {
35478 utfx.UTF8toUTF16(cp, dst);
35479 });
35480 };
35481
35482 /**
35483 * Calculates the byte length of an UTF8 code point.
35484 * @param {number} cp UTF8 code point
35485 * @returns {number} Byte length
35486 */
35487 utfx.calculateCodePoint = function(cp) {
35488 return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
35489 };
35490
35491 /**
35492 * Calculates the number of UTF8 bytes required to store UTF8 code points.
35493 * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively
35494 * `null` if there are no more code points left.
35495 * @returns {number} The number of UTF8 bytes required
35496 */
35497 utfx.calculateUTF8 = function(src) {
35498 var cp, l=0;
35499 while ((cp = src()) !== null)
35500 l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
35501 return l;
35502 };
35503
35504 /**
35505 * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes.
35506 * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively
35507 * `null` if there are no more characters left.
35508 * @returns {!Array.<number>} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1.
35509 */
35510 utfx.calculateUTF16asUTF8 = function(src) {
35511 var n=0, l=0;
35512 utfx.UTF16toUTF8(src, function(cp) {
35513 ++n; l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
35514 });
35515 return [n,l];
35516 };
35517
35518 return utfx;
35519 }();
35520
35521 // encodings/utf8
35522
35523 /**
35524 * Encodes this ByteBuffer's contents between {@link ByteBuffer#offset} and {@link ByteBuffer#limit} to an UTF8 encoded
35525 * string.
35526 * @returns {string} Hex encoded string
35527 * @throws {RangeError} If `offset > limit`
35528 * @expose
35529 */
35530 ByteBufferPrototype.toUTF8 = function(begin, end) {
35531 if (typeof begin === 'undefined') begin = this.offset;
35532 if (typeof end === 'undefined') end = this.limit;
35533 if (!this.noAssert) {
35534 if (typeof begin !== 'number' || begin % 1 !== 0)
35535 throw TypeError("Illegal begin: Not an integer");
35536 begin >>>= 0;
35537 if (typeof end !== 'number' || end % 1 !== 0)
35538 throw TypeError("Illegal end: Not an integer");
35539 end >>>= 0;
35540 if (begin < 0 || begin > end || end > this.buffer.byteLength)
35541 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
35542 }
35543 var sd; try {
35544 utfx.decodeUTF8toUTF16(function() {
35545 return begin < end ? this.view[begin++] : null;
35546 }.bind(this), sd = stringDestination());
35547 } catch (e) {
35548 if (begin !== end)
35549 throw RangeError("Illegal range: Truncated data, "+begin+" != "+end);
35550 }
35551 return sd();
35552 };
35553
35554 /**
35555 * Decodes an UTF8 encoded string to a ByteBuffer.
35556 * @param {string} str String to decode
35557 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
35558 * {@link ByteBuffer.DEFAULT_ENDIAN}.
35559 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
35560 * {@link ByteBuffer.DEFAULT_NOASSERT}.
35561 * @returns {!ByteBuffer} ByteBuffer
35562 * @expose
35563 */
35564 ByteBuffer.fromUTF8 = function(str, littleEndian, noAssert) {
35565 if (!noAssert)
35566 if (typeof str !== 'string')
35567 throw TypeError("Illegal str: Not a string");
35568 var bb = new ByteBuffer(utfx.calculateUTF16asUTF8(stringSource(str), true)[1], littleEndian, noAssert),
35569 i = 0;
35570 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
35571 bb.view[i++] = b;
35572 });
35573 bb.limit = i;
35574 return bb;
35575 };
35576
35577 return ByteBuffer;
35578});
35579
35580
35581/***/ }),
35582/* 411 */
35583/***/ (function(module, exports, __webpack_require__) {
35584
35585var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*
35586 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
35587 Copyright 2009 The Closure Library Authors. All Rights Reserved.
35588
35589 Licensed under the Apache License, Version 2.0 (the "License");
35590 you may not use this file except in compliance with the License.
35591 You may obtain a copy of the License at
35592
35593 http://www.apache.org/licenses/LICENSE-2.0
35594
35595 Unless required by applicable law or agreed to in writing, software
35596 distributed under the License is distributed on an "AS-IS" BASIS,
35597 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
35598 See the License for the specific language governing permissions and
35599 limitations under the License.
35600 */
35601
35602/**
35603 * @license long.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
35604 * Released under the Apache License, Version 2.0
35605 * see: https://github.com/dcodeIO/long.js for details
35606 */
35607(function(global, factory) {
35608
35609 /* AMD */ if (true)
35610 !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
35611 __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
35612 (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
35613 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
35614 /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
35615 module["exports"] = factory();
35616 /* Global */ else
35617 (global["dcodeIO"] = global["dcodeIO"] || {})["Long"] = factory();
35618
35619})(this, function() {
35620 "use strict";
35621
35622 /**
35623 * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
35624 * See the from* functions below for more convenient ways of constructing Longs.
35625 * @exports Long
35626 * @class A Long class for representing a 64 bit two's-complement integer value.
35627 * @param {number} low The low (signed) 32 bits of the long
35628 * @param {number} high The high (signed) 32 bits of the long
35629 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
35630 * @constructor
35631 */
35632 function Long(low, high, unsigned) {
35633
35634 /**
35635 * The low 32 bits as a signed value.
35636 * @type {number}
35637 */
35638 this.low = low | 0;
35639
35640 /**
35641 * The high 32 bits as a signed value.
35642 * @type {number}
35643 */
35644 this.high = high | 0;
35645
35646 /**
35647 * Whether unsigned or not.
35648 * @type {boolean}
35649 */
35650 this.unsigned = !!unsigned;
35651 }
35652
35653 // The internal representation of a long is the two given signed, 32-bit values.
35654 // We use 32-bit pieces because these are the size of integers on which
35655 // Javascript performs bit-operations. For operations like addition and
35656 // multiplication, we split each number into 16 bit pieces, which can easily be
35657 // multiplied within Javascript's floating-point representation without overflow
35658 // or change in sign.
35659 //
35660 // In the algorithms below, we frequently reduce the negative case to the
35661 // positive case by negating the input(s) and then post-processing the result.
35662 // Note that we must ALWAYS check specially whether those values are MIN_VALUE
35663 // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
35664 // a positive number, it overflows back into a negative). Not handling this
35665 // case would often result in infinite recursion.
35666 //
35667 // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
35668 // methods on which they depend.
35669
35670 /**
35671 * An indicator used to reliably determine if an object is a Long or not.
35672 * @type {boolean}
35673 * @const
35674 * @private
35675 */
35676 Long.prototype.__isLong__;
35677
35678 Object.defineProperty(Long.prototype, "__isLong__", {
35679 value: true,
35680 enumerable: false,
35681 configurable: false
35682 });
35683
35684 /**
35685 * @function
35686 * @param {*} obj Object
35687 * @returns {boolean}
35688 * @inner
35689 */
35690 function isLong(obj) {
35691 return (obj && obj["__isLong__"]) === true;
35692 }
35693
35694 /**
35695 * Tests if the specified object is a Long.
35696 * @function
35697 * @param {*} obj Object
35698 * @returns {boolean}
35699 */
35700 Long.isLong = isLong;
35701
35702 /**
35703 * A cache of the Long representations of small integer values.
35704 * @type {!Object}
35705 * @inner
35706 */
35707 var INT_CACHE = {};
35708
35709 /**
35710 * A cache of the Long representations of small unsigned integer values.
35711 * @type {!Object}
35712 * @inner
35713 */
35714 var UINT_CACHE = {};
35715
35716 /**
35717 * @param {number} value
35718 * @param {boolean=} unsigned
35719 * @returns {!Long}
35720 * @inner
35721 */
35722 function fromInt(value, unsigned) {
35723 var obj, cachedObj, cache;
35724 if (unsigned) {
35725 value >>>= 0;
35726 if (cache = (0 <= value && value < 256)) {
35727 cachedObj = UINT_CACHE[value];
35728 if (cachedObj)
35729 return cachedObj;
35730 }
35731 obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
35732 if (cache)
35733 UINT_CACHE[value] = obj;
35734 return obj;
35735 } else {
35736 value |= 0;
35737 if (cache = (-128 <= value && value < 128)) {
35738 cachedObj = INT_CACHE[value];
35739 if (cachedObj)
35740 return cachedObj;
35741 }
35742 obj = fromBits(value, value < 0 ? -1 : 0, false);
35743 if (cache)
35744 INT_CACHE[value] = obj;
35745 return obj;
35746 }
35747 }
35748
35749 /**
35750 * Returns a Long representing the given 32 bit integer value.
35751 * @function
35752 * @param {number} value The 32 bit integer in question
35753 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
35754 * @returns {!Long} The corresponding Long value
35755 */
35756 Long.fromInt = fromInt;
35757
35758 /**
35759 * @param {number} value
35760 * @param {boolean=} unsigned
35761 * @returns {!Long}
35762 * @inner
35763 */
35764 function fromNumber(value, unsigned) {
35765 if (isNaN(value) || !isFinite(value))
35766 return unsigned ? UZERO : ZERO;
35767 if (unsigned) {
35768 if (value < 0)
35769 return UZERO;
35770 if (value >= TWO_PWR_64_DBL)
35771 return MAX_UNSIGNED_VALUE;
35772 } else {
35773 if (value <= -TWO_PWR_63_DBL)
35774 return MIN_VALUE;
35775 if (value + 1 >= TWO_PWR_63_DBL)
35776 return MAX_VALUE;
35777 }
35778 if (value < 0)
35779 return fromNumber(-value, unsigned).neg();
35780 return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
35781 }
35782
35783 /**
35784 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
35785 * @function
35786 * @param {number} value The number in question
35787 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
35788 * @returns {!Long} The corresponding Long value
35789 */
35790 Long.fromNumber = fromNumber;
35791
35792 /**
35793 * @param {number} lowBits
35794 * @param {number} highBits
35795 * @param {boolean=} unsigned
35796 * @returns {!Long}
35797 * @inner
35798 */
35799 function fromBits(lowBits, highBits, unsigned) {
35800 return new Long(lowBits, highBits, unsigned);
35801 }
35802
35803 /**
35804 * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
35805 * assumed to use 32 bits.
35806 * @function
35807 * @param {number} lowBits The low 32 bits
35808 * @param {number} highBits The high 32 bits
35809 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
35810 * @returns {!Long} The corresponding Long value
35811 */
35812 Long.fromBits = fromBits;
35813
35814 /**
35815 * @function
35816 * @param {number} base
35817 * @param {number} exponent
35818 * @returns {number}
35819 * @inner
35820 */
35821 var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
35822
35823 /**
35824 * @param {string} str
35825 * @param {(boolean|number)=} unsigned
35826 * @param {number=} radix
35827 * @returns {!Long}
35828 * @inner
35829 */
35830 function fromString(str, unsigned, radix) {
35831 if (str.length === 0)
35832 throw Error('empty string');
35833 if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
35834 return ZERO;
35835 if (typeof unsigned === 'number') {
35836 // For goog.math.long compatibility
35837 radix = unsigned,
35838 unsigned = false;
35839 } else {
35840 unsigned = !! unsigned;
35841 }
35842 radix = radix || 10;
35843 if (radix < 2 || 36 < radix)
35844 throw RangeError('radix');
35845
35846 var p;
35847 if ((p = str.indexOf('-')) > 0)
35848 throw Error('interior hyphen');
35849 else if (p === 0) {
35850 return fromString(str.substring(1), unsigned, radix).neg();
35851 }
35852
35853 // Do several (8) digits each time through the loop, so as to
35854 // minimize the calls to the very expensive emulated div.
35855 var radixToPower = fromNumber(pow_dbl(radix, 8));
35856
35857 var result = ZERO;
35858 for (var i = 0; i < str.length; i += 8) {
35859 var size = Math.min(8, str.length - i),
35860 value = parseInt(str.substring(i, i + size), radix);
35861 if (size < 8) {
35862 var power = fromNumber(pow_dbl(radix, size));
35863 result = result.mul(power).add(fromNumber(value));
35864 } else {
35865 result = result.mul(radixToPower);
35866 result = result.add(fromNumber(value));
35867 }
35868 }
35869 result.unsigned = unsigned;
35870 return result;
35871 }
35872
35873 /**
35874 * Returns a Long representation of the given string, written using the specified radix.
35875 * @function
35876 * @param {string} str The textual representation of the Long
35877 * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to `false` for signed
35878 * @param {number=} radix The radix in which the text is written (2-36), defaults to 10
35879 * @returns {!Long} The corresponding Long value
35880 */
35881 Long.fromString = fromString;
35882
35883 /**
35884 * @function
35885 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
35886 * @returns {!Long}
35887 * @inner
35888 */
35889 function fromValue(val) {
35890 if (val /* is compatible */ instanceof Long)
35891 return val;
35892 if (typeof val === 'number')
35893 return fromNumber(val);
35894 if (typeof val === 'string')
35895 return fromString(val);
35896 // Throws for non-objects, converts non-instanceof Long:
35897 return fromBits(val.low, val.high, val.unsigned);
35898 }
35899
35900 /**
35901 * Converts the specified value to a Long.
35902 * @function
35903 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
35904 * @returns {!Long}
35905 */
35906 Long.fromValue = fromValue;
35907
35908 // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
35909 // no runtime penalty for these.
35910
35911 /**
35912 * @type {number}
35913 * @const
35914 * @inner
35915 */
35916 var TWO_PWR_16_DBL = 1 << 16;
35917
35918 /**
35919 * @type {number}
35920 * @const
35921 * @inner
35922 */
35923 var TWO_PWR_24_DBL = 1 << 24;
35924
35925 /**
35926 * @type {number}
35927 * @const
35928 * @inner
35929 */
35930 var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
35931
35932 /**
35933 * @type {number}
35934 * @const
35935 * @inner
35936 */
35937 var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
35938
35939 /**
35940 * @type {number}
35941 * @const
35942 * @inner
35943 */
35944 var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
35945
35946 /**
35947 * @type {!Long}
35948 * @const
35949 * @inner
35950 */
35951 var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
35952
35953 /**
35954 * @type {!Long}
35955 * @inner
35956 */
35957 var ZERO = fromInt(0);
35958
35959 /**
35960 * Signed zero.
35961 * @type {!Long}
35962 */
35963 Long.ZERO = ZERO;
35964
35965 /**
35966 * @type {!Long}
35967 * @inner
35968 */
35969 var UZERO = fromInt(0, true);
35970
35971 /**
35972 * Unsigned zero.
35973 * @type {!Long}
35974 */
35975 Long.UZERO = UZERO;
35976
35977 /**
35978 * @type {!Long}
35979 * @inner
35980 */
35981 var ONE = fromInt(1);
35982
35983 /**
35984 * Signed one.
35985 * @type {!Long}
35986 */
35987 Long.ONE = ONE;
35988
35989 /**
35990 * @type {!Long}
35991 * @inner
35992 */
35993 var UONE = fromInt(1, true);
35994
35995 /**
35996 * Unsigned one.
35997 * @type {!Long}
35998 */
35999 Long.UONE = UONE;
36000
36001 /**
36002 * @type {!Long}
36003 * @inner
36004 */
36005 var NEG_ONE = fromInt(-1);
36006
36007 /**
36008 * Signed negative one.
36009 * @type {!Long}
36010 */
36011 Long.NEG_ONE = NEG_ONE;
36012
36013 /**
36014 * @type {!Long}
36015 * @inner
36016 */
36017 var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
36018
36019 /**
36020 * Maximum signed value.
36021 * @type {!Long}
36022 */
36023 Long.MAX_VALUE = MAX_VALUE;
36024
36025 /**
36026 * @type {!Long}
36027 * @inner
36028 */
36029 var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
36030
36031 /**
36032 * Maximum unsigned value.
36033 * @type {!Long}
36034 */
36035 Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
36036
36037 /**
36038 * @type {!Long}
36039 * @inner
36040 */
36041 var MIN_VALUE = fromBits(0, 0x80000000|0, false);
36042
36043 /**
36044 * Minimum signed value.
36045 * @type {!Long}
36046 */
36047 Long.MIN_VALUE = MIN_VALUE;
36048
36049 /**
36050 * @alias Long.prototype
36051 * @inner
36052 */
36053 var LongPrototype = Long.prototype;
36054
36055 /**
36056 * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
36057 * @returns {number}
36058 */
36059 LongPrototype.toInt = function toInt() {
36060 return this.unsigned ? this.low >>> 0 : this.low;
36061 };
36062
36063 /**
36064 * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
36065 * @returns {number}
36066 */
36067 LongPrototype.toNumber = function toNumber() {
36068 if (this.unsigned)
36069 return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
36070 return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
36071 };
36072
36073 /**
36074 * Converts the Long to a string written in the specified radix.
36075 * @param {number=} radix Radix (2-36), defaults to 10
36076 * @returns {string}
36077 * @override
36078 * @throws {RangeError} If `radix` is out of range
36079 */
36080 LongPrototype.toString = function toString(radix) {
36081 radix = radix || 10;
36082 if (radix < 2 || 36 < radix)
36083 throw RangeError('radix');
36084 if (this.isZero())
36085 return '0';
36086 if (this.isNegative()) { // Unsigned Longs are never negative
36087 if (this.eq(MIN_VALUE)) {
36088 // We need to change the Long value before it can be negated, so we remove
36089 // the bottom-most digit in this base and then recurse to do the rest.
36090 var radixLong = fromNumber(radix),
36091 div = this.div(radixLong),
36092 rem1 = div.mul(radixLong).sub(this);
36093 return div.toString(radix) + rem1.toInt().toString(radix);
36094 } else
36095 return '-' + this.neg().toString(radix);
36096 }
36097
36098 // Do several (6) digits each time through the loop, so as to
36099 // minimize the calls to the very expensive emulated div.
36100 var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
36101 rem = this;
36102 var result = '';
36103 while (true) {
36104 var remDiv = rem.div(radixToPower),
36105 intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
36106 digits = intval.toString(radix);
36107 rem = remDiv;
36108 if (rem.isZero())
36109 return digits + result;
36110 else {
36111 while (digits.length < 6)
36112 digits = '0' + digits;
36113 result = '' + digits + result;
36114 }
36115 }
36116 };
36117
36118 /**
36119 * Gets the high 32 bits as a signed integer.
36120 * @returns {number} Signed high bits
36121 */
36122 LongPrototype.getHighBits = function getHighBits() {
36123 return this.high;
36124 };
36125
36126 /**
36127 * Gets the high 32 bits as an unsigned integer.
36128 * @returns {number} Unsigned high bits
36129 */
36130 LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
36131 return this.high >>> 0;
36132 };
36133
36134 /**
36135 * Gets the low 32 bits as a signed integer.
36136 * @returns {number} Signed low bits
36137 */
36138 LongPrototype.getLowBits = function getLowBits() {
36139 return this.low;
36140 };
36141
36142 /**
36143 * Gets the low 32 bits as an unsigned integer.
36144 * @returns {number} Unsigned low bits
36145 */
36146 LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
36147 return this.low >>> 0;
36148 };
36149
36150 /**
36151 * Gets the number of bits needed to represent the absolute value of this Long.
36152 * @returns {number}
36153 */
36154 LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
36155 if (this.isNegative()) // Unsigned Longs are never negative
36156 return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
36157 var val = this.high != 0 ? this.high : this.low;
36158 for (var bit = 31; bit > 0; bit--)
36159 if ((val & (1 << bit)) != 0)
36160 break;
36161 return this.high != 0 ? bit + 33 : bit + 1;
36162 };
36163
36164 /**
36165 * Tests if this Long's value equals zero.
36166 * @returns {boolean}
36167 */
36168 LongPrototype.isZero = function isZero() {
36169 return this.high === 0 && this.low === 0;
36170 };
36171
36172 /**
36173 * Tests if this Long's value is negative.
36174 * @returns {boolean}
36175 */
36176 LongPrototype.isNegative = function isNegative() {
36177 return !this.unsigned && this.high < 0;
36178 };
36179
36180 /**
36181 * Tests if this Long's value is positive.
36182 * @returns {boolean}
36183 */
36184 LongPrototype.isPositive = function isPositive() {
36185 return this.unsigned || this.high >= 0;
36186 };
36187
36188 /**
36189 * Tests if this Long's value is odd.
36190 * @returns {boolean}
36191 */
36192 LongPrototype.isOdd = function isOdd() {
36193 return (this.low & 1) === 1;
36194 };
36195
36196 /**
36197 * Tests if this Long's value is even.
36198 * @returns {boolean}
36199 */
36200 LongPrototype.isEven = function isEven() {
36201 return (this.low & 1) === 0;
36202 };
36203
36204 /**
36205 * Tests if this Long's value equals the specified's.
36206 * @param {!Long|number|string} other Other value
36207 * @returns {boolean}
36208 */
36209 LongPrototype.equals = function equals(other) {
36210 if (!isLong(other))
36211 other = fromValue(other);
36212 if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
36213 return false;
36214 return this.high === other.high && this.low === other.low;
36215 };
36216
36217 /**
36218 * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
36219 * @function
36220 * @param {!Long|number|string} other Other value
36221 * @returns {boolean}
36222 */
36223 LongPrototype.eq = LongPrototype.equals;
36224
36225 /**
36226 * Tests if this Long's value differs from the specified's.
36227 * @param {!Long|number|string} other Other value
36228 * @returns {boolean}
36229 */
36230 LongPrototype.notEquals = function notEquals(other) {
36231 return !this.eq(/* validates */ other);
36232 };
36233
36234 /**
36235 * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
36236 * @function
36237 * @param {!Long|number|string} other Other value
36238 * @returns {boolean}
36239 */
36240 LongPrototype.neq = LongPrototype.notEquals;
36241
36242 /**
36243 * Tests if this Long's value is less than the specified's.
36244 * @param {!Long|number|string} other Other value
36245 * @returns {boolean}
36246 */
36247 LongPrototype.lessThan = function lessThan(other) {
36248 return this.comp(/* validates */ other) < 0;
36249 };
36250
36251 /**
36252 * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
36253 * @function
36254 * @param {!Long|number|string} other Other value
36255 * @returns {boolean}
36256 */
36257 LongPrototype.lt = LongPrototype.lessThan;
36258
36259 /**
36260 * Tests if this Long's value is less than or equal the specified's.
36261 * @param {!Long|number|string} other Other value
36262 * @returns {boolean}
36263 */
36264 LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
36265 return this.comp(/* validates */ other) <= 0;
36266 };
36267
36268 /**
36269 * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
36270 * @function
36271 * @param {!Long|number|string} other Other value
36272 * @returns {boolean}
36273 */
36274 LongPrototype.lte = LongPrototype.lessThanOrEqual;
36275
36276 /**
36277 * Tests if this Long's value is greater than the specified's.
36278 * @param {!Long|number|string} other Other value
36279 * @returns {boolean}
36280 */
36281 LongPrototype.greaterThan = function greaterThan(other) {
36282 return this.comp(/* validates */ other) > 0;
36283 };
36284
36285 /**
36286 * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
36287 * @function
36288 * @param {!Long|number|string} other Other value
36289 * @returns {boolean}
36290 */
36291 LongPrototype.gt = LongPrototype.greaterThan;
36292
36293 /**
36294 * Tests if this Long's value is greater than or equal the specified's.
36295 * @param {!Long|number|string} other Other value
36296 * @returns {boolean}
36297 */
36298 LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
36299 return this.comp(/* validates */ other) >= 0;
36300 };
36301
36302 /**
36303 * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
36304 * @function
36305 * @param {!Long|number|string} other Other value
36306 * @returns {boolean}
36307 */
36308 LongPrototype.gte = LongPrototype.greaterThanOrEqual;
36309
36310 /**
36311 * Compares this Long's value with the specified's.
36312 * @param {!Long|number|string} other Other value
36313 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
36314 * if the given one is greater
36315 */
36316 LongPrototype.compare = function compare(other) {
36317 if (!isLong(other))
36318 other = fromValue(other);
36319 if (this.eq(other))
36320 return 0;
36321 var thisNeg = this.isNegative(),
36322 otherNeg = other.isNegative();
36323 if (thisNeg && !otherNeg)
36324 return -1;
36325 if (!thisNeg && otherNeg)
36326 return 1;
36327 // At this point the sign bits are the same
36328 if (!this.unsigned)
36329 return this.sub(other).isNegative() ? -1 : 1;
36330 // Both are positive if at least one is unsigned
36331 return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
36332 };
36333
36334 /**
36335 * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
36336 * @function
36337 * @param {!Long|number|string} other Other value
36338 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
36339 * if the given one is greater
36340 */
36341 LongPrototype.comp = LongPrototype.compare;
36342
36343 /**
36344 * Negates this Long's value.
36345 * @returns {!Long} Negated Long
36346 */
36347 LongPrototype.negate = function negate() {
36348 if (!this.unsigned && this.eq(MIN_VALUE))
36349 return MIN_VALUE;
36350 return this.not().add(ONE);
36351 };
36352
36353 /**
36354 * Negates this Long's value. This is an alias of {@link Long#negate}.
36355 * @function
36356 * @returns {!Long} Negated Long
36357 */
36358 LongPrototype.neg = LongPrototype.negate;
36359
36360 /**
36361 * Returns the sum of this and the specified Long.
36362 * @param {!Long|number|string} addend Addend
36363 * @returns {!Long} Sum
36364 */
36365 LongPrototype.add = function add(addend) {
36366 if (!isLong(addend))
36367 addend = fromValue(addend);
36368
36369 // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
36370
36371 var a48 = this.high >>> 16;
36372 var a32 = this.high & 0xFFFF;
36373 var a16 = this.low >>> 16;
36374 var a00 = this.low & 0xFFFF;
36375
36376 var b48 = addend.high >>> 16;
36377 var b32 = addend.high & 0xFFFF;
36378 var b16 = addend.low >>> 16;
36379 var b00 = addend.low & 0xFFFF;
36380
36381 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
36382 c00 += a00 + b00;
36383 c16 += c00 >>> 16;
36384 c00 &= 0xFFFF;
36385 c16 += a16 + b16;
36386 c32 += c16 >>> 16;
36387 c16 &= 0xFFFF;
36388 c32 += a32 + b32;
36389 c48 += c32 >>> 16;
36390 c32 &= 0xFFFF;
36391 c48 += a48 + b48;
36392 c48 &= 0xFFFF;
36393 return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
36394 };
36395
36396 /**
36397 * Returns the difference of this and the specified Long.
36398 * @param {!Long|number|string} subtrahend Subtrahend
36399 * @returns {!Long} Difference
36400 */
36401 LongPrototype.subtract = function subtract(subtrahend) {
36402 if (!isLong(subtrahend))
36403 subtrahend = fromValue(subtrahend);
36404 return this.add(subtrahend.neg());
36405 };
36406
36407 /**
36408 * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
36409 * @function
36410 * @param {!Long|number|string} subtrahend Subtrahend
36411 * @returns {!Long} Difference
36412 */
36413 LongPrototype.sub = LongPrototype.subtract;
36414
36415 /**
36416 * Returns the product of this and the specified Long.
36417 * @param {!Long|number|string} multiplier Multiplier
36418 * @returns {!Long} Product
36419 */
36420 LongPrototype.multiply = function multiply(multiplier) {
36421 if (this.isZero())
36422 return ZERO;
36423 if (!isLong(multiplier))
36424 multiplier = fromValue(multiplier);
36425 if (multiplier.isZero())
36426 return ZERO;
36427 if (this.eq(MIN_VALUE))
36428 return multiplier.isOdd() ? MIN_VALUE : ZERO;
36429 if (multiplier.eq(MIN_VALUE))
36430 return this.isOdd() ? MIN_VALUE : ZERO;
36431
36432 if (this.isNegative()) {
36433 if (multiplier.isNegative())
36434 return this.neg().mul(multiplier.neg());
36435 else
36436 return this.neg().mul(multiplier).neg();
36437 } else if (multiplier.isNegative())
36438 return this.mul(multiplier.neg()).neg();
36439
36440 // If both longs are small, use float multiplication
36441 if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
36442 return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
36443
36444 // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
36445 // We can skip products that would overflow.
36446
36447 var a48 = this.high >>> 16;
36448 var a32 = this.high & 0xFFFF;
36449 var a16 = this.low >>> 16;
36450 var a00 = this.low & 0xFFFF;
36451
36452 var b48 = multiplier.high >>> 16;
36453 var b32 = multiplier.high & 0xFFFF;
36454 var b16 = multiplier.low >>> 16;
36455 var b00 = multiplier.low & 0xFFFF;
36456
36457 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
36458 c00 += a00 * b00;
36459 c16 += c00 >>> 16;
36460 c00 &= 0xFFFF;
36461 c16 += a16 * b00;
36462 c32 += c16 >>> 16;
36463 c16 &= 0xFFFF;
36464 c16 += a00 * b16;
36465 c32 += c16 >>> 16;
36466 c16 &= 0xFFFF;
36467 c32 += a32 * b00;
36468 c48 += c32 >>> 16;
36469 c32 &= 0xFFFF;
36470 c32 += a16 * b16;
36471 c48 += c32 >>> 16;
36472 c32 &= 0xFFFF;
36473 c32 += a00 * b32;
36474 c48 += c32 >>> 16;
36475 c32 &= 0xFFFF;
36476 c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
36477 c48 &= 0xFFFF;
36478 return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
36479 };
36480
36481 /**
36482 * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
36483 * @function
36484 * @param {!Long|number|string} multiplier Multiplier
36485 * @returns {!Long} Product
36486 */
36487 LongPrototype.mul = LongPrototype.multiply;
36488
36489 /**
36490 * Returns this Long divided by the specified. The result is signed if this Long is signed or
36491 * unsigned if this Long is unsigned.
36492 * @param {!Long|number|string} divisor Divisor
36493 * @returns {!Long} Quotient
36494 */
36495 LongPrototype.divide = function divide(divisor) {
36496 if (!isLong(divisor))
36497 divisor = fromValue(divisor);
36498 if (divisor.isZero())
36499 throw Error('division by zero');
36500 if (this.isZero())
36501 return this.unsigned ? UZERO : ZERO;
36502 var approx, rem, res;
36503 if (!this.unsigned) {
36504 // This section is only relevant for signed longs and is derived from the
36505 // closure library as a whole.
36506 if (this.eq(MIN_VALUE)) {
36507 if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
36508 return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
36509 else if (divisor.eq(MIN_VALUE))
36510 return ONE;
36511 else {
36512 // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
36513 var halfThis = this.shr(1);
36514 approx = halfThis.div(divisor).shl(1);
36515 if (approx.eq(ZERO)) {
36516 return divisor.isNegative() ? ONE : NEG_ONE;
36517 } else {
36518 rem = this.sub(divisor.mul(approx));
36519 res = approx.add(rem.div(divisor));
36520 return res;
36521 }
36522 }
36523 } else if (divisor.eq(MIN_VALUE))
36524 return this.unsigned ? UZERO : ZERO;
36525 if (this.isNegative()) {
36526 if (divisor.isNegative())
36527 return this.neg().div(divisor.neg());
36528 return this.neg().div(divisor).neg();
36529 } else if (divisor.isNegative())
36530 return this.div(divisor.neg()).neg();
36531 res = ZERO;
36532 } else {
36533 // The algorithm below has not been made for unsigned longs. It's therefore
36534 // required to take special care of the MSB prior to running it.
36535 if (!divisor.unsigned)
36536 divisor = divisor.toUnsigned();
36537 if (divisor.gt(this))
36538 return UZERO;
36539 if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
36540 return UONE;
36541 res = UZERO;
36542 }
36543
36544 // Repeat the following until the remainder is less than other: find a
36545 // floating-point that approximates remainder / other *from below*, add this
36546 // into the result, and subtract it from the remainder. It is critical that
36547 // the approximate value is less than or equal to the real value so that the
36548 // remainder never becomes negative.
36549 rem = this;
36550 while (rem.gte(divisor)) {
36551 // Approximate the result of division. This may be a little greater or
36552 // smaller than the actual value.
36553 approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
36554
36555 // We will tweak the approximate result by changing it in the 48-th digit or
36556 // the smallest non-fractional digit, whichever is larger.
36557 var log2 = Math.ceil(Math.log(approx) / Math.LN2),
36558 delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
36559
36560 // Decrease the approximation until it is smaller than the remainder. Note
36561 // that if it is too large, the product overflows and is negative.
36562 approxRes = fromNumber(approx),
36563 approxRem = approxRes.mul(divisor);
36564 while (approxRem.isNegative() || approxRem.gt(rem)) {
36565 approx -= delta;
36566 approxRes = fromNumber(approx, this.unsigned);
36567 approxRem = approxRes.mul(divisor);
36568 }
36569
36570 // We know the answer can't be zero... and actually, zero would cause
36571 // infinite recursion since we would make no progress.
36572 if (approxRes.isZero())
36573 approxRes = ONE;
36574
36575 res = res.add(approxRes);
36576 rem = rem.sub(approxRem);
36577 }
36578 return res;
36579 };
36580
36581 /**
36582 * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
36583 * @function
36584 * @param {!Long|number|string} divisor Divisor
36585 * @returns {!Long} Quotient
36586 */
36587 LongPrototype.div = LongPrototype.divide;
36588
36589 /**
36590 * Returns this Long modulo the specified.
36591 * @param {!Long|number|string} divisor Divisor
36592 * @returns {!Long} Remainder
36593 */
36594 LongPrototype.modulo = function modulo(divisor) {
36595 if (!isLong(divisor))
36596 divisor = fromValue(divisor);
36597 return this.sub(this.div(divisor).mul(divisor));
36598 };
36599
36600 /**
36601 * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
36602 * @function
36603 * @param {!Long|number|string} divisor Divisor
36604 * @returns {!Long} Remainder
36605 */
36606 LongPrototype.mod = LongPrototype.modulo;
36607
36608 /**
36609 * Returns the bitwise NOT of this Long.
36610 * @returns {!Long}
36611 */
36612 LongPrototype.not = function not() {
36613 return fromBits(~this.low, ~this.high, this.unsigned);
36614 };
36615
36616 /**
36617 * Returns the bitwise AND of this Long and the specified.
36618 * @param {!Long|number|string} other Other Long
36619 * @returns {!Long}
36620 */
36621 LongPrototype.and = function and(other) {
36622 if (!isLong(other))
36623 other = fromValue(other);
36624 return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
36625 };
36626
36627 /**
36628 * Returns the bitwise OR of this Long and the specified.
36629 * @param {!Long|number|string} other Other Long
36630 * @returns {!Long}
36631 */
36632 LongPrototype.or = function or(other) {
36633 if (!isLong(other))
36634 other = fromValue(other);
36635 return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
36636 };
36637
36638 /**
36639 * Returns the bitwise XOR of this Long and the given one.
36640 * @param {!Long|number|string} other Other Long
36641 * @returns {!Long}
36642 */
36643 LongPrototype.xor = function xor(other) {
36644 if (!isLong(other))
36645 other = fromValue(other);
36646 return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
36647 };
36648
36649 /**
36650 * Returns this Long with bits shifted to the left by the given amount.
36651 * @param {number|!Long} numBits Number of bits
36652 * @returns {!Long} Shifted Long
36653 */
36654 LongPrototype.shiftLeft = function shiftLeft(numBits) {
36655 if (isLong(numBits))
36656 numBits = numBits.toInt();
36657 if ((numBits &= 63) === 0)
36658 return this;
36659 else if (numBits < 32)
36660 return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
36661 else
36662 return fromBits(0, this.low << (numBits - 32), this.unsigned);
36663 };
36664
36665 /**
36666 * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
36667 * @function
36668 * @param {number|!Long} numBits Number of bits
36669 * @returns {!Long} Shifted Long
36670 */
36671 LongPrototype.shl = LongPrototype.shiftLeft;
36672
36673 /**
36674 * Returns this Long with bits arithmetically shifted to the right by the given amount.
36675 * @param {number|!Long} numBits Number of bits
36676 * @returns {!Long} Shifted Long
36677 */
36678 LongPrototype.shiftRight = function shiftRight(numBits) {
36679 if (isLong(numBits))
36680 numBits = numBits.toInt();
36681 if ((numBits &= 63) === 0)
36682 return this;
36683 else if (numBits < 32)
36684 return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
36685 else
36686 return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
36687 };
36688
36689 /**
36690 * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
36691 * @function
36692 * @param {number|!Long} numBits Number of bits
36693 * @returns {!Long} Shifted Long
36694 */
36695 LongPrototype.shr = LongPrototype.shiftRight;
36696
36697 /**
36698 * Returns this Long with bits logically shifted to the right by the given amount.
36699 * @param {number|!Long} numBits Number of bits
36700 * @returns {!Long} Shifted Long
36701 */
36702 LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
36703 if (isLong(numBits))
36704 numBits = numBits.toInt();
36705 numBits &= 63;
36706 if (numBits === 0)
36707 return this;
36708 else {
36709 var high = this.high;
36710 if (numBits < 32) {
36711 var low = this.low;
36712 return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
36713 } else if (numBits === 32)
36714 return fromBits(high, 0, this.unsigned);
36715 else
36716 return fromBits(high >>> (numBits - 32), 0, this.unsigned);
36717 }
36718 };
36719
36720 /**
36721 * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
36722 * @function
36723 * @param {number|!Long} numBits Number of bits
36724 * @returns {!Long} Shifted Long
36725 */
36726 LongPrototype.shru = LongPrototype.shiftRightUnsigned;
36727
36728 /**
36729 * Converts this Long to signed.
36730 * @returns {!Long} Signed long
36731 */
36732 LongPrototype.toSigned = function toSigned() {
36733 if (!this.unsigned)
36734 return this;
36735 return fromBits(this.low, this.high, false);
36736 };
36737
36738 /**
36739 * Converts this Long to unsigned.
36740 * @returns {!Long} Unsigned long
36741 */
36742 LongPrototype.toUnsigned = function toUnsigned() {
36743 if (this.unsigned)
36744 return this;
36745 return fromBits(this.low, this.high, true);
36746 };
36747
36748 /**
36749 * Converts this Long to its byte representation.
36750 * @param {boolean=} le Whether little or big endian, defaults to big endian
36751 * @returns {!Array.<number>} Byte representation
36752 */
36753 LongPrototype.toBytes = function(le) {
36754 return le ? this.toBytesLE() : this.toBytesBE();
36755 }
36756
36757 /**
36758 * Converts this Long to its little endian byte representation.
36759 * @returns {!Array.<number>} Little endian byte representation
36760 */
36761 LongPrototype.toBytesLE = function() {
36762 var hi = this.high,
36763 lo = this.low;
36764 return [
36765 lo & 0xff,
36766 (lo >>> 8) & 0xff,
36767 (lo >>> 16) & 0xff,
36768 (lo >>> 24) & 0xff,
36769 hi & 0xff,
36770 (hi >>> 8) & 0xff,
36771 (hi >>> 16) & 0xff,
36772 (hi >>> 24) & 0xff
36773 ];
36774 }
36775
36776 /**
36777 * Converts this Long to its big endian byte representation.
36778 * @returns {!Array.<number>} Big endian byte representation
36779 */
36780 LongPrototype.toBytesBE = function() {
36781 var hi = this.high,
36782 lo = this.low;
36783 return [
36784 (hi >>> 24) & 0xff,
36785 (hi >>> 16) & 0xff,
36786 (hi >>> 8) & 0xff,
36787 hi & 0xff,
36788 (lo >>> 24) & 0xff,
36789 (lo >>> 16) & 0xff,
36790 (lo >>> 8) & 0xff,
36791 lo & 0xff
36792 ];
36793 }
36794
36795 return Long;
36796});
36797
36798
36799/***/ }),
36800/* 412 */
36801/***/ (function(module, exports) {
36802
36803/* (ignored) */
36804
36805/***/ }),
36806/* 413 */
36807/***/ (function(module, exports, __webpack_require__) {
36808
36809"use strict";
36810
36811
36812var _getOwnPropertySymbols = __webpack_require__(198);
36813
36814var _getOwnPropertySymbols2 = _interopRequireDefault(_getOwnPropertySymbols);
36815
36816var _create = __webpack_require__(111);
36817
36818var _create2 = _interopRequireDefault(_create);
36819
36820function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
36821
36822var has = Object.prototype.hasOwnProperty,
36823 prefix = '~';
36824
36825/**
36826 * Constructor to create a storage for our `EE` objects.
36827 * An `Events` instance is a plain object whose properties are event names.
36828 *
36829 * @constructor
36830 * @private
36831 */
36832function Events() {}
36833
36834//
36835// We try to not inherit from `Object.prototype`. In some engines creating an
36836// instance in this way is faster than calling `Object.create(null)` directly.
36837// If `Object.create(null)` is not supported we prefix the event names with a
36838// character to make sure that the built-in object properties are not
36839// overridden or used as an attack vector.
36840//
36841if (_create2.default) {
36842 Events.prototype = (0, _create2.default)(null);
36843
36844 //
36845 // This hack is needed because the `__proto__` property is still inherited in
36846 // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
36847 //
36848 if (!new Events().__proto__) prefix = false;
36849}
36850
36851/**
36852 * Representation of a single event listener.
36853 *
36854 * @param {Function} fn The listener function.
36855 * @param {*} context The context to invoke the listener with.
36856 * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
36857 * @constructor
36858 * @private
36859 */
36860function EE(fn, context, once) {
36861 this.fn = fn;
36862 this.context = context;
36863 this.once = once || false;
36864}
36865
36866/**
36867 * Add a listener for a given event.
36868 *
36869 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
36870 * @param {(String|Symbol)} event The event name.
36871 * @param {Function} fn The listener function.
36872 * @param {*} context The context to invoke the listener with.
36873 * @param {Boolean} once Specify if the listener is a one-time listener.
36874 * @returns {EventEmitter}
36875 * @private
36876 */
36877function addListener(emitter, event, fn, context, once) {
36878 if (typeof fn !== 'function') {
36879 throw new TypeError('The listener must be a function');
36880 }
36881
36882 var listener = new EE(fn, context || emitter, once),
36883 evt = prefix ? prefix + event : event;
36884
36885 if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);else emitter._events[evt] = [emitter._events[evt], listener];
36886
36887 return emitter;
36888}
36889
36890/**
36891 * Clear event by name.
36892 *
36893 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
36894 * @param {(String|Symbol)} evt The Event name.
36895 * @private
36896 */
36897function clearEvent(emitter, evt) {
36898 if (--emitter._eventsCount === 0) emitter._events = new Events();else delete emitter._events[evt];
36899}
36900
36901/**
36902 * Minimal `EventEmitter` interface that is molded against the Node.js
36903 * `EventEmitter` interface.
36904 *
36905 * @constructor
36906 * @public
36907 */
36908function EventEmitter() {
36909 this._events = new Events();
36910 this._eventsCount = 0;
36911}
36912
36913/**
36914 * Return an array listing the events for which the emitter has registered
36915 * listeners.
36916 *
36917 * @returns {Array}
36918 * @public
36919 */
36920EventEmitter.prototype.eventNames = function eventNames() {
36921 var names = [],
36922 events,
36923 name;
36924
36925 if (this._eventsCount === 0) return names;
36926
36927 for (name in events = this._events) {
36928 if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
36929 }
36930
36931 if (_getOwnPropertySymbols2.default) {
36932 return names.concat((0, _getOwnPropertySymbols2.default)(events));
36933 }
36934
36935 return names;
36936};
36937
36938/**
36939 * Return the listeners registered for a given event.
36940 *
36941 * @param {(String|Symbol)} event The event name.
36942 * @returns {Array} The registered listeners.
36943 * @public
36944 */
36945EventEmitter.prototype.listeners = function listeners(event) {
36946 var evt = prefix ? prefix + event : event,
36947 handlers = this._events[evt];
36948
36949 if (!handlers) return [];
36950 if (handlers.fn) return [handlers.fn];
36951
36952 for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
36953 ee[i] = handlers[i].fn;
36954 }
36955
36956 return ee;
36957};
36958
36959/**
36960 * Return the number of listeners listening to a given event.
36961 *
36962 * @param {(String|Symbol)} event The event name.
36963 * @returns {Number} The number of listeners.
36964 * @public
36965 */
36966EventEmitter.prototype.listenerCount = function listenerCount(event) {
36967 var evt = prefix ? prefix + event : event,
36968 listeners = this._events[evt];
36969
36970 if (!listeners) return 0;
36971 if (listeners.fn) return 1;
36972 return listeners.length;
36973};
36974
36975/**
36976 * Calls each of the listeners registered for a given event.
36977 *
36978 * @param {(String|Symbol)} event The event name.
36979 * @returns {Boolean} `true` if the event had listeners, else `false`.
36980 * @public
36981 */
36982EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
36983 var evt = prefix ? prefix + event : event;
36984
36985 if (!this._events[evt]) return false;
36986
36987 var listeners = this._events[evt],
36988 len = arguments.length,
36989 args,
36990 i;
36991
36992 if (listeners.fn) {
36993 if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
36994
36995 switch (len) {
36996 case 1:
36997 return listeners.fn.call(listeners.context), true;
36998 case 2:
36999 return listeners.fn.call(listeners.context, a1), true;
37000 case 3:
37001 return listeners.fn.call(listeners.context, a1, a2), true;
37002 case 4:
37003 return listeners.fn.call(listeners.context, a1, a2, a3), true;
37004 case 5:
37005 return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
37006 case 6:
37007 return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
37008 }
37009
37010 for (i = 1, args = new Array(len - 1); i < len; i++) {
37011 args[i - 1] = arguments[i];
37012 }
37013
37014 listeners.fn.apply(listeners.context, args);
37015 } else {
37016 var length = listeners.length,
37017 j;
37018
37019 for (i = 0; i < length; i++) {
37020 if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
37021
37022 switch (len) {
37023 case 1:
37024 listeners[i].fn.call(listeners[i].context);break;
37025 case 2:
37026 listeners[i].fn.call(listeners[i].context, a1);break;
37027 case 3:
37028 listeners[i].fn.call(listeners[i].context, a1, a2);break;
37029 case 4:
37030 listeners[i].fn.call(listeners[i].context, a1, a2, a3);break;
37031 default:
37032 if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) {
37033 args[j - 1] = arguments[j];
37034 }
37035
37036 listeners[i].fn.apply(listeners[i].context, args);
37037 }
37038 }
37039 }
37040
37041 return true;
37042};
37043
37044/**
37045 * Add a listener for a given event.
37046 *
37047 * @param {(String|Symbol)} event The event name.
37048 * @param {Function} fn The listener function.
37049 * @param {*} [context=this] The context to invoke the listener with.
37050 * @returns {EventEmitter} `this`.
37051 * @public
37052 */
37053EventEmitter.prototype.on = function on(event, fn, context) {
37054 return addListener(this, event, fn, context, false);
37055};
37056
37057/**
37058 * Add a one-time listener for a given event.
37059 *
37060 * @param {(String|Symbol)} event The event name.
37061 * @param {Function} fn The listener function.
37062 * @param {*} [context=this] The context to invoke the listener with.
37063 * @returns {EventEmitter} `this`.
37064 * @public
37065 */
37066EventEmitter.prototype.once = function once(event, fn, context) {
37067 return addListener(this, event, fn, context, true);
37068};
37069
37070/**
37071 * Remove the listeners of a given event.
37072 *
37073 * @param {(String|Symbol)} event The event name.
37074 * @param {Function} fn Only remove the listeners that match this function.
37075 * @param {*} context Only remove the listeners that have this context.
37076 * @param {Boolean} once Only remove one-time listeners.
37077 * @returns {EventEmitter} `this`.
37078 * @public
37079 */
37080EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
37081 var evt = prefix ? prefix + event : event;
37082
37083 if (!this._events[evt]) return this;
37084 if (!fn) {
37085 clearEvent(this, evt);
37086 return this;
37087 }
37088
37089 var listeners = this._events[evt];
37090
37091 if (listeners.fn) {
37092 if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
37093 clearEvent(this, evt);
37094 }
37095 } else {
37096 for (var i = 0, events = [], length = listeners.length; i < length; i++) {
37097 if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
37098 events.push(listeners[i]);
37099 }
37100 }
37101
37102 //
37103 // Reset the array, or remove it completely if we have no more listeners.
37104 //
37105 if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;else clearEvent(this, evt);
37106 }
37107
37108 return this;
37109};
37110
37111/**
37112 * Remove all listeners, or those of the specified event.
37113 *
37114 * @param {(String|Symbol)} [event] The event name.
37115 * @returns {EventEmitter} `this`.
37116 * @public
37117 */
37118EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
37119 var evt;
37120
37121 if (event) {
37122 evt = prefix ? prefix + event : event;
37123 if (this._events[evt]) clearEvent(this, evt);
37124 } else {
37125 this._events = new Events();
37126 this._eventsCount = 0;
37127 }
37128
37129 return this;
37130};
37131
37132//
37133// Alias methods names because people roll like that.
37134//
37135EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
37136EventEmitter.prototype.addListener = EventEmitter.prototype.on;
37137
37138//
37139// Expose the prefix.
37140//
37141EventEmitter.prefixed = prefix;
37142
37143//
37144// Allow `EventEmitter` to be imported as module namespace.
37145//
37146EventEmitter.EventEmitter = EventEmitter;
37147
37148//
37149// Expose the module.
37150//
37151if (true) {
37152 module.exports = EventEmitter;
37153}
37154
37155/***/ }),
37156/* 414 */
37157/***/ (function(module, exports, __webpack_require__) {
37158
37159module.exports = __webpack_require__(415);
37160
37161
37162/***/ }),
37163/* 415 */
37164/***/ (function(module, exports, __webpack_require__) {
37165
37166/**
37167 * Copyright (c) 2014-present, Facebook, Inc.
37168 *
37169 * This source code is licensed under the MIT license found in the
37170 * LICENSE file in the root directory of this source tree.
37171 */
37172
37173var runtime = (function (exports) {
37174 "use strict";
37175
37176 var Op = Object.prototype;
37177 var hasOwn = Op.hasOwnProperty;
37178 var undefined; // More compressible than void 0.
37179 var $Symbol = typeof Symbol === "function" ? Symbol : {};
37180 var iteratorSymbol = $Symbol.iterator || "@@iterator";
37181 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
37182 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
37183
37184 function define(obj, key, value) {
37185 Object.defineProperty(obj, key, {
37186 value: value,
37187 enumerable: true,
37188 configurable: true,
37189 writable: true
37190 });
37191 return obj[key];
37192 }
37193 try {
37194 // IE 8 has a broken Object.defineProperty that only works on DOM objects.
37195 define({}, "");
37196 } catch (err) {
37197 define = function(obj, key, value) {
37198 return obj[key] = value;
37199 };
37200 }
37201
37202 function wrap(innerFn, outerFn, self, tryLocsList) {
37203 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
37204 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
37205 var generator = Object.create(protoGenerator.prototype);
37206 var context = new Context(tryLocsList || []);
37207
37208 // The ._invoke method unifies the implementations of the .next,
37209 // .throw, and .return methods.
37210 generator._invoke = makeInvokeMethod(innerFn, self, context);
37211
37212 return generator;
37213 }
37214 exports.wrap = wrap;
37215
37216 // Try/catch helper to minimize deoptimizations. Returns a completion
37217 // record like context.tryEntries[i].completion. This interface could
37218 // have been (and was previously) designed to take a closure to be
37219 // invoked without arguments, but in all the cases we care about we
37220 // already have an existing method we want to call, so there's no need
37221 // to create a new function object. We can even get away with assuming
37222 // the method takes exactly one argument, since that happens to be true
37223 // in every case, so we don't have to touch the arguments object. The
37224 // only additional allocation required is the completion record, which
37225 // has a stable shape and so hopefully should be cheap to allocate.
37226 function tryCatch(fn, obj, arg) {
37227 try {
37228 return { type: "normal", arg: fn.call(obj, arg) };
37229 } catch (err) {
37230 return { type: "throw", arg: err };
37231 }
37232 }
37233
37234 var GenStateSuspendedStart = "suspendedStart";
37235 var GenStateSuspendedYield = "suspendedYield";
37236 var GenStateExecuting = "executing";
37237 var GenStateCompleted = "completed";
37238
37239 // Returning this object from the innerFn has the same effect as
37240 // breaking out of the dispatch switch statement.
37241 var ContinueSentinel = {};
37242
37243 // Dummy constructor functions that we use as the .constructor and
37244 // .constructor.prototype properties for functions that return Generator
37245 // objects. For full spec compliance, you may wish to configure your
37246 // minifier not to mangle the names of these two functions.
37247 function Generator() {}
37248 function GeneratorFunction() {}
37249 function GeneratorFunctionPrototype() {}
37250
37251 // This is a polyfill for %IteratorPrototype% for environments that
37252 // don't natively support it.
37253 var IteratorPrototype = {};
37254 IteratorPrototype[iteratorSymbol] = function () {
37255 return this;
37256 };
37257
37258 var getProto = Object.getPrototypeOf;
37259 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
37260 if (NativeIteratorPrototype &&
37261 NativeIteratorPrototype !== Op &&
37262 hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
37263 // This environment has a native %IteratorPrototype%; use it instead
37264 // of the polyfill.
37265 IteratorPrototype = NativeIteratorPrototype;
37266 }
37267
37268 var Gp = GeneratorFunctionPrototype.prototype =
37269 Generator.prototype = Object.create(IteratorPrototype);
37270 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
37271 GeneratorFunctionPrototype.constructor = GeneratorFunction;
37272 GeneratorFunction.displayName = define(
37273 GeneratorFunctionPrototype,
37274 toStringTagSymbol,
37275 "GeneratorFunction"
37276 );
37277
37278 // Helper for defining the .next, .throw, and .return methods of the
37279 // Iterator interface in terms of a single ._invoke method.
37280 function defineIteratorMethods(prototype) {
37281 ["next", "throw", "return"].forEach(function(method) {
37282 define(prototype, method, function(arg) {
37283 return this._invoke(method, arg);
37284 });
37285 });
37286 }
37287
37288 exports.isGeneratorFunction = function(genFun) {
37289 var ctor = typeof genFun === "function" && genFun.constructor;
37290 return ctor
37291 ? ctor === GeneratorFunction ||
37292 // For the native GeneratorFunction constructor, the best we can
37293 // do is to check its .name property.
37294 (ctor.displayName || ctor.name) === "GeneratorFunction"
37295 : false;
37296 };
37297
37298 exports.mark = function(genFun) {
37299 if (Object.setPrototypeOf) {
37300 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
37301 } else {
37302 genFun.__proto__ = GeneratorFunctionPrototype;
37303 define(genFun, toStringTagSymbol, "GeneratorFunction");
37304 }
37305 genFun.prototype = Object.create(Gp);
37306 return genFun;
37307 };
37308
37309 // Within the body of any async function, `await x` is transformed to
37310 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
37311 // `hasOwn.call(value, "__await")` to determine if the yielded value is
37312 // meant to be awaited.
37313 exports.awrap = function(arg) {
37314 return { __await: arg };
37315 };
37316
37317 function AsyncIterator(generator, PromiseImpl) {
37318 function invoke(method, arg, resolve, reject) {
37319 var record = tryCatch(generator[method], generator, arg);
37320 if (record.type === "throw") {
37321 reject(record.arg);
37322 } else {
37323 var result = record.arg;
37324 var value = result.value;
37325 if (value &&
37326 typeof value === "object" &&
37327 hasOwn.call(value, "__await")) {
37328 return PromiseImpl.resolve(value.__await).then(function(value) {
37329 invoke("next", value, resolve, reject);
37330 }, function(err) {
37331 invoke("throw", err, resolve, reject);
37332 });
37333 }
37334
37335 return PromiseImpl.resolve(value).then(function(unwrapped) {
37336 // When a yielded Promise is resolved, its final value becomes
37337 // the .value of the Promise<{value,done}> result for the
37338 // current iteration.
37339 result.value = unwrapped;
37340 resolve(result);
37341 }, function(error) {
37342 // If a rejected Promise was yielded, throw the rejection back
37343 // into the async generator function so it can be handled there.
37344 return invoke("throw", error, resolve, reject);
37345 });
37346 }
37347 }
37348
37349 var previousPromise;
37350
37351 function enqueue(method, arg) {
37352 function callInvokeWithMethodAndArg() {
37353 return new PromiseImpl(function(resolve, reject) {
37354 invoke(method, arg, resolve, reject);
37355 });
37356 }
37357
37358 return previousPromise =
37359 // If enqueue has been called before, then we want to wait until
37360 // all previous Promises have been resolved before calling invoke,
37361 // so that results are always delivered in the correct order. If
37362 // enqueue has not been called before, then it is important to
37363 // call invoke immediately, without waiting on a callback to fire,
37364 // so that the async generator function has the opportunity to do
37365 // any necessary setup in a predictable way. This predictability
37366 // is why the Promise constructor synchronously invokes its
37367 // executor callback, and why async functions synchronously
37368 // execute code before the first await. Since we implement simple
37369 // async functions in terms of async generators, it is especially
37370 // important to get this right, even though it requires care.
37371 previousPromise ? previousPromise.then(
37372 callInvokeWithMethodAndArg,
37373 // Avoid propagating failures to Promises returned by later
37374 // invocations of the iterator.
37375 callInvokeWithMethodAndArg
37376 ) : callInvokeWithMethodAndArg();
37377 }
37378
37379 // Define the unified helper method that is used to implement .next,
37380 // .throw, and .return (see defineIteratorMethods).
37381 this._invoke = enqueue;
37382 }
37383
37384 defineIteratorMethods(AsyncIterator.prototype);
37385 AsyncIterator.prototype[asyncIteratorSymbol] = function () {
37386 return this;
37387 };
37388 exports.AsyncIterator = AsyncIterator;
37389
37390 // Note that simple async functions are implemented on top of
37391 // AsyncIterator objects; they just return a Promise for the value of
37392 // the final result produced by the iterator.
37393 exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
37394 if (PromiseImpl === void 0) PromiseImpl = Promise;
37395
37396 var iter = new AsyncIterator(
37397 wrap(innerFn, outerFn, self, tryLocsList),
37398 PromiseImpl
37399 );
37400
37401 return exports.isGeneratorFunction(outerFn)
37402 ? iter // If outerFn is a generator, return the full iterator.
37403 : iter.next().then(function(result) {
37404 return result.done ? result.value : iter.next();
37405 });
37406 };
37407
37408 function makeInvokeMethod(innerFn, self, context) {
37409 var state = GenStateSuspendedStart;
37410
37411 return function invoke(method, arg) {
37412 if (state === GenStateExecuting) {
37413 throw new Error("Generator is already running");
37414 }
37415
37416 if (state === GenStateCompleted) {
37417 if (method === "throw") {
37418 throw arg;
37419 }
37420
37421 // Be forgiving, per 25.3.3.3.3 of the spec:
37422 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
37423 return doneResult();
37424 }
37425
37426 context.method = method;
37427 context.arg = arg;
37428
37429 while (true) {
37430 var delegate = context.delegate;
37431 if (delegate) {
37432 var delegateResult = maybeInvokeDelegate(delegate, context);
37433 if (delegateResult) {
37434 if (delegateResult === ContinueSentinel) continue;
37435 return delegateResult;
37436 }
37437 }
37438
37439 if (context.method === "next") {
37440 // Setting context._sent for legacy support of Babel's
37441 // function.sent implementation.
37442 context.sent = context._sent = context.arg;
37443
37444 } else if (context.method === "throw") {
37445 if (state === GenStateSuspendedStart) {
37446 state = GenStateCompleted;
37447 throw context.arg;
37448 }
37449
37450 context.dispatchException(context.arg);
37451
37452 } else if (context.method === "return") {
37453 context.abrupt("return", context.arg);
37454 }
37455
37456 state = GenStateExecuting;
37457
37458 var record = tryCatch(innerFn, self, context);
37459 if (record.type === "normal") {
37460 // If an exception is thrown from innerFn, we leave state ===
37461 // GenStateExecuting and loop back for another invocation.
37462 state = context.done
37463 ? GenStateCompleted
37464 : GenStateSuspendedYield;
37465
37466 if (record.arg === ContinueSentinel) {
37467 continue;
37468 }
37469
37470 return {
37471 value: record.arg,
37472 done: context.done
37473 };
37474
37475 } else if (record.type === "throw") {
37476 state = GenStateCompleted;
37477 // Dispatch the exception by looping back around to the
37478 // context.dispatchException(context.arg) call above.
37479 context.method = "throw";
37480 context.arg = record.arg;
37481 }
37482 }
37483 };
37484 }
37485
37486 // Call delegate.iterator[context.method](context.arg) and handle the
37487 // result, either by returning a { value, done } result from the
37488 // delegate iterator, or by modifying context.method and context.arg,
37489 // setting context.delegate to null, and returning the ContinueSentinel.
37490 function maybeInvokeDelegate(delegate, context) {
37491 var method = delegate.iterator[context.method];
37492 if (method === undefined) {
37493 // A .throw or .return when the delegate iterator has no .throw
37494 // method always terminates the yield* loop.
37495 context.delegate = null;
37496
37497 if (context.method === "throw") {
37498 // Note: ["return"] must be used for ES3 parsing compatibility.
37499 if (delegate.iterator["return"]) {
37500 // If the delegate iterator has a return method, give it a
37501 // chance to clean up.
37502 context.method = "return";
37503 context.arg = undefined;
37504 maybeInvokeDelegate(delegate, context);
37505
37506 if (context.method === "throw") {
37507 // If maybeInvokeDelegate(context) changed context.method from
37508 // "return" to "throw", let that override the TypeError below.
37509 return ContinueSentinel;
37510 }
37511 }
37512
37513 context.method = "throw";
37514 context.arg = new TypeError(
37515 "The iterator does not provide a 'throw' method");
37516 }
37517
37518 return ContinueSentinel;
37519 }
37520
37521 var record = tryCatch(method, delegate.iterator, context.arg);
37522
37523 if (record.type === "throw") {
37524 context.method = "throw";
37525 context.arg = record.arg;
37526 context.delegate = null;
37527 return ContinueSentinel;
37528 }
37529
37530 var info = record.arg;
37531
37532 if (! info) {
37533 context.method = "throw";
37534 context.arg = new TypeError("iterator result is not an object");
37535 context.delegate = null;
37536 return ContinueSentinel;
37537 }
37538
37539 if (info.done) {
37540 // Assign the result of the finished delegate to the temporary
37541 // variable specified by delegate.resultName (see delegateYield).
37542 context[delegate.resultName] = info.value;
37543
37544 // Resume execution at the desired location (see delegateYield).
37545 context.next = delegate.nextLoc;
37546
37547 // If context.method was "throw" but the delegate handled the
37548 // exception, let the outer generator proceed normally. If
37549 // context.method was "next", forget context.arg since it has been
37550 // "consumed" by the delegate iterator. If context.method was
37551 // "return", allow the original .return call to continue in the
37552 // outer generator.
37553 if (context.method !== "return") {
37554 context.method = "next";
37555 context.arg = undefined;
37556 }
37557
37558 } else {
37559 // Re-yield the result returned by the delegate method.
37560 return info;
37561 }
37562
37563 // The delegate iterator is finished, so forget it and continue with
37564 // the outer generator.
37565 context.delegate = null;
37566 return ContinueSentinel;
37567 }
37568
37569 // Define Generator.prototype.{next,throw,return} in terms of the
37570 // unified ._invoke helper method.
37571 defineIteratorMethods(Gp);
37572
37573 define(Gp, toStringTagSymbol, "Generator");
37574
37575 // A Generator should always return itself as the iterator object when the
37576 // @@iterator function is called on it. Some browsers' implementations of the
37577 // iterator prototype chain incorrectly implement this, causing the Generator
37578 // object to not be returned from this call. This ensures that doesn't happen.
37579 // See https://github.com/facebook/regenerator/issues/274 for more details.
37580 Gp[iteratorSymbol] = function() {
37581 return this;
37582 };
37583
37584 Gp.toString = function() {
37585 return "[object Generator]";
37586 };
37587
37588 function pushTryEntry(locs) {
37589 var entry = { tryLoc: locs[0] };
37590
37591 if (1 in locs) {
37592 entry.catchLoc = locs[1];
37593 }
37594
37595 if (2 in locs) {
37596 entry.finallyLoc = locs[2];
37597 entry.afterLoc = locs[3];
37598 }
37599
37600 this.tryEntries.push(entry);
37601 }
37602
37603 function resetTryEntry(entry) {
37604 var record = entry.completion || {};
37605 record.type = "normal";
37606 delete record.arg;
37607 entry.completion = record;
37608 }
37609
37610 function Context(tryLocsList) {
37611 // The root entry object (effectively a try statement without a catch
37612 // or a finally block) gives us a place to store values thrown from
37613 // locations where there is no enclosing try statement.
37614 this.tryEntries = [{ tryLoc: "root" }];
37615 tryLocsList.forEach(pushTryEntry, this);
37616 this.reset(true);
37617 }
37618
37619 exports.keys = function(object) {
37620 var keys = [];
37621 for (var key in object) {
37622 keys.push(key);
37623 }
37624 keys.reverse();
37625
37626 // Rather than returning an object with a next method, we keep
37627 // things simple and return the next function itself.
37628 return function next() {
37629 while (keys.length) {
37630 var key = keys.pop();
37631 if (key in object) {
37632 next.value = key;
37633 next.done = false;
37634 return next;
37635 }
37636 }
37637
37638 // To avoid creating an additional object, we just hang the .value
37639 // and .done properties off the next function object itself. This
37640 // also ensures that the minifier will not anonymize the function.
37641 next.done = true;
37642 return next;
37643 };
37644 };
37645
37646 function values(iterable) {
37647 if (iterable) {
37648 var iteratorMethod = iterable[iteratorSymbol];
37649 if (iteratorMethod) {
37650 return iteratorMethod.call(iterable);
37651 }
37652
37653 if (typeof iterable.next === "function") {
37654 return iterable;
37655 }
37656
37657 if (!isNaN(iterable.length)) {
37658 var i = -1, next = function next() {
37659 while (++i < iterable.length) {
37660 if (hasOwn.call(iterable, i)) {
37661 next.value = iterable[i];
37662 next.done = false;
37663 return next;
37664 }
37665 }
37666
37667 next.value = undefined;
37668 next.done = true;
37669
37670 return next;
37671 };
37672
37673 return next.next = next;
37674 }
37675 }
37676
37677 // Return an iterator with no values.
37678 return { next: doneResult };
37679 }
37680 exports.values = values;
37681
37682 function doneResult() {
37683 return { value: undefined, done: true };
37684 }
37685
37686 Context.prototype = {
37687 constructor: Context,
37688
37689 reset: function(skipTempReset) {
37690 this.prev = 0;
37691 this.next = 0;
37692 // Resetting context._sent for legacy support of Babel's
37693 // function.sent implementation.
37694 this.sent = this._sent = undefined;
37695 this.done = false;
37696 this.delegate = null;
37697
37698 this.method = "next";
37699 this.arg = undefined;
37700
37701 this.tryEntries.forEach(resetTryEntry);
37702
37703 if (!skipTempReset) {
37704 for (var name in this) {
37705 // Not sure about the optimal order of these conditions:
37706 if (name.charAt(0) === "t" &&
37707 hasOwn.call(this, name) &&
37708 !isNaN(+name.slice(1))) {
37709 this[name] = undefined;
37710 }
37711 }
37712 }
37713 },
37714
37715 stop: function() {
37716 this.done = true;
37717
37718 var rootEntry = this.tryEntries[0];
37719 var rootRecord = rootEntry.completion;
37720 if (rootRecord.type === "throw") {
37721 throw rootRecord.arg;
37722 }
37723
37724 return this.rval;
37725 },
37726
37727 dispatchException: function(exception) {
37728 if (this.done) {
37729 throw exception;
37730 }
37731
37732 var context = this;
37733 function handle(loc, caught) {
37734 record.type = "throw";
37735 record.arg = exception;
37736 context.next = loc;
37737
37738 if (caught) {
37739 // If the dispatched exception was caught by a catch block,
37740 // then let that catch block handle the exception normally.
37741 context.method = "next";
37742 context.arg = undefined;
37743 }
37744
37745 return !! caught;
37746 }
37747
37748 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
37749 var entry = this.tryEntries[i];
37750 var record = entry.completion;
37751
37752 if (entry.tryLoc === "root") {
37753 // Exception thrown outside of any try block that could handle
37754 // it, so set the completion value of the entire function to
37755 // throw the exception.
37756 return handle("end");
37757 }
37758
37759 if (entry.tryLoc <= this.prev) {
37760 var hasCatch = hasOwn.call(entry, "catchLoc");
37761 var hasFinally = hasOwn.call(entry, "finallyLoc");
37762
37763 if (hasCatch && hasFinally) {
37764 if (this.prev < entry.catchLoc) {
37765 return handle(entry.catchLoc, true);
37766 } else if (this.prev < entry.finallyLoc) {
37767 return handle(entry.finallyLoc);
37768 }
37769
37770 } else if (hasCatch) {
37771 if (this.prev < entry.catchLoc) {
37772 return handle(entry.catchLoc, true);
37773 }
37774
37775 } else if (hasFinally) {
37776 if (this.prev < entry.finallyLoc) {
37777 return handle(entry.finallyLoc);
37778 }
37779
37780 } else {
37781 throw new Error("try statement without catch or finally");
37782 }
37783 }
37784 }
37785 },
37786
37787 abrupt: function(type, arg) {
37788 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
37789 var entry = this.tryEntries[i];
37790 if (entry.tryLoc <= this.prev &&
37791 hasOwn.call(entry, "finallyLoc") &&
37792 this.prev < entry.finallyLoc) {
37793 var finallyEntry = entry;
37794 break;
37795 }
37796 }
37797
37798 if (finallyEntry &&
37799 (type === "break" ||
37800 type === "continue") &&
37801 finallyEntry.tryLoc <= arg &&
37802 arg <= finallyEntry.finallyLoc) {
37803 // Ignore the finally entry if control is not jumping to a
37804 // location outside the try/catch block.
37805 finallyEntry = null;
37806 }
37807
37808 var record = finallyEntry ? finallyEntry.completion : {};
37809 record.type = type;
37810 record.arg = arg;
37811
37812 if (finallyEntry) {
37813 this.method = "next";
37814 this.next = finallyEntry.finallyLoc;
37815 return ContinueSentinel;
37816 }
37817
37818 return this.complete(record);
37819 },
37820
37821 complete: function(record, afterLoc) {
37822 if (record.type === "throw") {
37823 throw record.arg;
37824 }
37825
37826 if (record.type === "break" ||
37827 record.type === "continue") {
37828 this.next = record.arg;
37829 } else if (record.type === "return") {
37830 this.rval = this.arg = record.arg;
37831 this.method = "return";
37832 this.next = "end";
37833 } else if (record.type === "normal" && afterLoc) {
37834 this.next = afterLoc;
37835 }
37836
37837 return ContinueSentinel;
37838 },
37839
37840 finish: function(finallyLoc) {
37841 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
37842 var entry = this.tryEntries[i];
37843 if (entry.finallyLoc === finallyLoc) {
37844 this.complete(entry.completion, entry.afterLoc);
37845 resetTryEntry(entry);
37846 return ContinueSentinel;
37847 }
37848 }
37849 },
37850
37851 "catch": function(tryLoc) {
37852 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
37853 var entry = this.tryEntries[i];
37854 if (entry.tryLoc === tryLoc) {
37855 var record = entry.completion;
37856 if (record.type === "throw") {
37857 var thrown = record.arg;
37858 resetTryEntry(entry);
37859 }
37860 return thrown;
37861 }
37862 }
37863
37864 // The context.catch method must only be called with a location
37865 // argument that corresponds to a known catch block.
37866 throw new Error("illegal catch attempt");
37867 },
37868
37869 delegateYield: function(iterable, resultName, nextLoc) {
37870 this.delegate = {
37871 iterator: values(iterable),
37872 resultName: resultName,
37873 nextLoc: nextLoc
37874 };
37875
37876 if (this.method === "next") {
37877 // Deliberately forget the last sent value so that we don't
37878 // accidentally pass it on to the delegate.
37879 this.arg = undefined;
37880 }
37881
37882 return ContinueSentinel;
37883 }
37884 };
37885
37886 // Regardless of whether this script is executing as a CommonJS module
37887 // or not, return the runtime object so that we can declare the variable
37888 // regeneratorRuntime in the outer scope, which allows this module to be
37889 // injected easily by `bin/regenerator --include-runtime script.js`.
37890 return exports;
37891
37892}(
37893 // If this script is executing as a CommonJS module, use module.exports
37894 // as the regeneratorRuntime namespace. Otherwise create a new empty
37895 // object. Either way, the resulting object will be used to initialize
37896 // the regeneratorRuntime variable at the top of this file.
37897 true ? module.exports : {}
37898));
37899
37900try {
37901 regeneratorRuntime = runtime;
37902} catch (accidentalStrictMode) {
37903 // This module should not be running in strict mode, so the above
37904 // assignment should always work unless something is misconfigured. Just
37905 // in case runtime.js accidentally runs in strict mode, we can escape
37906 // strict mode using a global Function call. This could conceivably fail
37907 // if a Content Security Policy forbids using Function, but in that case
37908 // the proper solution is to fix the accidental strict mode problem. If
37909 // you've misconfigured your bundler to force strict mode and applied a
37910 // CSP to forbid Function, and you're not willing to fix either of those
37911 // problems, please detail your unique predicament in a GitHub issue.
37912 Function("r", "regeneratorRuntime = r")(runtime);
37913}
37914
37915
37916/***/ }),
37917/* 416 */
37918/***/ (function(module, exports) {
37919
37920function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
37921 try {
37922 var info = gen[key](arg);
37923 var value = info.value;
37924 } catch (error) {
37925 reject(error);
37926 return;
37927 }
37928
37929 if (info.done) {
37930 resolve(value);
37931 } else {
37932 Promise.resolve(value).then(_next, _throw);
37933 }
37934}
37935
37936function _asyncToGenerator(fn) {
37937 return function () {
37938 var self = this,
37939 args = arguments;
37940 return new Promise(function (resolve, reject) {
37941 var gen = fn.apply(self, args);
37942
37943 function _next(value) {
37944 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
37945 }
37946
37947 function _throw(err) {
37948 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
37949 }
37950
37951 _next(undefined);
37952 });
37953 };
37954}
37955
37956module.exports = _asyncToGenerator;
37957
37958/***/ }),
37959/* 417 */
37960/***/ (function(module, exports, __webpack_require__) {
37961
37962var arrayWithoutHoles = __webpack_require__(418);
37963
37964var iterableToArray = __webpack_require__(201);
37965
37966var unsupportedIterableToArray = __webpack_require__(202);
37967
37968var nonIterableSpread = __webpack_require__(419);
37969
37970function _toConsumableArray(arr) {
37971 return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
37972}
37973
37974module.exports = _toConsumableArray;
37975
37976/***/ }),
37977/* 418 */
37978/***/ (function(module, exports, __webpack_require__) {
37979
37980var arrayLikeToArray = __webpack_require__(200);
37981
37982function _arrayWithoutHoles(arr) {
37983 if (Array.isArray(arr)) return arrayLikeToArray(arr);
37984}
37985
37986module.exports = _arrayWithoutHoles;
37987
37988/***/ }),
37989/* 419 */
37990/***/ (function(module, exports) {
37991
37992function _nonIterableSpread() {
37993 throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
37994}
37995
37996module.exports = _nonIterableSpread;
37997
37998/***/ }),
37999/* 420 */
38000/***/ (function(module, exports) {
38001
38002function _defineProperty(obj, key, value) {
38003 if (key in obj) {
38004 Object.defineProperty(obj, key, {
38005 value: value,
38006 enumerable: true,
38007 configurable: true,
38008 writable: true
38009 });
38010 } else {
38011 obj[key] = value;
38012 }
38013
38014 return obj;
38015}
38016
38017module.exports = _defineProperty;
38018
38019/***/ }),
38020/* 421 */
38021/***/ (function(module, exports, __webpack_require__) {
38022
38023var objectWithoutPropertiesLoose = __webpack_require__(422);
38024
38025function _objectWithoutProperties(source, excluded) {
38026 if (source == null) return {};
38027 var target = objectWithoutPropertiesLoose(source, excluded);
38028 var key, i;
38029
38030 if (Object.getOwnPropertySymbols) {
38031 var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
38032
38033 for (i = 0; i < sourceSymbolKeys.length; i++) {
38034 key = sourceSymbolKeys[i];
38035 if (excluded.indexOf(key) >= 0) continue;
38036 if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
38037 target[key] = source[key];
38038 }
38039 }
38040
38041 return target;
38042}
38043
38044module.exports = _objectWithoutProperties;
38045
38046/***/ }),
38047/* 422 */
38048/***/ (function(module, exports) {
38049
38050function _objectWithoutPropertiesLoose(source, excluded) {
38051 if (source == null) return {};
38052 var target = {};
38053 var sourceKeys = Object.keys(source);
38054 var key, i;
38055
38056 for (i = 0; i < sourceKeys.length; i++) {
38057 key = sourceKeys[i];
38058 if (excluded.indexOf(key) >= 0) continue;
38059 target[key] = source[key];
38060 }
38061
38062 return target;
38063}
38064
38065module.exports = _objectWithoutPropertiesLoose;
38066
38067/***/ }),
38068/* 423 */
38069/***/ (function(module, exports) {
38070
38071function _assertThisInitialized(self) {
38072 if (self === void 0) {
38073 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
38074 }
38075
38076 return self;
38077}
38078
38079module.exports = _assertThisInitialized;
38080
38081/***/ }),
38082/* 424 */
38083/***/ (function(module, exports) {
38084
38085function _inheritsLoose(subClass, superClass) {
38086 subClass.prototype = Object.create(superClass.prototype);
38087 subClass.prototype.constructor = subClass;
38088 subClass.__proto__ = superClass;
38089}
38090
38091module.exports = _inheritsLoose;
38092
38093/***/ }),
38094/* 425 */
38095/***/ (function(module, exports, __webpack_require__) {
38096
38097var arrayShuffle = __webpack_require__(426),
38098 baseShuffle = __webpack_require__(429),
38099 isArray = __webpack_require__(208);
38100
38101/**
38102 * Creates an array of shuffled values, using a version of the
38103 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
38104 *
38105 * @static
38106 * @memberOf _
38107 * @since 0.1.0
38108 * @category Collection
38109 * @param {Array|Object} collection The collection to shuffle.
38110 * @returns {Array} Returns the new shuffled array.
38111 * @example
38112 *
38113 * _.shuffle([1, 2, 3, 4]);
38114 * // => [4, 1, 3, 2]
38115 */
38116function shuffle(collection) {
38117 var func = isArray(collection) ? arrayShuffle : baseShuffle;
38118 return func(collection);
38119}
38120
38121module.exports = shuffle;
38122
38123
38124/***/ }),
38125/* 426 */
38126/***/ (function(module, exports, __webpack_require__) {
38127
38128var copyArray = __webpack_require__(427),
38129 shuffleSelf = __webpack_require__(203);
38130
38131/**
38132 * A specialized version of `_.shuffle` for arrays.
38133 *
38134 * @private
38135 * @param {Array} array The array to shuffle.
38136 * @returns {Array} Returns the new shuffled array.
38137 */
38138function arrayShuffle(array) {
38139 return shuffleSelf(copyArray(array));
38140}
38141
38142module.exports = arrayShuffle;
38143
38144
38145/***/ }),
38146/* 427 */
38147/***/ (function(module, exports) {
38148
38149/**
38150 * Copies the values of `source` to `array`.
38151 *
38152 * @private
38153 * @param {Array} source The array to copy values from.
38154 * @param {Array} [array=[]] The array to copy values to.
38155 * @returns {Array} Returns `array`.
38156 */
38157function copyArray(source, array) {
38158 var index = -1,
38159 length = source.length;
38160
38161 array || (array = Array(length));
38162 while (++index < length) {
38163 array[index] = source[index];
38164 }
38165 return array;
38166}
38167
38168module.exports = copyArray;
38169
38170
38171/***/ }),
38172/* 428 */
38173/***/ (function(module, exports) {
38174
38175/* Built-in method references for those with the same name as other `lodash` methods. */
38176var nativeFloor = Math.floor,
38177 nativeRandom = Math.random;
38178
38179/**
38180 * The base implementation of `_.random` without support for returning
38181 * floating-point numbers.
38182 *
38183 * @private
38184 * @param {number} lower The lower bound.
38185 * @param {number} upper The upper bound.
38186 * @returns {number} Returns the random number.
38187 */
38188function baseRandom(lower, upper) {
38189 return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
38190}
38191
38192module.exports = baseRandom;
38193
38194
38195/***/ }),
38196/* 429 */
38197/***/ (function(module, exports, __webpack_require__) {
38198
38199var shuffleSelf = __webpack_require__(203),
38200 values = __webpack_require__(204);
38201
38202/**
38203 * The base implementation of `_.shuffle`.
38204 *
38205 * @private
38206 * @param {Array|Object} collection The collection to shuffle.
38207 * @returns {Array} Returns the new shuffled array.
38208 */
38209function baseShuffle(collection) {
38210 return shuffleSelf(values(collection));
38211}
38212
38213module.exports = baseShuffle;
38214
38215
38216/***/ }),
38217/* 430 */
38218/***/ (function(module, exports, __webpack_require__) {
38219
38220var arrayMap = __webpack_require__(431);
38221
38222/**
38223 * The base implementation of `_.values` and `_.valuesIn` which creates an
38224 * array of `object` property values corresponding to the property names
38225 * of `props`.
38226 *
38227 * @private
38228 * @param {Object} object The object to query.
38229 * @param {Array} props The property names to get values for.
38230 * @returns {Object} Returns the array of property values.
38231 */
38232function baseValues(object, props) {
38233 return arrayMap(props, function(key) {
38234 return object[key];
38235 });
38236}
38237
38238module.exports = baseValues;
38239
38240
38241/***/ }),
38242/* 431 */
38243/***/ (function(module, exports) {
38244
38245/**
38246 * A specialized version of `_.map` for arrays without support for iteratee
38247 * shorthands.
38248 *
38249 * @private
38250 * @param {Array} [array] The array to iterate over.
38251 * @param {Function} iteratee The function invoked per iteration.
38252 * @returns {Array} Returns the new mapped array.
38253 */
38254function arrayMap(array, iteratee) {
38255 var index = -1,
38256 length = array == null ? 0 : array.length,
38257 result = Array(length);
38258
38259 while (++index < length) {
38260 result[index] = iteratee(array[index], index, array);
38261 }
38262 return result;
38263}
38264
38265module.exports = arrayMap;
38266
38267
38268/***/ }),
38269/* 432 */
38270/***/ (function(module, exports, __webpack_require__) {
38271
38272var arrayLikeKeys = __webpack_require__(433),
38273 baseKeys = __webpack_require__(446),
38274 isArrayLike = __webpack_require__(449);
38275
38276/**
38277 * Creates an array of the own enumerable property names of `object`.
38278 *
38279 * **Note:** Non-object values are coerced to objects. See the
38280 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
38281 * for more details.
38282 *
38283 * @static
38284 * @since 0.1.0
38285 * @memberOf _
38286 * @category Object
38287 * @param {Object} object The object to query.
38288 * @returns {Array} Returns the array of property names.
38289 * @example
38290 *
38291 * function Foo() {
38292 * this.a = 1;
38293 * this.b = 2;
38294 * }
38295 *
38296 * Foo.prototype.c = 3;
38297 *
38298 * _.keys(new Foo);
38299 * // => ['a', 'b'] (iteration order is not guaranteed)
38300 *
38301 * _.keys('hi');
38302 * // => ['0', '1']
38303 */
38304function keys(object) {
38305 return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
38306}
38307
38308module.exports = keys;
38309
38310
38311/***/ }),
38312/* 433 */
38313/***/ (function(module, exports, __webpack_require__) {
38314
38315var baseTimes = __webpack_require__(434),
38316 isArguments = __webpack_require__(435),
38317 isArray = __webpack_require__(208),
38318 isBuffer = __webpack_require__(439),
38319 isIndex = __webpack_require__(441),
38320 isTypedArray = __webpack_require__(442);
38321
38322/** Used for built-in method references. */
38323var objectProto = Object.prototype;
38324
38325/** Used to check objects for own properties. */
38326var hasOwnProperty = objectProto.hasOwnProperty;
38327
38328/**
38329 * Creates an array of the enumerable property names of the array-like `value`.
38330 *
38331 * @private
38332 * @param {*} value The value to query.
38333 * @param {boolean} inherited Specify returning inherited property names.
38334 * @returns {Array} Returns the array of property names.
38335 */
38336function arrayLikeKeys(value, inherited) {
38337 var isArr = isArray(value),
38338 isArg = !isArr && isArguments(value),
38339 isBuff = !isArr && !isArg && isBuffer(value),
38340 isType = !isArr && !isArg && !isBuff && isTypedArray(value),
38341 skipIndexes = isArr || isArg || isBuff || isType,
38342 result = skipIndexes ? baseTimes(value.length, String) : [],
38343 length = result.length;
38344
38345 for (var key in value) {
38346 if ((inherited || hasOwnProperty.call(value, key)) &&
38347 !(skipIndexes && (
38348 // Safari 9 has enumerable `arguments.length` in strict mode.
38349 key == 'length' ||
38350 // Node.js 0.10 has enumerable non-index properties on buffers.
38351 (isBuff && (key == 'offset' || key == 'parent')) ||
38352 // PhantomJS 2 has enumerable non-index properties on typed arrays.
38353 (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
38354 // Skip index properties.
38355 isIndex(key, length)
38356 ))) {
38357 result.push(key);
38358 }
38359 }
38360 return result;
38361}
38362
38363module.exports = arrayLikeKeys;
38364
38365
38366/***/ }),
38367/* 434 */
38368/***/ (function(module, exports) {
38369
38370/**
38371 * The base implementation of `_.times` without support for iteratee shorthands
38372 * or max array length checks.
38373 *
38374 * @private
38375 * @param {number} n The number of times to invoke `iteratee`.
38376 * @param {Function} iteratee The function invoked per iteration.
38377 * @returns {Array} Returns the array of results.
38378 */
38379function baseTimes(n, iteratee) {
38380 var index = -1,
38381 result = Array(n);
38382
38383 while (++index < n) {
38384 result[index] = iteratee(index);
38385 }
38386 return result;
38387}
38388
38389module.exports = baseTimes;
38390
38391
38392/***/ }),
38393/* 435 */
38394/***/ (function(module, exports, __webpack_require__) {
38395
38396var baseIsArguments = __webpack_require__(436),
38397 isObjectLike = __webpack_require__(79);
38398
38399/** Used for built-in method references. */
38400var objectProto = Object.prototype;
38401
38402/** Used to check objects for own properties. */
38403var hasOwnProperty = objectProto.hasOwnProperty;
38404
38405/** Built-in value references. */
38406var propertyIsEnumerable = objectProto.propertyIsEnumerable;
38407
38408/**
38409 * Checks if `value` is likely an `arguments` object.
38410 *
38411 * @static
38412 * @memberOf _
38413 * @since 0.1.0
38414 * @category Lang
38415 * @param {*} value The value to check.
38416 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
38417 * else `false`.
38418 * @example
38419 *
38420 * _.isArguments(function() { return arguments; }());
38421 * // => true
38422 *
38423 * _.isArguments([1, 2, 3]);
38424 * // => false
38425 */
38426var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
38427 return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
38428 !propertyIsEnumerable.call(value, 'callee');
38429};
38430
38431module.exports = isArguments;
38432
38433
38434/***/ }),
38435/* 436 */
38436/***/ (function(module, exports, __webpack_require__) {
38437
38438var baseGetTag = __webpack_require__(78),
38439 isObjectLike = __webpack_require__(79);
38440
38441/** `Object#toString` result references. */
38442var argsTag = '[object Arguments]';
38443
38444/**
38445 * The base implementation of `_.isArguments`.
38446 *
38447 * @private
38448 * @param {*} value The value to check.
38449 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
38450 */
38451function baseIsArguments(value) {
38452 return isObjectLike(value) && baseGetTag(value) == argsTag;
38453}
38454
38455module.exports = baseIsArguments;
38456
38457
38458/***/ }),
38459/* 437 */
38460/***/ (function(module, exports, __webpack_require__) {
38461
38462var Symbol = __webpack_require__(205);
38463
38464/** Used for built-in method references. */
38465var objectProto = Object.prototype;
38466
38467/** Used to check objects for own properties. */
38468var hasOwnProperty = objectProto.hasOwnProperty;
38469
38470/**
38471 * Used to resolve the
38472 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
38473 * of values.
38474 */
38475var nativeObjectToString = objectProto.toString;
38476
38477/** Built-in value references. */
38478var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
38479
38480/**
38481 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
38482 *
38483 * @private
38484 * @param {*} value The value to query.
38485 * @returns {string} Returns the raw `toStringTag`.
38486 */
38487function getRawTag(value) {
38488 var isOwn = hasOwnProperty.call(value, symToStringTag),
38489 tag = value[symToStringTag];
38490
38491 try {
38492 value[symToStringTag] = undefined;
38493 var unmasked = true;
38494 } catch (e) {}
38495
38496 var result = nativeObjectToString.call(value);
38497 if (unmasked) {
38498 if (isOwn) {
38499 value[symToStringTag] = tag;
38500 } else {
38501 delete value[symToStringTag];
38502 }
38503 }
38504 return result;
38505}
38506
38507module.exports = getRawTag;
38508
38509
38510/***/ }),
38511/* 438 */
38512/***/ (function(module, exports) {
38513
38514/** Used for built-in method references. */
38515var objectProto = Object.prototype;
38516
38517/**
38518 * Used to resolve the
38519 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
38520 * of values.
38521 */
38522var nativeObjectToString = objectProto.toString;
38523
38524/**
38525 * Converts `value` to a string using `Object.prototype.toString`.
38526 *
38527 * @private
38528 * @param {*} value The value to convert.
38529 * @returns {string} Returns the converted string.
38530 */
38531function objectToString(value) {
38532 return nativeObjectToString.call(value);
38533}
38534
38535module.exports = objectToString;
38536
38537
38538/***/ }),
38539/* 439 */
38540/***/ (function(module, exports, __webpack_require__) {
38541
38542/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(206),
38543 stubFalse = __webpack_require__(440);
38544
38545/** Detect free variable `exports`. */
38546var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
38547
38548/** Detect free variable `module`. */
38549var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
38550
38551/** Detect the popular CommonJS extension `module.exports`. */
38552var moduleExports = freeModule && freeModule.exports === freeExports;
38553
38554/** Built-in value references. */
38555var Buffer = moduleExports ? root.Buffer : undefined;
38556
38557/* Built-in method references for those with the same name as other `lodash` methods. */
38558var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
38559
38560/**
38561 * Checks if `value` is a buffer.
38562 *
38563 * @static
38564 * @memberOf _
38565 * @since 4.3.0
38566 * @category Lang
38567 * @param {*} value The value to check.
38568 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
38569 * @example
38570 *
38571 * _.isBuffer(new Buffer(2));
38572 * // => true
38573 *
38574 * _.isBuffer(new Uint8Array(2));
38575 * // => false
38576 */
38577var isBuffer = nativeIsBuffer || stubFalse;
38578
38579module.exports = isBuffer;
38580
38581/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(209)(module)))
38582
38583/***/ }),
38584/* 440 */
38585/***/ (function(module, exports) {
38586
38587/**
38588 * This method returns `false`.
38589 *
38590 * @static
38591 * @memberOf _
38592 * @since 4.13.0
38593 * @category Util
38594 * @returns {boolean} Returns `false`.
38595 * @example
38596 *
38597 * _.times(2, _.stubFalse);
38598 * // => [false, false]
38599 */
38600function stubFalse() {
38601 return false;
38602}
38603
38604module.exports = stubFalse;
38605
38606
38607/***/ }),
38608/* 441 */
38609/***/ (function(module, exports) {
38610
38611/** Used as references for various `Number` constants. */
38612var MAX_SAFE_INTEGER = 9007199254740991;
38613
38614/** Used to detect unsigned integer values. */
38615var reIsUint = /^(?:0|[1-9]\d*)$/;
38616
38617/**
38618 * Checks if `value` is a valid array-like index.
38619 *
38620 * @private
38621 * @param {*} value The value to check.
38622 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
38623 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
38624 */
38625function isIndex(value, length) {
38626 var type = typeof value;
38627 length = length == null ? MAX_SAFE_INTEGER : length;
38628
38629 return !!length &&
38630 (type == 'number' ||
38631 (type != 'symbol' && reIsUint.test(value))) &&
38632 (value > -1 && value % 1 == 0 && value < length);
38633}
38634
38635module.exports = isIndex;
38636
38637
38638/***/ }),
38639/* 442 */
38640/***/ (function(module, exports, __webpack_require__) {
38641
38642var baseIsTypedArray = __webpack_require__(443),
38643 baseUnary = __webpack_require__(444),
38644 nodeUtil = __webpack_require__(445);
38645
38646/* Node.js helper references. */
38647var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
38648
38649/**
38650 * Checks if `value` is classified as a typed array.
38651 *
38652 * @static
38653 * @memberOf _
38654 * @since 3.0.0
38655 * @category Lang
38656 * @param {*} value The value to check.
38657 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
38658 * @example
38659 *
38660 * _.isTypedArray(new Uint8Array);
38661 * // => true
38662 *
38663 * _.isTypedArray([]);
38664 * // => false
38665 */
38666var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
38667
38668module.exports = isTypedArray;
38669
38670
38671/***/ }),
38672/* 443 */
38673/***/ (function(module, exports, __webpack_require__) {
38674
38675var baseGetTag = __webpack_require__(78),
38676 isLength = __webpack_require__(210),
38677 isObjectLike = __webpack_require__(79);
38678
38679/** `Object#toString` result references. */
38680var argsTag = '[object Arguments]',
38681 arrayTag = '[object Array]',
38682 boolTag = '[object Boolean]',
38683 dateTag = '[object Date]',
38684 errorTag = '[object Error]',
38685 funcTag = '[object Function]',
38686 mapTag = '[object Map]',
38687 numberTag = '[object Number]',
38688 objectTag = '[object Object]',
38689 regexpTag = '[object RegExp]',
38690 setTag = '[object Set]',
38691 stringTag = '[object String]',
38692 weakMapTag = '[object WeakMap]';
38693
38694var arrayBufferTag = '[object ArrayBuffer]',
38695 dataViewTag = '[object DataView]',
38696 float32Tag = '[object Float32Array]',
38697 float64Tag = '[object Float64Array]',
38698 int8Tag = '[object Int8Array]',
38699 int16Tag = '[object Int16Array]',
38700 int32Tag = '[object Int32Array]',
38701 uint8Tag = '[object Uint8Array]',
38702 uint8ClampedTag = '[object Uint8ClampedArray]',
38703 uint16Tag = '[object Uint16Array]',
38704 uint32Tag = '[object Uint32Array]';
38705
38706/** Used to identify `toStringTag` values of typed arrays. */
38707var typedArrayTags = {};
38708typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
38709typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
38710typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
38711typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
38712typedArrayTags[uint32Tag] = true;
38713typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
38714typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
38715typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
38716typedArrayTags[errorTag] = typedArrayTags[funcTag] =
38717typedArrayTags[mapTag] = typedArrayTags[numberTag] =
38718typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
38719typedArrayTags[setTag] = typedArrayTags[stringTag] =
38720typedArrayTags[weakMapTag] = false;
38721
38722/**
38723 * The base implementation of `_.isTypedArray` without Node.js optimizations.
38724 *
38725 * @private
38726 * @param {*} value The value to check.
38727 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
38728 */
38729function baseIsTypedArray(value) {
38730 return isObjectLike(value) &&
38731 isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
38732}
38733
38734module.exports = baseIsTypedArray;
38735
38736
38737/***/ }),
38738/* 444 */
38739/***/ (function(module, exports) {
38740
38741/**
38742 * The base implementation of `_.unary` without support for storing metadata.
38743 *
38744 * @private
38745 * @param {Function} func The function to cap arguments for.
38746 * @returns {Function} Returns the new capped function.
38747 */
38748function baseUnary(func) {
38749 return function(value) {
38750 return func(value);
38751 };
38752}
38753
38754module.exports = baseUnary;
38755
38756
38757/***/ }),
38758/* 445 */
38759/***/ (function(module, exports, __webpack_require__) {
38760
38761/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(207);
38762
38763/** Detect free variable `exports`. */
38764var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
38765
38766/** Detect free variable `module`. */
38767var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
38768
38769/** Detect the popular CommonJS extension `module.exports`. */
38770var moduleExports = freeModule && freeModule.exports === freeExports;
38771
38772/** Detect free variable `process` from Node.js. */
38773var freeProcess = moduleExports && freeGlobal.process;
38774
38775/** Used to access faster Node.js helpers. */
38776var nodeUtil = (function() {
38777 try {
38778 // Use `util.types` for Node.js 10+.
38779 var types = freeModule && freeModule.require && freeModule.require('util').types;
38780
38781 if (types) {
38782 return types;
38783 }
38784
38785 // Legacy `process.binding('util')` for Node.js < 10.
38786 return freeProcess && freeProcess.binding && freeProcess.binding('util');
38787 } catch (e) {}
38788}());
38789
38790module.exports = nodeUtil;
38791
38792/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(209)(module)))
38793
38794/***/ }),
38795/* 446 */
38796/***/ (function(module, exports, __webpack_require__) {
38797
38798var isPrototype = __webpack_require__(447),
38799 nativeKeys = __webpack_require__(448);
38800
38801/** Used for built-in method references. */
38802var objectProto = Object.prototype;
38803
38804/** Used to check objects for own properties. */
38805var hasOwnProperty = objectProto.hasOwnProperty;
38806
38807/**
38808 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
38809 *
38810 * @private
38811 * @param {Object} object The object to query.
38812 * @returns {Array} Returns the array of property names.
38813 */
38814function baseKeys(object) {
38815 if (!isPrototype(object)) {
38816 return nativeKeys(object);
38817 }
38818 var result = [];
38819 for (var key in Object(object)) {
38820 if (hasOwnProperty.call(object, key) && key != 'constructor') {
38821 result.push(key);
38822 }
38823 }
38824 return result;
38825}
38826
38827module.exports = baseKeys;
38828
38829
38830/***/ }),
38831/* 447 */
38832/***/ (function(module, exports) {
38833
38834/** Used for built-in method references. */
38835var objectProto = Object.prototype;
38836
38837/**
38838 * Checks if `value` is likely a prototype object.
38839 *
38840 * @private
38841 * @param {*} value The value to check.
38842 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
38843 */
38844function isPrototype(value) {
38845 var Ctor = value && value.constructor,
38846 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
38847
38848 return value === proto;
38849}
38850
38851module.exports = isPrototype;
38852
38853
38854/***/ }),
38855/* 448 */
38856/***/ (function(module, exports, __webpack_require__) {
38857
38858var overArg = __webpack_require__(211);
38859
38860/* Built-in method references for those with the same name as other `lodash` methods. */
38861var nativeKeys = overArg(Object.keys, Object);
38862
38863module.exports = nativeKeys;
38864
38865
38866/***/ }),
38867/* 449 */
38868/***/ (function(module, exports, __webpack_require__) {
38869
38870var isFunction = __webpack_require__(450),
38871 isLength = __webpack_require__(210);
38872
38873/**
38874 * Checks if `value` is array-like. A value is considered array-like if it's
38875 * not a function and has a `value.length` that's an integer greater than or
38876 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
38877 *
38878 * @static
38879 * @memberOf _
38880 * @since 4.0.0
38881 * @category Lang
38882 * @param {*} value The value to check.
38883 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
38884 * @example
38885 *
38886 * _.isArrayLike([1, 2, 3]);
38887 * // => true
38888 *
38889 * _.isArrayLike(document.body.children);
38890 * // => true
38891 *
38892 * _.isArrayLike('abc');
38893 * // => true
38894 *
38895 * _.isArrayLike(_.noop);
38896 * // => false
38897 */
38898function isArrayLike(value) {
38899 return value != null && isLength(value.length) && !isFunction(value);
38900}
38901
38902module.exports = isArrayLike;
38903
38904
38905/***/ }),
38906/* 450 */
38907/***/ (function(module, exports, __webpack_require__) {
38908
38909var baseGetTag = __webpack_require__(78),
38910 isObject = __webpack_require__(451);
38911
38912/** `Object#toString` result references. */
38913var asyncTag = '[object AsyncFunction]',
38914 funcTag = '[object Function]',
38915 genTag = '[object GeneratorFunction]',
38916 proxyTag = '[object Proxy]';
38917
38918/**
38919 * Checks if `value` is classified as a `Function` object.
38920 *
38921 * @static
38922 * @memberOf _
38923 * @since 0.1.0
38924 * @category Lang
38925 * @param {*} value The value to check.
38926 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
38927 * @example
38928 *
38929 * _.isFunction(_);
38930 * // => true
38931 *
38932 * _.isFunction(/abc/);
38933 * // => false
38934 */
38935function isFunction(value) {
38936 if (!isObject(value)) {
38937 return false;
38938 }
38939 // The use of `Object#toString` avoids issues with the `typeof` operator
38940 // in Safari 9 which returns 'object' for typed arrays and other constructors.
38941 var tag = baseGetTag(value);
38942 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
38943}
38944
38945module.exports = isFunction;
38946
38947
38948/***/ }),
38949/* 451 */
38950/***/ (function(module, exports) {
38951
38952/**
38953 * Checks if `value` is the
38954 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
38955 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
38956 *
38957 * @static
38958 * @memberOf _
38959 * @since 0.1.0
38960 * @category Lang
38961 * @param {*} value The value to check.
38962 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
38963 * @example
38964 *
38965 * _.isObject({});
38966 * // => true
38967 *
38968 * _.isObject([1, 2, 3]);
38969 * // => true
38970 *
38971 * _.isObject(_.noop);
38972 * // => true
38973 *
38974 * _.isObject(null);
38975 * // => false
38976 */
38977function isObject(value) {
38978 var type = typeof value;
38979 return value != null && (type == 'object' || type == 'function');
38980}
38981
38982module.exports = isObject;
38983
38984
38985/***/ }),
38986/* 452 */
38987/***/ (function(module, exports, __webpack_require__) {
38988
38989var arrayWithHoles = __webpack_require__(453);
38990
38991var iterableToArray = __webpack_require__(201);
38992
38993var unsupportedIterableToArray = __webpack_require__(202);
38994
38995var nonIterableRest = __webpack_require__(454);
38996
38997function _toArray(arr) {
38998 return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest();
38999}
39000
39001module.exports = _toArray;
39002
39003/***/ }),
39004/* 453 */
39005/***/ (function(module, exports) {
39006
39007function _arrayWithHoles(arr) {
39008 if (Array.isArray(arr)) return arr;
39009}
39010
39011module.exports = _arrayWithHoles;
39012
39013/***/ }),
39014/* 454 */
39015/***/ (function(module, exports) {
39016
39017function _nonIterableRest() {
39018 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
39019}
39020
39021module.exports = _nonIterableRest;
39022
39023/***/ }),
39024/* 455 */
39025/***/ (function(module, exports) {
39026
39027function _defineProperties(target, props) {
39028 for (var i = 0; i < props.length; i++) {
39029 var descriptor = props[i];
39030 descriptor.enumerable = descriptor.enumerable || false;
39031 descriptor.configurable = true;
39032 if ("value" in descriptor) descriptor.writable = true;
39033 Object.defineProperty(target, descriptor.key, descriptor);
39034 }
39035}
39036
39037function _createClass(Constructor, protoProps, staticProps) {
39038 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
39039 if (staticProps) _defineProperties(Constructor, staticProps);
39040 return Constructor;
39041}
39042
39043module.exports = _createClass;
39044
39045/***/ }),
39046/* 456 */
39047/***/ (function(module, exports) {
39048
39049function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
39050 var desc = {};
39051 Object.keys(descriptor).forEach(function (key) {
39052 desc[key] = descriptor[key];
39053 });
39054 desc.enumerable = !!desc.enumerable;
39055 desc.configurable = !!desc.configurable;
39056
39057 if ('value' in desc || desc.initializer) {
39058 desc.writable = true;
39059 }
39060
39061 desc = decorators.slice().reverse().reduce(function (desc, decorator) {
39062 return decorator(target, property, desc) || desc;
39063 }, desc);
39064
39065 if (context && desc.initializer !== void 0) {
39066 desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
39067 desc.initializer = undefined;
39068 }
39069
39070 if (desc.initializer === void 0) {
39071 Object.defineProperty(target, property, desc);
39072 desc = null;
39073 }
39074
39075 return desc;
39076}
39077
39078module.exports = _applyDecoratedDescriptor;
39079
39080/***/ }),
39081/* 457 */
39082/***/ (function(module, exports, __webpack_require__) {
39083
39084/*
39085
39086 Javascript State Machine Library - https://github.com/jakesgordon/javascript-state-machine
39087
39088 Copyright (c) 2012, 2013, 2014, 2015, Jake Gordon and contributors
39089 Released under the MIT license - https://github.com/jakesgordon/javascript-state-machine/blob/master/LICENSE
39090
39091*/
39092
39093(function () {
39094
39095 var StateMachine = {
39096
39097 //---------------------------------------------------------------------------
39098
39099 VERSION: "2.4.0",
39100
39101 //---------------------------------------------------------------------------
39102
39103 Result: {
39104 SUCCEEDED: 1, // the event transitioned successfully from one state to another
39105 NOTRANSITION: 2, // the event was successfull but no state transition was necessary
39106 CANCELLED: 3, // the event was cancelled by the caller in a beforeEvent callback
39107 PENDING: 4 // the event is asynchronous and the caller is in control of when the transition occurs
39108 },
39109
39110 Error: {
39111 INVALID_TRANSITION: 100, // caller tried to fire an event that was innapropriate in the current state
39112 PENDING_TRANSITION: 200, // caller tried to fire an event while an async transition was still pending
39113 INVALID_CALLBACK: 300 // caller provided callback function threw an exception
39114 },
39115
39116 WILDCARD: '*',
39117 ASYNC: 'async',
39118
39119 //---------------------------------------------------------------------------
39120
39121 create: function(cfg, target) {
39122
39123 var initial = (typeof cfg.initial == 'string') ? { state: cfg.initial } : cfg.initial; // allow for a simple string, or an object with { state: 'foo', event: 'setup', defer: true|false }
39124 var terminal = cfg.terminal || cfg['final'];
39125 var fsm = target || cfg.target || {};
39126 var events = cfg.events || [];
39127 var callbacks = cfg.callbacks || {};
39128 var map = {}; // track state transitions allowed for an event { event: { from: [ to ] } }
39129 var transitions = {}; // track events allowed from a state { state: [ event ] }
39130
39131 var add = function(e) {
39132 var from = Array.isArray(e.from) ? e.from : (e.from ? [e.from] : [StateMachine.WILDCARD]); // allow 'wildcard' transition if 'from' is not specified
39133 map[e.name] = map[e.name] || {};
39134 for (var n = 0 ; n < from.length ; n++) {
39135 transitions[from[n]] = transitions[from[n]] || [];
39136 transitions[from[n]].push(e.name);
39137
39138 map[e.name][from[n]] = e.to || from[n]; // allow no-op transition if 'to' is not specified
39139 }
39140 if (e.to)
39141 transitions[e.to] = transitions[e.to] || [];
39142 };
39143
39144 if (initial) {
39145 initial.event = initial.event || 'startup';
39146 add({ name: initial.event, from: 'none', to: initial.state });
39147 }
39148
39149 for(var n = 0 ; n < events.length ; n++)
39150 add(events[n]);
39151
39152 for(var name in map) {
39153 if (map.hasOwnProperty(name))
39154 fsm[name] = StateMachine.buildEvent(name, map[name]);
39155 }
39156
39157 for(var name in callbacks) {
39158 if (callbacks.hasOwnProperty(name))
39159 fsm[name] = callbacks[name]
39160 }
39161
39162 fsm.current = 'none';
39163 fsm.is = function(state) { return Array.isArray(state) ? (state.indexOf(this.current) >= 0) : (this.current === state); };
39164 fsm.can = function(event) { return !this.transition && (map[event] !== undefined) && (map[event].hasOwnProperty(this.current) || map[event].hasOwnProperty(StateMachine.WILDCARD)); }
39165 fsm.cannot = function(event) { return !this.can(event); };
39166 fsm.transitions = function() { return (transitions[this.current] || []).concat(transitions[StateMachine.WILDCARD] || []); };
39167 fsm.isFinished = function() { return this.is(terminal); };
39168 fsm.error = cfg.error || function(name, from, to, args, error, msg, e) { throw e || msg; }; // default behavior when something unexpected happens is to throw an exception, but caller can override this behavior if desired (see github issue #3 and #17)
39169 fsm.states = function() { return Object.keys(transitions).sort() };
39170
39171 if (initial && !initial.defer)
39172 fsm[initial.event]();
39173
39174 return fsm;
39175
39176 },
39177
39178 //===========================================================================
39179
39180 doCallback: function(fsm, func, name, from, to, args) {
39181 if (func) {
39182 try {
39183 return func.apply(fsm, [name, from, to].concat(args));
39184 }
39185 catch(e) {
39186 return fsm.error(name, from, to, args, StateMachine.Error.INVALID_CALLBACK, "an exception occurred in a caller-provided callback function", e);
39187 }
39188 }
39189 },
39190
39191 beforeAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbeforeevent'], name, from, to, args); },
39192 afterAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafterevent'] || fsm['onevent'], name, from, to, args); },
39193 leaveAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleavestate'], name, from, to, args); },
39194 enterAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenterstate'] || fsm['onstate'], name, from, to, args); },
39195 changeState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onchangestate'], name, from, to, args); },
39196
39197 beforeThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbefore' + name], name, from, to, args); },
39198 afterThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafter' + name] || fsm['on' + name], name, from, to, args); },
39199 leaveThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleave' + from], name, from, to, args); },
39200 enterThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenter' + to] || fsm['on' + to], name, from, to, args); },
39201
39202 beforeEvent: function(fsm, name, from, to, args) {
39203 if ((false === StateMachine.beforeThisEvent(fsm, name, from, to, args)) ||
39204 (false === StateMachine.beforeAnyEvent( fsm, name, from, to, args)))
39205 return false;
39206 },
39207
39208 afterEvent: function(fsm, name, from, to, args) {
39209 StateMachine.afterThisEvent(fsm, name, from, to, args);
39210 StateMachine.afterAnyEvent( fsm, name, from, to, args);
39211 },
39212
39213 leaveState: function(fsm, name, from, to, args) {
39214 var specific = StateMachine.leaveThisState(fsm, name, from, to, args),
39215 general = StateMachine.leaveAnyState( fsm, name, from, to, args);
39216 if ((false === specific) || (false === general))
39217 return false;
39218 else if ((StateMachine.ASYNC === specific) || (StateMachine.ASYNC === general))
39219 return StateMachine.ASYNC;
39220 },
39221
39222 enterState: function(fsm, name, from, to, args) {
39223 StateMachine.enterThisState(fsm, name, from, to, args);
39224 StateMachine.enterAnyState( fsm, name, from, to, args);
39225 },
39226
39227 //===========================================================================
39228
39229 buildEvent: function(name, map) {
39230 return function() {
39231
39232 var from = this.current;
39233 var to = map[from] || (map[StateMachine.WILDCARD] != StateMachine.WILDCARD ? map[StateMachine.WILDCARD] : from) || from;
39234 var args = Array.prototype.slice.call(arguments); // turn arguments into pure array
39235
39236 if (this.transition)
39237 return this.error(name, from, to, args, StateMachine.Error.PENDING_TRANSITION, "event " + name + " inappropriate because previous transition did not complete");
39238
39239 if (this.cannot(name))
39240 return this.error(name, from, to, args, StateMachine.Error.INVALID_TRANSITION, "event " + name + " inappropriate in current state " + this.current);
39241
39242 if (false === StateMachine.beforeEvent(this, name, from, to, args))
39243 return StateMachine.Result.CANCELLED;
39244
39245 if (from === to) {
39246 StateMachine.afterEvent(this, name, from, to, args);
39247 return StateMachine.Result.NOTRANSITION;
39248 }
39249
39250 // prepare a transition method for use EITHER lower down, or by caller if they want an async transition (indicated by an ASYNC return value from leaveState)
39251 var fsm = this;
39252 this.transition = function() {
39253 fsm.transition = null; // this method should only ever be called once
39254 fsm.current = to;
39255 StateMachine.enterState( fsm, name, from, to, args);
39256 StateMachine.changeState(fsm, name, from, to, args);
39257 StateMachine.afterEvent( fsm, name, from, to, args);
39258 return StateMachine.Result.SUCCEEDED;
39259 };
39260 this.transition.cancel = function() { // provide a way for caller to cancel async transition if desired (issue #22)
39261 fsm.transition = null;
39262 StateMachine.afterEvent(fsm, name, from, to, args);
39263 }
39264
39265 var leave = StateMachine.leaveState(this, name, from, to, args);
39266 if (false === leave) {
39267 this.transition = null;
39268 return StateMachine.Result.CANCELLED;
39269 }
39270 else if (StateMachine.ASYNC === leave) {
39271 return StateMachine.Result.PENDING;
39272 }
39273 else {
39274 if (this.transition) // need to check in case user manually called transition() but forgot to return StateMachine.ASYNC
39275 return this.transition();
39276 }
39277
39278 };
39279 }
39280
39281 }; // StateMachine
39282
39283 //===========================================================================
39284
39285 //======
39286 // NODE
39287 //======
39288 if (true) {
39289 if (typeof module !== 'undefined' && module.exports) {
39290 exports = module.exports = StateMachine;
39291 }
39292 exports.StateMachine = StateMachine;
39293 }
39294 //============
39295 // AMD/REQUIRE
39296 //============
39297 else if (typeof define === 'function' && define.amd) {
39298 define(function(require) { return StateMachine; });
39299 }
39300 //========
39301 // BROWSER
39302 //========
39303 else if (typeof window !== 'undefined') {
39304 window.StateMachine = StateMachine;
39305 }
39306 //===========
39307 // WEB WORKER
39308 //===========
39309 else if (typeof self !== 'undefined') {
39310 self.StateMachine = StateMachine;
39311 }
39312
39313}());
39314
39315
39316/***/ }),
39317/* 458 */
39318/***/ (function(module, exports) {
39319
39320function _typeof(obj) {
39321 "@babel/helpers - typeof";
39322
39323 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
39324 module.exports = _typeof = function _typeof(obj) {
39325 return typeof obj;
39326 };
39327 } else {
39328 module.exports = _typeof = function _typeof(obj) {
39329 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
39330 };
39331 }
39332
39333 return _typeof(obj);
39334}
39335
39336module.exports = _typeof;
39337
39338/***/ }),
39339/* 459 */
39340/***/ (function(module, exports, __webpack_require__) {
39341
39342var baseGetTag = __webpack_require__(78),
39343 getPrototype = __webpack_require__(460),
39344 isObjectLike = __webpack_require__(79);
39345
39346/** `Object#toString` result references. */
39347var objectTag = '[object Object]';
39348
39349/** Used for built-in method references. */
39350var funcProto = Function.prototype,
39351 objectProto = Object.prototype;
39352
39353/** Used to resolve the decompiled source of functions. */
39354var funcToString = funcProto.toString;
39355
39356/** Used to check objects for own properties. */
39357var hasOwnProperty = objectProto.hasOwnProperty;
39358
39359/** Used to infer the `Object` constructor. */
39360var objectCtorString = funcToString.call(Object);
39361
39362/**
39363 * Checks if `value` is a plain object, that is, an object created by the
39364 * `Object` constructor or one with a `[[Prototype]]` of `null`.
39365 *
39366 * @static
39367 * @memberOf _
39368 * @since 0.8.0
39369 * @category Lang
39370 * @param {*} value The value to check.
39371 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
39372 * @example
39373 *
39374 * function Foo() {
39375 * this.a = 1;
39376 * }
39377 *
39378 * _.isPlainObject(new Foo);
39379 * // => false
39380 *
39381 * _.isPlainObject([1, 2, 3]);
39382 * // => false
39383 *
39384 * _.isPlainObject({ 'x': 0, 'y': 0 });
39385 * // => true
39386 *
39387 * _.isPlainObject(Object.create(null));
39388 * // => true
39389 */
39390function isPlainObject(value) {
39391 if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
39392 return false;
39393 }
39394 var proto = getPrototype(value);
39395 if (proto === null) {
39396 return true;
39397 }
39398 var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
39399 return typeof Ctor == 'function' && Ctor instanceof Ctor &&
39400 funcToString.call(Ctor) == objectCtorString;
39401}
39402
39403module.exports = isPlainObject;
39404
39405
39406/***/ }),
39407/* 460 */
39408/***/ (function(module, exports, __webpack_require__) {
39409
39410var overArg = __webpack_require__(211);
39411
39412/** Built-in value references. */
39413var getPrototype = overArg(Object.getPrototypeOf, Object);
39414
39415module.exports = getPrototype;
39416
39417
39418/***/ }),
39419/* 461 */
39420/***/ (function(module, exports, __webpack_require__) {
39421
39422"use strict";
39423var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;
39424
39425var _assign = __webpack_require__(199);
39426
39427var _assign2 = _interopRequireDefault(_assign);
39428
39429var _set = __webpack_require__(193);
39430
39431var _set2 = _interopRequireDefault(_set);
39432
39433var _from = __webpack_require__(191);
39434
39435var _from2 = _interopRequireDefault(_from);
39436
39437var _isIterable2 = __webpack_require__(112);
39438
39439var _isIterable3 = _interopRequireDefault(_isIterable2);
39440
39441var _create = __webpack_require__(111);
39442
39443var _create2 = _interopRequireDefault(_create);
39444
39445var _typeof2 = __webpack_require__(23);
39446
39447var _typeof3 = _interopRequireDefault(_typeof2);
39448
39449function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
39450
39451(function (global, factory) {
39452 ( false ? 'undefined' : (0, _typeof3.default)(exports)) === 'object' && typeof module !== 'undefined' ? factory(exports, __webpack_require__(113)) : true ? !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, __webpack_require__(113)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
39453 __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
39454 (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
39455 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : (global = global || self, factory(global.AV = global.AV || {}, global.AV));
39456})(undefined, function (exports, core) {
39457 'use strict';
39458
39459 function _inheritsLoose(subClass, superClass) {
39460 subClass.prototype = (0, _create2.default)(superClass.prototype);
39461 subClass.prototype.constructor = subClass;
39462 subClass.__proto__ = superClass;
39463 }
39464
39465 function _toConsumableArray(arr) {
39466 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
39467 }
39468
39469 function _arrayWithoutHoles(arr) {
39470 if (Array.isArray(arr)) {
39471 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
39472 arr2[i] = arr[i];
39473 }return arr2;
39474 }
39475 }
39476
39477 function _iterableToArray(iter) {
39478 if ((0, _isIterable3.default)(Object(iter)) || Object.prototype.toString.call(iter) === "[object Arguments]") return (0, _from2.default)(iter);
39479 }
39480
39481 function _nonIterableSpread() {
39482 throw new TypeError("Invalid attempt to spread non-iterable instance");
39483 }
39484
39485 /* eslint-disable import/no-unresolved */
39486
39487 if (!core.Protocals) {
39488 throw new Error('LeanCloud Realtime SDK not installed');
39489 }
39490
39491 var CommandType = core.Protocals.CommandType,
39492 GenericCommand = core.Protocals.GenericCommand,
39493 AckCommand = core.Protocals.AckCommand;
39494
39495 var warn = function warn(error) {
39496 return console.warn(error.message);
39497 };
39498
39499 var LiveQueryClient =
39500 /*#__PURE__*/
39501 function (_EventEmitter) {
39502 _inheritsLoose(LiveQueryClient, _EventEmitter);
39503
39504 function LiveQueryClient(appId, subscriptionId, connection) {
39505 var _this;
39506
39507 _this = _EventEmitter.call(this) || this;
39508 _this._appId = appId;
39509 _this.id = subscriptionId;
39510 _this._connection = connection;
39511 _this._eventemitter = new core.EventEmitter();
39512 _this._querys = new _set2.default();
39513 return _this;
39514 }
39515
39516 var _proto = LiveQueryClient.prototype;
39517
39518 _proto._send = function _send(cmd) {
39519 var _this$_connection;
39520
39521 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
39522 args[_key - 1] = arguments[_key];
39523 }
39524
39525 return (_this$_connection = this._connection).send.apply(_this$_connection, [(0, _assign2.default)(cmd, {
39526 appId: this._appId,
39527 installationId: this.id,
39528 service: 1
39529 })].concat(args));
39530 };
39531
39532 _proto._open = function _open() {
39533 return this._send(new GenericCommand({
39534 cmd: CommandType.login
39535 }));
39536 };
39537
39538 _proto.close = function close() {
39539 var _ee = this._eventemitter;
39540
39541 _ee.emit('beforeclose');
39542
39543 return this._send(new GenericCommand({
39544 cmd: CommandType.logout
39545 })).then(function () {
39546 return _ee.emit('close');
39547 });
39548 };
39549
39550 _proto.register = function register(liveQuery) {
39551 this._querys.add(liveQuery);
39552 };
39553
39554 _proto.deregister = function deregister(liveQuery) {
39555 var _this2 = this;
39556
39557 this._querys.delete(liveQuery);
39558
39559 setTimeout(function () {
39560 if (!_this2._querys.size) _this2.close().catch(warn);
39561 }, 0);
39562 };
39563
39564 _proto._dispatchCommand = function _dispatchCommand(command) {
39565 if (command.cmd !== CommandType.data) {
39566 this.emit('unhandledmessage', command);
39567 return core.Promise.resolve();
39568 }
39569
39570 return this._dispatchDataCommand(command);
39571 };
39572
39573 _proto._dispatchDataCommand = function _dispatchDataCommand(_ref) {
39574 var _ref$dataMessage = _ref.dataMessage,
39575 ids = _ref$dataMessage.ids,
39576 msg = _ref$dataMessage.msg;
39577 this.emit('message', msg.map(function (_ref2) {
39578 var data = _ref2.data;
39579 return JSON.parse(data);
39580 })); // send ack
39581
39582 var command = new GenericCommand({
39583 cmd: CommandType.ack,
39584 ackMessage: new AckCommand({
39585 ids: ids
39586 })
39587 });
39588 return this._send(command, false).catch(warn);
39589 };
39590
39591 return LiveQueryClient;
39592 }(core.EventEmitter);
39593
39594 var finalize = function finalize(callback) {
39595 return [// eslint-disable-next-line no-sequences
39596 function (value) {
39597 return callback(), value;
39598 }, function (error) {
39599 callback();
39600 throw error;
39601 }];
39602 };
39603
39604 var onRealtimeCreate = function onRealtimeCreate(realtime) {
39605 /* eslint-disable no-param-reassign */
39606 realtime._liveQueryClients = {};
39607
39608 realtime.createLiveQueryClient = function (subscriptionId) {
39609 var _realtime$_open$then;
39610
39611 if (realtime._liveQueryClients[subscriptionId] !== undefined) {
39612 return core.Promise.resolve(realtime._liveQueryClients[subscriptionId]);
39613 }
39614
39615 var promise = (_realtime$_open$then = realtime._open().then(function (connection) {
39616 var client = new LiveQueryClient(realtime._options.appId, subscriptionId, connection);
39617 connection.on('reconnect', function () {
39618 return client._open().then(function () {
39619 return client.emit('reconnect');
39620 }, function (error) {
39621 return client.emit('reconnecterror', error);
39622 });
39623 });
39624
39625 client._eventemitter.on('beforeclose', function () {
39626 delete realtime._liveQueryClients[client.id];
39627 }, realtime);
39628
39629 client._eventemitter.on('close', function () {
39630 realtime._deregister(client);
39631 }, realtime);
39632
39633 return client._open().then(function () {
39634 realtime._liveQueryClients[client.id] = client;
39635
39636 realtime._register(client);
39637
39638 return client;
39639 });
39640 })).then.apply(_realtime$_open$then, _toConsumableArray(finalize(function () {
39641 if (realtime._deregisterPending) realtime._deregisterPending(promise);
39642 })));
39643
39644 realtime._liveQueryClients[subscriptionId] = promise;
39645 if (realtime._registerPending) realtime._registerPending(promise);
39646 return promise;
39647 };
39648 /* eslint-enable no-param-reassign */
39649 };
39650
39651 var beforeCommandDispatch = function beforeCommandDispatch(command, realtime) {
39652 var isLiveQueryCommand = command.installationId && command.service === 1;
39653 if (!isLiveQueryCommand) return true;
39654 var targetClient = realtime._liveQueryClients[command.installationId];
39655
39656 if (targetClient) {
39657 targetClient._dispatchCommand(command).catch(function (error) {
39658 return console.warn(error);
39659 });
39660 } else {
39661 console.warn('Unexpected message received without any live client match: %O', command);
39662 }
39663
39664 return false;
39665 }; // eslint-disable-next-line import/prefer-default-export
39666
39667
39668 var LiveQueryPlugin = {
39669 name: 'leancloud-realtime-plugin-live-query',
39670 onRealtimeCreate: onRealtimeCreate,
39671 beforeCommandDispatch: beforeCommandDispatch
39672 };
39673
39674 exports.LiveQueryPlugin = LiveQueryPlugin;
39675
39676 Object.defineProperty(exports, '__esModule', { value: true });
39677});
39678//# sourceMappingURL=live-query.js.map
39679
39680/***/ })
39681/******/ ]);
39682});
39683//# sourceMappingURL=av-live-query.js.map
\No newline at end of file