UNPKG

d2

Version:

Javascript library for DHIS2

15,880 lines 578 kB
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define([], factory);
	else if(typeof exports === 'object')
		exports["d2"] = factory();
	else
		root["d2"] = factory();
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = "./src/d2.js");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./node_modules/isomorphic-fetch/fetch-npm-browserify.js":
/*!***************************************************************!*\
  !*** ./node_modules/isomorphic-fetch/fetch-npm-browserify.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// the whatwg-fetch polyfill installs the fetch() function
// on the global object (window or self)
//
// Return that as the export for use in Webpack, Browserify etc.
__webpack_require__(/*! whatwg-fetch */ "./node_modules/whatwg-fetch/fetch.js");
module.exports = self.fetch.bind(self);


/***/ }),

/***/ "./node_modules/lodash/_DataView.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_DataView.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(/*! ./_getNative */ "./node_modules/lodash/_getNative.js"),
    root = __webpack_require__(/*! ./_root */ "./node_modules/lodash/_root.js");

/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');

module.exports = DataView;


/***/ }),

/***/ "./node_modules/lodash/_Hash.js":
/*!**************************************!*\
  !*** ./node_modules/lodash/_Hash.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var hashClear = __webpack_require__(/*! ./_hashClear */ "./node_modules/lodash/_hashClear.js"),
    hashDelete = __webpack_require__(/*! ./_hashDelete */ "./node_modules/lodash/_hashDelete.js"),
    hashGet = __webpack_require__(/*! ./_hashGet */ "./node_modules/lodash/_hashGet.js"),
    hashHas = __webpack_require__(/*! ./_hashHas */ "./node_modules/lodash/_hashHas.js"),
    hashSet = __webpack_require__(/*! ./_hashSet */ "./node_modules/lodash/_hashSet.js");

/**
 * Creates a hash object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Hash(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;

module.exports = Hash;


/***/ }),

/***/ "./node_modules/lodash/_ListCache.js":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_ListCache.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var listCacheClear = __webpack_require__(/*! ./_listCacheClear */ "./node_modules/lodash/_listCacheClear.js"),
    listCacheDelete = __webpack_require__(/*! ./_listCacheDelete */ "./node_modules/lodash/_listCacheDelete.js"),
    listCacheGet = __webpack_require__(/*! ./_listCacheGet */ "./node_modules/lodash/_listCacheGet.js"),
    listCacheHas = __webpack_require__(/*! ./_listCacheHas */ "./node_modules/lodash/_listCacheHas.js"),
    listCacheSet = __webpack_require__(/*! ./_listCacheSet */ "./node_modules/lodash/_listCacheSet.js");

/**
 * Creates an list cache object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function ListCache(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;

module.exports = ListCache;


/***/ }),

/***/ "./node_modules/lodash/_Map.js":
/*!*************************************!*\
  !*** ./node_modules/lodash/_Map.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(/*! ./_getNative */ "./node_modules/lodash/_getNative.js"),
    root = __webpack_require__(/*! ./_root */ "./node_modules/lodash/_root.js");

/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');

module.exports = Map;


/***/ }),

/***/ "./node_modules/lodash/_MapCache.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_MapCache.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var mapCacheClear = __webpack_require__(/*! ./_mapCacheClear */ "./node_modules/lodash/_mapCacheClear.js"),
    mapCacheDelete = __webpack_require__(/*! ./_mapCacheDelete */ "./node_modules/lodash/_mapCacheDelete.js"),
    mapCacheGet = __webpack_require__(/*! ./_mapCacheGet */ "./node_modules/lodash/_mapCacheGet.js"),
    mapCacheHas = __webpack_require__(/*! ./_mapCacheHas */ "./node_modules/lodash/_mapCacheHas.js"),
    mapCacheSet = __webpack_require__(/*! ./_mapCacheSet */ "./node_modules/lodash/_mapCacheSet.js");

/**
 * Creates a map cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function MapCache(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;

module.exports = MapCache;


/***/ }),

/***/ "./node_modules/lodash/_Promise.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_Promise.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(/*! ./_getNative */ "./node_modules/lodash/_getNative.js"),
    root = __webpack_require__(/*! ./_root */ "./node_modules/lodash/_root.js");

/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');

module.exports = Promise;


/***/ }),

/***/ "./node_modules/lodash/_Set.js":
/*!*************************************!*\
  !*** ./node_modules/lodash/_Set.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(/*! ./_getNative */ "./node_modules/lodash/_getNative.js"),
    root = __webpack_require__(/*! ./_root */ "./node_modules/lodash/_root.js");

/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');

module.exports = Set;


/***/ }),

/***/ "./node_modules/lodash/_SetCache.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_SetCache.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var MapCache = __webpack_require__(/*! ./_MapCache */ "./node_modules/lodash/_MapCache.js"),
    setCacheAdd = __webpack_require__(/*! ./_setCacheAdd */ "./node_modules/lodash/_setCacheAdd.js"),
    setCacheHas = __webpack_require__(/*! ./_setCacheHas */ "./node_modules/lodash/_setCacheHas.js");

/**
 *
 * Creates an array cache object to store unique values.
 *
 * @private
 * @constructor
 * @param {Array} [values] The values to cache.
 */
function SetCache(values) {
  var index = -1,
      length = values == null ? 0 : values.length;

  this.__data__ = new MapCache;
  while (++index < length) {
    this.add(values[index]);
  }
}

// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;

module.exports = SetCache;


/***/ }),

/***/ "./node_modules/lodash/_Stack.js":
/*!***************************************!*\
  !*** ./node_modules/lodash/_Stack.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var ListCache = __webpack_require__(/*! ./_ListCache */ "./node_modules/lodash/_ListCache.js"),
    stackClear = __webpack_require__(/*! ./_stackClear */ "./node_modules/lodash/_stackClear.js"),
    stackDelete = __webpack_require__(/*! ./_stackDelete */ "./node_modules/lodash/_stackDelete.js"),
    stackGet = __webpack_require__(/*! ./_stackGet */ "./node_modules/lodash/_stackGet.js"),
    stackHas = __webpack_require__(/*! ./_stackHas */ "./node_modules/lodash/_stackHas.js"),
    stackSet = __webpack_require__(/*! ./_stackSet */ "./node_modules/lodash/_stackSet.js");

/**
 * Creates a stack cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Stack(entries) {
  var data = this.__data__ = new ListCache(entries);
  this.size = data.size;
}

// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;

module.exports = Stack;


/***/ }),

/***/ "./node_modules/lodash/_Symbol.js":
/*!****************************************!*\
  !*** ./node_modules/lodash/_Symbol.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var root = __webpack_require__(/*! ./_root */ "./node_modules/lodash/_root.js");

/** Built-in value references. */
var Symbol = root.Symbol;

module.exports = Symbol;


/***/ }),

/***/ "./node_modules/lodash/_Uint8Array.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_Uint8Array.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var root = __webpack_require__(/*! ./_root */ "./node_modules/lodash/_root.js");

/** Built-in value references. */
var Uint8Array = root.Uint8Array;

module.exports = Uint8Array;


/***/ }),

/***/ "./node_modules/lodash/_WeakMap.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_WeakMap.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(/*! ./_getNative */ "./node_modules/lodash/_getNative.js"),
    root = __webpack_require__(/*! ./_root */ "./node_modules/lodash/_root.js");

/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');

module.exports = WeakMap;


/***/ }),

/***/ "./node_modules/lodash/_apply.js":
/*!***************************************!*\
  !*** ./node_modules/lodash/_apply.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * A faster alternative to `Function#apply`, this function invokes `func`
 * with the `this` binding of `thisArg` and the arguments of `args`.
 *
 * @private
 * @param {Function} func The function to invoke.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {Array} args The arguments to invoke `func` with.
 * @returns {*} Returns the result of `func`.
 */
function apply(func, thisArg, args) {
  switch (args.length) {
    case 0: return func.call(thisArg);
    case 1: return func.call(thisArg, args[0]);
    case 2: return func.call(thisArg, args[0], args[1]);
    case 3: return func.call(thisArg, args[0], args[1], args[2]);
  }
  return func.apply(thisArg, args);
}

module.exports = apply;


/***/ }),

/***/ "./node_modules/lodash/_arrayFilter.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_arrayFilter.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * A specialized version of `_.filter` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */
function arrayFilter(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length,
      resIndex = 0,
      result = [];

  while (++index < length) {
    var value = array[index];
    if (predicate(value, index, array)) {
      result[resIndex++] = value;
    }
  }
  return result;
}

module.exports = arrayFilter;


/***/ }),

/***/ "./node_modules/lodash/_arrayLikeKeys.js":
/*!***********************************************!*\
  !*** ./node_modules/lodash/_arrayLikeKeys.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseTimes = __webpack_require__(/*! ./_baseTimes */ "./node_modules/lodash/_baseTimes.js"),
    isArguments = __webpack_require__(/*! ./isArguments */ "./node_modules/lodash/isArguments.js"),
    isArray = __webpack_require__(/*! ./isArray */ "./node_modules/lodash/isArray.js"),
    isBuffer = __webpack_require__(/*! ./isBuffer */ "./node_modules/lodash/isBuffer.js"),
    isIndex = __webpack_require__(/*! ./_isIndex */ "./node_modules/lodash/_isIndex.js"),
    isTypedArray = __webpack_require__(/*! ./isTypedArray */ "./node_modules/lodash/isTypedArray.js");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Creates an array of the enumerable property names of the array-like `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @param {boolean} inherited Specify returning inherited property names.
 * @returns {Array} Returns the array of property names.
 */
function arrayLikeKeys(value, inherited) {
  var isArr = isArray(value),
      isArg = !isArr && isArguments(value),
      isBuff = !isArr && !isArg && isBuffer(value),
      isType = !isArr && !isArg && !isBuff && isTypedArray(value),
      skipIndexes = isArr || isArg || isBuff || isType,
      result = skipIndexes ? baseTimes(value.length, String) : [],
      length = result.length;

  for (var key in value) {
    if ((inherited || hasOwnProperty.call(value, key)) &&
        !(skipIndexes && (
           // Safari 9 has enumerable `arguments.length` in strict mode.
           key == 'length' ||
           // Node.js 0.10 has enumerable non-index properties on buffers.
           (isBuff && (key == 'offset' || key == 'parent')) ||
           // PhantomJS 2 has enumerable non-index properties on typed arrays.
           (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
           // Skip index properties.
           isIndex(key, length)
        ))) {
      result.push(key);
    }
  }
  return result;
}

module.exports = arrayLikeKeys;


/***/ }),

/***/ "./node_modules/lodash/_arrayMap.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_arrayMap.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * A specialized version of `_.map` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */
function arrayMap(array, iteratee) {
  var index = -1,
      length = array == null ? 0 : array.length,
      result = Array(length);

  while (++index < length) {
    result[index] = iteratee(array[index], index, array);
  }
  return result;
}

module.exports = arrayMap;


/***/ }),

/***/ "./node_modules/lodash/_arrayPush.js":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_arrayPush.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Appends the elements of `values` to `array`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to append.
 * @returns {Array} Returns `array`.
 */
function arrayPush(array, values) {
  var index = -1,
      length = values.length,
      offset = array.length;

  while (++index < length) {
    array[offset + index] = values[index];
  }
  return array;
}

module.exports = arrayPush;


/***/ }),

/***/ "./node_modules/lodash/_arraySome.js":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_arraySome.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * A specialized version of `_.some` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 */
function arraySome(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (predicate(array[index], index, array)) {
      return true;
    }
  }
  return false;
}

module.exports = arraySome;


/***/ }),

/***/ "./node_modules/lodash/_assocIndexOf.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_assocIndexOf.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var eq = __webpack_require__(/*! ./eq */ "./node_modules/lodash/eq.js");

/**
 * Gets the index at which the `key` is found in `array` of key-value pairs.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} key The key to search for.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function assocIndexOf(array, key) {
  var length = array.length;
  while (length--) {
    if (eq(array[length][0], key)) {
      return length;
    }
  }
  return -1;
}

module.exports = assocIndexOf;


/***/ }),

/***/ "./node_modules/lodash/_baseEach.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_baseEach.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseForOwn = __webpack_require__(/*! ./_baseForOwn */ "./node_modules/lodash/_baseForOwn.js"),
    createBaseEach = __webpack_require__(/*! ./_createBaseEach */ "./node_modules/lodash/_createBaseEach.js");

/**
 * The base implementation of `_.forEach` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array|Object} Returns `collection`.
 */
var baseEach = createBaseEach(baseForOwn);

module.exports = baseEach;


/***/ }),

/***/ "./node_modules/lodash/_baseFlatten.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_baseFlatten.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var arrayPush = __webpack_require__(/*! ./_arrayPush */ "./node_modules/lodash/_arrayPush.js"),
    isFlattenable = __webpack_require__(/*! ./_isFlattenable */ "./node_modules/lodash/_isFlattenable.js");

/**
 * The base implementation of `_.flatten` with support for restricting flattening.
 *
 * @private
 * @param {Array} array The array to flatten.
 * @param {number} depth The maximum recursion depth.
 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
 * @param {Array} [result=[]] The initial result value.
 * @returns {Array} Returns the new flattened array.
 */
function baseFlatten(array, depth, predicate, isStrict, result) {
  var index = -1,
      length = array.length;

  predicate || (predicate = isFlattenable);
  result || (result = []);

  while (++index < length) {
    var value = array[index];
    if (depth > 0 && predicate(value)) {
      if (depth > 1) {
        // Recursively flatten arrays (susceptible to call stack limits).
        baseFlatten(value, depth - 1, predicate, isStrict, result);
      } else {
        arrayPush(result, value);
      }
    } else if (!isStrict) {
      result[result.length] = value;
    }
  }
  return result;
}

module.exports = baseFlatten;


/***/ }),

/***/ "./node_modules/lodash/_baseFor.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_baseFor.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var createBaseFor = __webpack_require__(/*! ./_createBaseFor */ "./node_modules/lodash/_createBaseFor.js");

/**
 * The base implementation of `baseForOwn` which iterates over `object`
 * properties returned by `keysFunc` and invokes `iteratee` for each property.
 * Iteratee functions may exit iteration early by explicitly returning `false`.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @returns {Object} Returns `object`.
 */
var baseFor = createBaseFor();

module.exports = baseFor;


/***/ }),

/***/ "./node_modules/lodash/_baseForOwn.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_baseForOwn.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseFor = __webpack_require__(/*! ./_baseFor */ "./node_modules/lodash/_baseFor.js"),
    keys = __webpack_require__(/*! ./keys */ "./node_modules/lodash/keys.js");

/**
 * The base implementation of `_.forOwn` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Object} Returns `object`.
 */
function baseForOwn(object, iteratee) {
  return object && baseFor(object, iteratee, keys);
}

module.exports = baseForOwn;


/***/ }),

/***/ "./node_modules/lodash/_baseGet.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_baseGet.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var castPath = __webpack_require__(/*! ./_castPath */ "./node_modules/lodash/_castPath.js"),
    toKey = __webpack_require__(/*! ./_toKey */ "./node_modules/lodash/_toKey.js");

/**
 * The base implementation of `_.get` without support for default values.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @returns {*} Returns the resolved value.
 */
function baseGet(object, path) {
  path = castPath(path, object);

  var index = 0,
      length = path.length;

  while (object != null && index < length) {
    object = object[toKey(path[index++])];
  }
  return (index && index == length) ? object : undefined;
}

module.exports = baseGet;


/***/ }),

/***/ "./node_modules/lodash/_baseGetAllKeys.js":
/*!************************************************!*\
  !*** ./node_modules/lodash/_baseGetAllKeys.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var arrayPush = __webpack_require__(/*! ./_arrayPush */ "./node_modules/lodash/_arrayPush.js"),
    isArray = __webpack_require__(/*! ./isArray */ "./node_modules/lodash/isArray.js");

/**
 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @param {Function} symbolsFunc The function to get the symbols of `object`.
 * @returns {Array} Returns the array of property names and symbols.
 */
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  var result = keysFunc(object);
  return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}

module.exports = baseGetAllKeys;


/***/ }),

/***/ "./node_modules/lodash/_baseGetTag.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_baseGetTag.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Symbol = __webpack_require__(/*! ./_Symbol */ "./node_modules/lodash/_Symbol.js"),
    getRawTag = __webpack_require__(/*! ./_getRawTag */ "./node_modules/lodash/_getRawTag.js"),
    objectToString = __webpack_require__(/*! ./_objectToString */ "./node_modules/lodash/_objectToString.js");

/** `Object#toString` result references. */
var nullTag = '[object Null]',
    undefinedTag = '[object Undefined]';

/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;

/**
 * The base implementation of `getTag` without fallbacks for buggy environments.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
function baseGetTag(value) {
  if (value == null) {
    return value === undefined ? undefinedTag : nullTag;
  }
  return (symToStringTag && symToStringTag in Object(value))
    ? getRawTag(value)
    : objectToString(value);
}

module.exports = baseGetTag;


/***/ }),

/***/ "./node_modules/lodash/_baseHasIn.js":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_baseHasIn.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.hasIn` without support for deep paths.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {Array|string} key The key to check.
 * @returns {boolean} Returns `true` if `key` exists, else `false`.
 */
function baseHasIn(object, key) {
  return object != null && key in Object(object);
}

module.exports = baseHasIn;


/***/ }),

/***/ "./node_modules/lodash/_baseIsArguments.js":
/*!*************************************************!*\
  !*** ./node_modules/lodash/_baseIsArguments.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "./node_modules/lodash/_baseGetTag.js"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "./node_modules/lodash/isObjectLike.js");

/** `Object#toString` result references. */
var argsTag = '[object Arguments]';

/**
 * The base implementation of `_.isArguments`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 */
function baseIsArguments(value) {
  return isObjectLike(value) && baseGetTag(value) == argsTag;
}

module.exports = baseIsArguments;


/***/ }),

/***/ "./node_modules/lodash/_baseIsEqual.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_baseIsEqual.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsEqualDeep = __webpack_require__(/*! ./_baseIsEqualDeep */ "./node_modules/lodash/_baseIsEqualDeep.js"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "./node_modules/lodash/isObjectLike.js");

/**
 * The base implementation of `_.isEqual` which supports partial comparisons
 * and tracks traversed objects.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @param {boolean} bitmask The bitmask flags.
 *  1 - Unordered comparison
 *  2 - Partial comparison
 * @param {Function} [customizer] The function to customize comparisons.
 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 */
function baseIsEqual(value, other, bitmask, customizer, stack) {
  if (value === other) {
    return true;
  }
  if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
    return value !== value && other !== other;
  }
  return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}

module.exports = baseIsEqual;


/***/ }),

/***/ "./node_modules/lodash/_baseIsEqualDeep.js":
/*!*************************************************!*\
  !*** ./node_modules/lodash/_baseIsEqualDeep.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Stack = __webpack_require__(/*! ./_Stack */ "./node_modules/lodash/_Stack.js"),
    equalArrays = __webpack_require__(/*! ./_equalArrays */ "./node_modules/lodash/_equalArrays.js"),
    equalByTag = __webpack_require__(/*! ./_equalByTag */ "./node_modules/lodash/_equalByTag.js"),
    equalObjects = __webpack_require__(/*! ./_equalObjects */ "./node_modules/lodash/_equalObjects.js"),
    getTag = __webpack_require__(/*! ./_getTag */ "./node_modules/lodash/_getTag.js"),
    isArray = __webpack_require__(/*! ./isArray */ "./node_modules/lodash/isArray.js"),
    isBuffer = __webpack_require__(/*! ./isBuffer */ "./node_modules/lodash/isBuffer.js"),
    isTypedArray = __webpack_require__(/*! ./isTypedArray */ "./node_modules/lodash/isTypedArray.js");

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    objectTag = '[object Object]';

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * A specialized version of `baseIsEqual` for arrays and objects which performs
 * deep comparisons and tracks traversed objects enabling objects with circular
 * references to be compared.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  var objIsArr = isArray(object),
      othIsArr = isArray(other),
      objTag = objIsArr ? arrayTag : getTag(object),
      othTag = othIsArr ? arrayTag : getTag(other);

  objTag = objTag == argsTag ? objectTag : objTag;
  othTag = othTag == argsTag ? objectTag : othTag;

  var objIsObj = objTag == objectTag,
      othIsObj = othTag == objectTag,
      isSameTag = objTag == othTag;

  if (isSameTag && isBuffer(object)) {
    if (!isBuffer(other)) {
      return false;
    }
    objIsArr = true;
    objIsObj = false;
  }
  if (isSameTag && !objIsObj) {
    stack || (stack = new Stack);
    return (objIsArr || isTypedArray(object))
      ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
      : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  }
  if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
    var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
        othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');

    if (objIsWrapped || othIsWrapped) {
      var objUnwrapped = objIsWrapped ? object.value() : object,
          othUnwrapped = othIsWrapped ? other.value() : other;

      stack || (stack = new Stack);
      return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
    }
  }
  if (!isSameTag) {
    return false;
  }
  stack || (stack = new Stack);
  return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}

module.exports = baseIsEqualDeep;


/***/ }),

/***/ "./node_modules/lodash/_baseIsMatch.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_baseIsMatch.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Stack = __webpack_require__(/*! ./_Stack */ "./node_modules/lodash/_Stack.js"),
    baseIsEqual = __webpack_require__(/*! ./_baseIsEqual */ "./node_modules/lodash/_baseIsEqual.js");

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;

/**
 * The base implementation of `_.isMatch` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The object to inspect.
 * @param {Object} source The object of property values to match.
 * @param {Array} matchData The property names, values, and compare flags to match.
 * @param {Function} [customizer] The function to customize comparisons.
 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
 */
function baseIsMatch(object, source, matchData, customizer) {
  var index = matchData.length,
      length = index,
      noCustomizer = !customizer;

  if (object == null) {
    return !length;
  }
  object = Object(object);
  while (index--) {
    var data = matchData[index];
    if ((noCustomizer && data[2])
          ? data[1] !== object[data[0]]
          : !(data[0] in object)
        ) {
      return false;
    }
  }
  while (++index < length) {
    data = matchData[index];
    var key = data[0],
        objValue = object[key],
        srcValue = data[1];

    if (noCustomizer && data[2]) {
      if (objValue === undefined && !(key in object)) {
        return false;
      }
    } else {
      var stack = new Stack;
      if (customizer) {
        var result = customizer(objValue, srcValue, key, object, source, stack);
      }
      if (!(result === undefined
            ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
            : result
          )) {
        return false;
      }
    }
  }
  return true;
}

module.exports = baseIsMatch;


/***/ }),

/***/ "./node_modules/lodash/_baseIsNative.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_baseIsNative.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isFunction = __webpack_require__(/*! ./isFunction */ "./node_modules/lodash/isFunction.js"),
    isMasked = __webpack_require__(/*! ./_isMasked */ "./node_modules/lodash/_isMasked.js"),
    isObject = __webpack_require__(/*! ./isObject */ "./node_modules/lodash/isObject.js"),
    toSource = __webpack_require__(/*! ./_toSource */ "./node_modules/lodash/_toSource.js");

/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;

/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;

/** Used for built-in method references. */
var funcProto = Function.prototype,
    objectProto = Object.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
  funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);

/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */
function baseIsNative(value) {
  if (!isObject(value) || isMasked(value)) {
    return false;
  }
  var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
  return pattern.test(toSource(value));
}

module.exports = baseIsNative;


/***/ }),

/***/ "./node_modules/lodash/_baseIsTypedArray.js":
/*!**************************************************!*\
  !*** ./node_modules/lodash/_baseIsTypedArray.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "./node_modules/lodash/_baseGetTag.js"),
    isLength = __webpack_require__(/*! ./isLength */ "./node_modules/lodash/isLength.js"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "./node_modules/lodash/isObjectLike.js");

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    funcTag = '[object Function]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    objectTag = '[object Object]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    weakMapTag = '[object WeakMap]';

var arrayBufferTag = '[object ArrayBuffer]',
    dataViewTag = '[object DataView]',
    float32Tag = '[object Float32Array]',
    float64Tag = '[object Float64Array]',
    int8Tag = '[object Int8Array]',
    int16Tag = '[object Int16Array]',
    int32Tag = '[object Int32Array]',
    uint8Tag = '[object Uint8Array]',
    uint8ClampedTag = '[object Uint8ClampedArray]',
    uint16Tag = '[object Uint16Array]',
    uint32Tag = '[object Uint32Array]';

/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;

/**
 * The base implementation of `_.isTypedArray` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 */
function baseIsTypedArray(value) {
  return isObjectLike(value) &&
    isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}

module.exports = baseIsTypedArray;


/***/ }),

/***/ "./node_modules/lodash/_baseIteratee.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_baseIteratee.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseMatches = __webpack_require__(/*! ./_baseMatches */ "./node_modules/lodash/_baseMatches.js"),
    baseMatchesProperty = __webpack_require__(/*! ./_baseMatchesProperty */ "./node_modules/lodash/_baseMatchesProperty.js"),
    identity = __webpack_require__(/*! ./identity */ "./node_modules/lodash/identity.js"),
    isArray = __webpack_require__(/*! ./isArray */ "./node_modules/lodash/isArray.js"),
    property = __webpack_require__(/*! ./property */ "./node_modules/lodash/property.js");

/**
 * The base implementation of `_.iteratee`.
 *
 * @private
 * @param {*} [value=_.identity] The value to convert to an iteratee.
 * @returns {Function} Returns the iteratee.
 */
function baseIteratee(value) {
  // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  if (typeof value == 'function') {
    return value;
  }
  if (value == null) {
    return identity;
  }
  if (typeof value == 'object') {
    return isArray(value)
      ? baseMatchesProperty(value[0], value[1])
      : baseMatches(value);
  }
  return property(value);
}

module.exports = baseIteratee;


/***/ }),

/***/ "./node_modules/lodash/_baseKeys.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_baseKeys.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isPrototype = __webpack_require__(/*! ./_isPrototype */ "./node_modules/lodash/_isPrototype.js"),
    nativeKeys = __webpack_require__(/*! ./_nativeKeys */ "./node_modules/lodash/_nativeKeys.js");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function baseKeys(object) {
  if (!isPrototype(object)) {
    return nativeKeys(object);
  }
  var result = [];
  for (var key in Object(object)) {
    if (hasOwnProperty.call(object, key) && key != 'constructor') {
      result.push(key);
    }
  }
  return result;
}

module.exports = baseKeys;


/***/ }),

/***/ "./node_modules/lodash/_baseMap.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_baseMap.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseEach = __webpack_require__(/*! ./_baseEach */ "./node_modules/lodash/_baseEach.js"),
    isArrayLike = __webpack_require__(/*! ./isArrayLike */ "./node_modules/lodash/isArrayLike.js");

/**
 * The base implementation of `_.map` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */
function baseMap(collection, iteratee) {
  var index = -1,
      result = isArrayLike(collection) ? Array(collection.length) : [];

  baseEach(collection, function(value, key, collection) {
    result[++index] = iteratee(value, key, collection);
  });
  return result;
}

module.exports = baseMap;


/***/ }),

/***/ "./node_modules/lodash/_baseMatches.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_baseMatches.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsMatch = __webpack_require__(/*! ./_baseIsMatch */ "./node_modules/lodash/_baseIsMatch.js"),
    getMatchData = __webpack_require__(/*! ./_getMatchData */ "./node_modules/lodash/_getMatchData.js"),
    matchesStrictComparable = __webpack_require__(/*! ./_matchesStrictComparable */ "./node_modules/lodash/_matchesStrictComparable.js");

/**
 * The base implementation of `_.matches` which doesn't clone `source`.
 *
 * @private
 * @param {Object} source The object of property values to match.
 * @returns {Function} Returns the new spec function.
 */
function baseMatches(source) {
  var matchData = getMatchData(source);
  if (matchData.length == 1 && matchData[0][2]) {
    return matchesStrictComparable(matchData[0][0], matchData[0][1]);
  }
  return function(object) {
    return object === source || baseIsMatch(object, source, matchData);
  };
}

module.exports = baseMatches;


/***/ }),

/***/ "./node_modules/lodash/_baseMatchesProperty.js":
/*!*****************************************************!*\
  !*** ./node_modules/lodash/_baseMatchesProperty.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsEqual = __webpack_require__(/*! ./_baseIsEqual */ "./node_modules/lodash/_baseIsEqual.js"),
    get = __webpack_require__(/*! ./get */ "./node_modules/lodash/get.js"),
    hasIn = __webpack_require__(/*! ./hasIn */ "./node_modules/lodash/hasIn.js"),
    isKey = __webpack_require__(/*! ./_isKey */ "./node_modules/lodash/_isKey.js"),
    isStrictComparable = __webpack_require__(/*! ./_isStrictComparable */ "./node_modules/lodash/_isStrictComparable.js"),
    matchesStrictComparable = __webpack_require__(/*! ./_matchesStrictComparable */ "./node_modules/lodash/_matchesStrictComparable.js"),
    toKey = __webpack_require__(/*! ./_toKey */ "./node_modules/lodash/_toKey.js");

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;

/**
 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
 *
 * @private
 * @param {string} path The path of the property to get.
 * @param {*} srcValue The value to match.
 * @returns {Function} Returns the new spec function.
 */
function baseMatchesProperty(path, srcValue) {
  if (isKey(path) && isStrictComparable(srcValue)) {
    return matchesStrictComparable(toKey(path), srcValue);
  }
  return function(object) {
    var objValue = get(object, path);
    return (objValue === undefined && objValue === srcValue)
      ? hasIn(object, path)
      : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
  };
}

module.exports = baseMatchesProperty;


/***/ }),

/***/ "./node_modules/lodash/_baseOrderBy.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_baseOrderBy.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var arrayMap = __webpack_require__(/*! ./_arrayMap */ "./node_modules/lodash/_arrayMap.js"),
    baseIteratee = __webpack_require__(/*! ./_baseIteratee */ "./node_modules/lodash/_baseIteratee.js"),
    baseMap = __webpack_require__(/*! ./_baseMap */ "./node_modules/lodash/_baseMap.js"),
    baseSortBy = __webpack_require__(/*! ./_baseSortBy */ "./node_modules/lodash/_baseSortBy.js"),
    baseUnary = __webpack_require__(/*! ./_baseUnary */ "./node_modules/lodash/_baseUnary.js"),
    compareMultiple = __webpack_require__(/*! ./_compareMultiple */ "./node_modules/lodash/_compareMultiple.js"),
    identity = __webpack_require__(/*! ./identity */ "./node_modules/lodash/identity.js");

/**
 * The base implementation of `_.orderBy` without param guards.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
 * @param {string[]} orders The sort orders of `iteratees`.
 * @returns {Array} Returns the new sorted array.
 */
function baseOrderBy(collection, iteratees, orders) {
  var index = -1;
  iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee));

  var result = baseMap(collection, function(value, key, collection) {
    var criteria = arrayMap(iteratees, function(iteratee) {
      return iteratee(value);
    });
    return { 'criteria': criteria, 'index': ++index, 'value': value };
  });

  return baseSortBy(result, function(object, other) {
    return compareMultiple(object, other, orders);
  });
}

module.exports = baseOrderBy;


/***/ }),

/***/ "./node_modules/lodash/_baseProperty.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_baseProperty.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.property` without support for deep paths.
 *
 * @private
 * @param {string} key The key of the property to get.
 * @returns {Function} Returns the new accessor function.
 */
function baseProperty(key) {
  return function(object) {
    return object == null ? undefined : object[key];
  };
}

module.exports = baseProperty;


/***/ }),

/***/ "./node_modules/lodash/_basePropertyDeep.js":
/*!**************************************************!*\
  !*** ./node_modules/lodash/_basePropertyDeep.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGet = __webpack_require__(/*! ./_baseGet */ "./node_modules/lodash/_baseGet.js");

/**
 * A specialized version of `baseProperty` which supports deep paths.
 *
 * @private
 * @param {Array|string} path The path of the property to get.
 * @returns {Function} Returns the new accessor function.
 */
function basePropertyDeep(path) {
  return function(object) {
    return baseGet(object, path);
  };
}

module.exports = basePropertyDeep;


/***/ }),

/***/ "./node_modules/lodash/_baseRest.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_baseRest.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var identity = __webpack_require__(/*! ./identity */ "./node_modules/lodash/identity.js"),
    overRest = __webpack_require__(/*! ./_overRest */ "./node_modules/lodash/_overRest.js"),
    setToString = __webpack_require__(/*! ./_setToString */ "./node_modules/lodash/_setToString.js");

/**
 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @returns {Function} Returns the new function.
 */
function baseRest(func, start) {
  return setToString(overRest(func, start, identity), func + '');
}

module.exports = baseRest;


/***/ }),

/***/ "./node_modules/lodash/_baseSetToString.js":
/*!*************************************************!*\
  !*** ./node_modules/lodash/_baseSetToString.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var constant = __webpack_require__(/*! ./constant */ "./node_modules/lodash/constant.js"),
    defineProperty = __webpack_require__(/*! ./_defineProperty */ "./node_modules/lodash/_defineProperty.js"),
    identity = __webpack_require__(/*! ./identity */ "./node_modules/lodash/identity.js");

/**
 * The base implementation of `setToString` without support for hot loop shorting.
 *
 * @private
 * @param {Function} func The function to modify.
 * @param {Function} string The `toString` result.
 * @returns {Function} Returns `func`.
 */
var baseSetToString = !defineProperty ? identity : function(func, string) {
  return defineProperty(func, 'toString', {
    'configurable': true,
    'enumerable': false,
    'value': constant(string),
    'writable': true
  });
};

module.exports = baseSetToString;


/***/ }),

/***/ "./node_modules/lodash/_baseSortBy.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_baseSortBy.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.sortBy` which uses `comparer` to define the
 * sort order of `array` and replaces criteria objects with their corresponding
 * values.
 *
 * @private
 * @param {Array} array The array to sort.
 * @param {Function} comparer The function to define sort order.
 * @returns {Array} Returns `array`.
 */
function baseSortBy(array, comparer) {
  var length = array.length;

  array.sort(comparer);
  while (length--) {
    array[length] = array[length].value;
  }
  return array;
}

module.exports = baseSortBy;


/***/ }),

/***/ "./node_modules/lodash/_baseTimes.js":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_baseTimes.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.times` without support for iteratee shorthands
 * or max array length checks.
 *
 * @private
 * @param {number} n The number of times to invoke `iteratee`.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the array of results.
 */
function baseTimes(n, iteratee) {
  var index = -1,
      result = Array(n);

  while (++index < n) {
    result[index] = iteratee(index);
  }
  return result;
}

module.exports = baseTimes;


/***/ }),

/***/ "./node_modules/lodash/_baseToString.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_baseToString.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Symbol = __webpack_require__(/*! ./_Symbol */ "./node_modules/lodash/_Symbol.js"),
    arrayMap = __webpack_require__(/*! ./_arrayMap */ "./node_modules/lodash/_arrayMap.js"),
    isArray = __webpack_require__(/*! ./isArray */ "./node_modules/lodash/isArray.js"),
    isSymbol = __webpack_require__(/*! ./isSymbol */ "./node_modules/lodash/isSymbol.js");

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;

/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
    symbolToString = symbolProto ? symbolProto.toString : undefined;

/**
 * The base implementation of `_.toString` which doesn't convert nullish
 * values to empty strings.
 *
 * @private
 * @param {*} value The value to process.
 * @returns {string} Returns the string.
 */
function baseToString(value) {
  // Exit early for strings to avoid a performance hit in some environments.
  if (typeof value == 'string') {
    return value;
  }
  if (isArray(value)) {
    // Recursively convert values (susceptible to call stack limits).
    return arrayMap(value, baseToString) + '';
  }
  if (isSymbol(value)) {
    return symbolToString ? symbolToString.call(value) : '';
  }
  var result = (value + '');
  return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}

module.exports = baseToString;


/***/ }),

/***/ "./node_modules/lodash/_baseUnary.js":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_baseUnary.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.unary` without support for storing metadata.
 *
 * @private
 * @param {Function} func The function to cap arguments for.
 * @returns {Function} Returns the new capped function.
 */
function baseUnary(func) {
  return function(value) {
    return func(value);
  };
}

module.exports = baseUnary;


/***/ }),

/***/ "./node_modules/lodash/_cacheHas.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_cacheHas.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Checks if a `cache` value for `key` exists.
 *
 * @private
 * @param {Object} cache The cache to query.
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function cacheHas(cache, key) {
  return cache.has(key);
}

module.exports = cacheHas;


/***/ }),

/***/ "./node_modules/lodash/_castPath.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_castPath.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isArray = __webpack_require__(/*! ./isArray */ "./node_modules/lodash/isArray.js"),
    isKey = __webpack_require__(/*! ./_isKey */ "./node_modules/lodash/_isKey.js"),
    stringToPath = __webpack_require__(/*! ./_stringToPath */ "./node_modules/lodash/_stringToPath.js"),
    toString = __webpack_require__(/*! ./toString */ "./node_modules/lodash/toString.js");

/**
 * Casts `value` to a path array if it's not one.
 *
 * @private
 * @param {*} value The value to inspect.
 * @param {Object} [object] The object to query keys on.
 * @returns {Array} Returns the cast property path array.
 */
function castPath(value, object) {
  if (isArray(value)) {
    return value;
  }
  return isKey(value, object) ? [value] : stringToPath(toString(value));
}

module.exports = castPath;


/***/ }),

/***/ "./node_modules/lodash/_compareAscending.js":
/*!**************************************************!*\
  !*** ./node_modules/lodash/_compareAscending.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isSymbol = __webpack_require__(/*! ./isSymbol */ "./node_modules/lodash/isSymbol.js");

/**
 * Compares values to sort them in ascending order.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {number} Returns the sort order indicator for `value`.
 */
function compareAscending(value, other) {
  if (value !== other) {
    var valIsDefined = value !== undefined,
        valIsNull = value === null,
        valIsReflexive = value === value,
        valIsSymbol = isSymbol(value);

    var othIsDefined = other !== undefined,
        othIsNull = other === null,
        othIsReflexive = other === other,
        othIsSymbol = isSymbol(other);

    if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
        (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
        (valIsNull && othIsDefined && othIsReflexive) ||
        (!valIsDefined && othIsReflexive) ||
        !valIsReflexive) {
      return 1;
    }
    if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
        (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
        (othIsNull && valIsDefined && valIsReflexive) ||
        (!othIsDefined && valIsReflexive) ||
        !othIsReflexive) {
      return -1;
    }
  }
  return 0;
}

module.exports = compareAscending;


/***/ }),

/***/ "./node_modules/lodash/_compareMultiple.js":
/*!*************************************************!*\
  !*** ./node_modules/lodash/_compareMultiple.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var compareAscending = __webpack_require__(/*! ./_compareAscending */ "./node_modules/lodash/_compareAscending.js");

/**
 * Used by `_.orderBy` to compare multiple properties of a value to another
 * and stable sort them.
 *
 * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
 * specify an order of "desc" for descending or "asc" for ascending sort order
 * of corresponding values.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {boolean[]|string[]} orders The order to sort by for each property.
 * @returns {number} Returns the sort order indicator for `object`.
 */
function compareMultiple(object, other, orders) {
  var index = -1,
      objCriteria = object.criteria,
      othCriteria = other.criteria,
      length = objCriteria.length,
      ordersLength = orders.length;

  while (++index < length) {
    var result = compareAscending(objCriteria[index], othCriteria[index]);
    if (result) {
      if (index >= ordersLength) {
        return result;
      }
      var order = orders[index];
      return result * (order == 'desc' ? -1 : 1);
    }
  }
  // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
  // that causes it, under certain circumstances, to provide the same value for
  // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
  // for more details.
  //
  // This also ensures a stable sort in V8 and other engines.
  // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
  return object.index - other.index;
}

module.exports = compareMultiple;


/***/ }),

/***/ "./node_modules/lodash/_coreJsData.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_coreJsData.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var root = __webpack_require__(/*! ./_root */ "./node_modules/lodash/_root.js");

/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];

module.exports = coreJsData;


/***/ }),

/***/ "./node_modules/lodash/_createBaseEach.js":
/*!************************************************!*\
  !*** ./node_modules/lodash/_createBaseEach.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isArrayLike = __webpack_require__(/*! ./isArrayLike */ "./node_modules/lodash/isArrayLike.js");

/**
 * Creates a `baseEach` or `baseEachRight` function.
 *
 * @private
 * @param {Function} eachFunc The function to iterate over a collection.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new base function.
 */
function createBaseEach(eachFunc, fromRight) {
  return function(collection, iteratee) {
    if (collection == null) {
      return collection;
    }
    if (!isArrayLike(collection)) {
      return eachFunc(collection, iteratee);
    }
    var length = collection.length,
        index = fromRight ? length : -1,
        iterable = Object(collection);

    while ((fromRight ? index-- : ++index < length)) {
      if (iteratee(iterable[index], index, iterable) === false) {
        break;
      }
    }
    return collection;
  };
}

module.exports = createBaseEach;


/***/ }),

/***/ "./node_modules/lodash/_createBaseFor.js":
/*!***********************************************!*\
  !*** ./node_modules/lodash/_createBaseFor.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
 *
 * @private
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new base function.
 */
function createBaseFor(fromRight) {
  return function(object, iteratee, keysFunc) {
    var index = -1,
        iterable = Object(object),
        props = keysFunc(object),
        length = props.length;

    while (length--) {
      var key = props[fromRight ? length : ++index];
      if (iteratee(iterable[key], key, iterable) === false) {
        break;
      }
    }
    return object;
  };
}

module.exports = createBaseFor;


/***/ }),

/***/ "./node_modules/lodash/_defineProperty.js":
/*!************************************************!*\
  !*** ./node_modules/lodash/_defineProperty.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(/*! ./_getNative */ "./node_modules/lodash/_getNative.js");

var defineProperty = (function() {
  try {
    var func = getNative(Object, 'defineProperty');
    func({}, '', {});
    return func;
  } catch (e) {}
}());

module.exports = defineProperty;


/***/ }),

/***/ "./node_modules/lodash/_equalArrays.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_equalArrays.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var SetCache = __webpack_require__(/*! ./_SetCache */ "./node_modules/lodash/_SetCache.js"),
    arraySome = __webpack_require__(/*! ./_arraySome */ "./node_modules/lodash/_arraySome.js"),
    cacheHas = __webpack_require__(/*! ./_cacheHas */ "./node_modules/lodash/_cacheHas.js");

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;

/**
 * A specialized version of `baseIsEqualDeep` for arrays with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Array} array The array to compare.
 * @param {Array} other The other array to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `array` and `other` objects.
 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
 */
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
      arrLength = array.length,
      othLength = other.length;

  if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
    return false;
  }
  // Assume cyclic values are equal.
  var stacked = stack.get(array);
  if (stacked && stack.get(other)) {
    return stacked == other;
  }
  var index = -1,
      result = true,
      seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;

  stack.set(array, other);
  stack.set(other, array);

  // Ignore non-index properties.
  while (++index < arrLength) {
    var arrValue = array[index],
        othValue = other[index];

    if (customizer) {
      var compared = isPartial
        ? customizer(othValue, arrValue, index, other, array, stack)
        : customizer(arrValue, othValue, index, array, other, stack);
    }
    if (compared !== undefined) {
      if (compared) {
        continue;
      }
      result = false;
      break;
    }
    // Recursively compare arrays (susceptible to call stack limits).
    if (seen) {
      if (!arraySome(other, function(othValue, othIndex) {
            if (!cacheHas(seen, othIndex) &&
                (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
              return seen.push(othIndex);
            }
          })) {
        result = false;
        break;
      }
    } else if (!(
          arrValue === othValue ||
            equalFunc(arrValue, othValue, bitmask, customizer, stack)
        )) {
      result = false;
      break;
    }
  }
  stack['delete'](array);
  stack['delete'](other);
  return result;
}

module.exports = equalArrays;


/***/ }),

/***/ "./node_modules/lodash/_equalByTag.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_equalByTag.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Symbol = __webpack_require__(/*! ./_Symbol */ "./node_modules/lodash/_Symbol.js"),
    Uint8Array = __webpack_require__(/*! ./_Uint8Array */ "./node_modules/lodash/_Uint8Array.js"),
    eq = __webpack_require__(/*! ./eq */ "./node_modules/lodash/eq.js"),
    equalArrays = __webpack_require__(/*! ./_equalArrays */ "./node_modules/lodash/_equalArrays.js"),
    mapToArray = __webpack_require__(/*! ./_mapToArray */ "./node_modules/lodash/_mapToArray.js"),
    setToArray = __webpack_require__(/*! ./_setToArray */ "./node_modules/lodash/_setToArray.js");

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;

/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    symbolTag = '[object Symbol]';

var arrayBufferTag = '[object ArrayBuffer]',
    dataViewTag = '[object DataView]';

/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
    symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;

/**
 * A specialized version of `baseIsEqualDeep` for comparing objects of
 * the same `toStringTag`.
 *
 * **Note:** This function only supports comparing values with tags of
 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {string} tag The `toStringTag` of the objects to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  switch (tag) {
    case dataViewTag:
      if ((object.byteLength != other.byteLength) ||
          (object.byteOffset != other.byteOffset)) {
        return false;
      }
      object = object.buffer;
      other = other.buffer;

    case arrayBufferTag:
      if ((object.byteLength != other.byteLength) ||
          !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
        return false;
      }
      return true;

    case boolTag:
    case dateTag:
    case numberTag:
      // Coerce booleans to `1` or `0` and dates to milliseconds.
      // Invalid dates are coerced to `NaN`.
      return eq(+object, +other);

    case errorTag:
      return object.name == other.name && object.message == other.message;

    case regexpTag:
    case stringTag:
      // Coerce regexes to strings and treat strings, primitives and objects,
      // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
      // for more details.
      return object == (other + '');

    case mapTag:
      var convert = mapToArray;

    case setTag:
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
      convert || (convert = setToArray);

      if (object.size != other.size && !isPartial) {
        return false;
      }
      // Assume cyclic values are equal.
      var stacked = stack.get(object);
      if (stacked) {
        return stacked == other;
      }
      bitmask |= COMPARE_UNORDERED_FLAG;

      // Recursively compare objects (susceptible to call stack limits).
      stack.set(object, other);
      var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
      stack['delete'](object);
      return result;

    case symbolTag:
      if (symbolValueOf) {
        return symbolValueOf.call(object) == symbolValueOf.call(other);
      }
  }
  return false;
}

module.exports = equalByTag;


/***/ }),

/***/ "./node_modules/lodash/_equalObjects.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_equalObjects.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getAllKeys = __webpack_require__(/*! ./_getAllKeys */ "./node_modules/lodash/_getAllKeys.js");

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * A specialized version of `baseIsEqualDeep` for objects with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
      objProps = getAllKeys(object),
      objLength = objProps.length,
      othProps = getAllKeys(other),
      othLength = othProps.length;

  if (objLength != othLength && !isPartial) {
    return false;
  }
  var index = objLength;
  while (index--) {
    var key = objProps[index];
    if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
      return false;
    }
  }
  // Assume cyclic values are equal.
  var stacked = stack.get(object);
  if (stacked && stack.get(other)) {
    return stacked == other;
  }
  var result = true;
  stack.set(object, other);
  stack.set(other, object);

  var skipCtor = isPartial;
  while (++index < objLength) {
    key = objProps[index];
    var objValue = object[key],
        othValue = other[key];

    if (customizer) {
      var compared = isPartial
        ? customizer(othValue, objValue, key, other, object, stack)
        : customizer(objValue, othValue, key, object, other, stack);
    }
    // Recursively compare objects (susceptible to call stack limits).
    if (!(compared === undefined
          ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
          : compared
        )) {
      result = false;
      break;
    }
    skipCtor || (skipCtor = key == 'constructor');
  }
  if (result && !skipCtor) {
    var objCtor = object.constructor,
        othCtor = other.constructor;

    // Non `Object` object instances with different constructors are not equal.
    if (objCtor != othCtor &&
        ('constructor' in object && 'constructor' in other) &&
        !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
          typeof othCtor == 'function' && othCtor instanceof othCtor)) {
      result = false;
    }
  }
  stack['delete'](object);
  stack['delete'](other);
  return result;
}

module.exports = equalObjects;


/***/ }),

/***/ "./node_modules/lodash/_freeGlobal.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_freeGlobal.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

module.exports = freeGlobal;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js")))

/***/ }),

/***/ "./node_modules/lodash/_getAllKeys.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_getAllKeys.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGetAllKeys = __webpack_require__(/*! ./_baseGetAllKeys */ "./node_modules/lodash/_baseGetAllKeys.js"),
    getSymbols = __webpack_require__(/*! ./_getSymbols */ "./node_modules/lodash/_getSymbols.js"),
    keys = __webpack_require__(/*! ./keys */ "./node_modules/lodash/keys.js");

/**
 * Creates an array of own enumerable property names and symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */
function getAllKeys(object) {
  return baseGetAllKeys(object, keys, getSymbols);
}

module.exports = getAllKeys;


/***/ }),

/***/ "./node_modules/lodash/_getMapData.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_getMapData.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isKeyable = __webpack_require__(/*! ./_isKeyable */ "./node_modules/lodash/_isKeyable.js");

/**
 * Gets the data for `map`.
 *
 * @private
 * @param {Object} map The map to query.
 * @param {string} key The reference key.
 * @returns {*} Returns the map data.
 */
function getMapData(map, key) {
  var data = map.__data__;
  return isKeyable(key)
    ? data[typeof key == 'string' ? 'string' : 'hash']
    : data.map;
}

module.exports = getMapData;


/***/ }),

/***/ "./node_modules/lodash/_getMatchData.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_getMatchData.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isStrictComparable = __webpack_require__(/*! ./_isStrictComparable */ "./node_modules/lodash/_isStrictComparable.js"),
    keys = __webpack_require__(/*! ./keys */ "./node_modules/lodash/keys.js");

/**
 * Gets the property names, values, and compare flags of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the match data of `object`.
 */
function getMatchData(object) {
  var result = keys(object),
      length = result.length;

  while (length--) {
    var key = result[length],
        value = object[key];

    result[length] = [key, value, isStrictComparable(value)];
  }
  return result;
}

module.exports = getMatchData;


/***/ }),

/***/ "./node_modules/lodash/_getNative.js":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_getNative.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsNative = __webpack_require__(/*! ./_baseIsNative */ "./node_modules/lodash/_baseIsNative.js"),
    getValue = __webpack_require__(/*! ./_getValue */ "./node_modules/lodash/_getValue.js");

/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */
function getNative(object, key) {
  var value = getValue(object, key);
  return baseIsNative(value) ? value : undefined;
}

module.exports = getNative;


/***/ }),

/***/ "./node_modules/lodash/_getRawTag.js":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_getRawTag.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Symbol = __webpack_require__(/*! ./_Symbol */ "./node_modules/lodash/_Symbol.js");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var nativeObjectToString = objectProto.toString;

/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;

/**
 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the raw `toStringTag`.
 */
function getRawTag(value) {
  var isOwn = hasOwnProperty.call(value, symToStringTag),
      tag = value[symToStringTag];

  try {
    value[symToStringTag] = undefined;
    var unmasked = true;
  } catch (e) {}

  var result = nativeObjectToString.call(value);
  if (unmasked) {
    if (isOwn) {
      value[symToStringTag] = tag;
    } else {
      delete value[symToStringTag];
    }
  }
  return result;
}

module.exports = getRawTag;


/***/ }),

/***/ "./node_modules/lodash/_getSymbols.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_getSymbols.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var arrayFilter = __webpack_require__(/*! ./_arrayFilter */ "./node_modules/lodash/_arrayFilter.js"),
    stubArray = __webpack_require__(/*! ./stubArray */ "./node_modules/lodash/stubArray.js");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;

/**
 * Creates an array of the own enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
  if (object == null) {
    return [];
  }
  object = Object(object);
  return arrayFilter(nativeGetSymbols(object), function(symbol) {
    return propertyIsEnumerable.call(object, symbol);
  });
};

module.exports = getSymbols;


/***/ }),

/***/ "./node_modules/lodash/_getTag.js":
/*!****************************************!*\
  !*** ./node_modules/lodash/_getTag.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var DataView = __webpack_require__(/*! ./_DataView */ "./node_modules/lodash/_DataView.js"),
    Map = __webpack_require__(/*! ./_Map */ "./node_modules/lodash/_Map.js"),
    Promise = __webpack_require__(/*! ./_Promise */ "./node_modules/lodash/_Promise.js"),
    Set = __webpack_require__(/*! ./_Set */ "./node_modules/lodash/_Set.js"),
    WeakMap = __webpack_require__(/*! ./_WeakMap */ "./node_modules/lodash/_WeakMap.js"),
    baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "./node_modules/lodash/_baseGetTag.js"),
    toSource = __webpack_require__(/*! ./_toSource */ "./node_modules/lodash/_toSource.js");

/** `Object#toString` result references. */
var mapTag = '[object Map]',
    objectTag = '[object Object]',
    promiseTag = '[object Promise]',
    setTag = '[object Set]',
    weakMapTag = '[object WeakMap]';

var dataViewTag = '[object DataView]';

/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
    mapCtorString = toSource(Map),
    promiseCtorString = toSource(Promise),
    setCtorString = toSource(Set),
    weakMapCtorString = toSource(WeakMap);

/**
 * Gets the `toStringTag` of `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
var getTag = baseGetTag;

// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
    (Map && getTag(new Map) != mapTag) ||
    (Promise && getTag(Promise.resolve()) != promiseTag) ||
    (Set && getTag(new Set) != setTag) ||
    (WeakMap && getTag(new WeakMap) != weakMapTag)) {
  getTag = function(value) {
    var result = baseGetTag(value),
        Ctor = result == objectTag ? value.constructor : undefined,
        ctorString = Ctor ? toSource(Ctor) : '';

    if (ctorString) {
      switch (ctorString) {
        case dataViewCtorString: return dataViewTag;
        case mapCtorString: return mapTag;
        case promiseCtorString: return promiseTag;
        case setCtorString: return setTag;
        case weakMapCtorString: return weakMapTag;
      }
    }
    return result;
  };
}

module.exports = getTag;


/***/ }),

/***/ "./node_modules/lodash/_getValue.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_getValue.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Gets the value at `key` of `object`.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function getValue(object, key) {
  return object == null ? undefined : object[key];
}

module.exports = getValue;


/***/ }),

/***/ "./node_modules/lodash/_hasPath.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_hasPath.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var castPath = __webpack_require__(/*! ./_castPath */ "./node_modules/lodash/_castPath.js"),
    isArguments = __webpack_require__(/*! ./isArguments */ "./node_modules/lodash/isArguments.js"),
    isArray = __webpack_require__(/*! ./isArray */ "./node_modules/lodash/isArray.js"),
    isIndex = __webpack_require__(/*! ./_isIndex */ "./node_modules/lodash/_isIndex.js"),
    isLength = __webpack_require__(/*! ./isLength */ "./node_modules/lodash/isLength.js"),
    toKey = __webpack_require__(/*! ./_toKey */ "./node_modules/lodash/_toKey.js");

/**
 * Checks if `path` exists on `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @param {Function} hasFunc The function to check properties.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 */
function hasPath(object, path, hasFunc) {
  path = castPath(path, object);

  var index = -1,
      length = path.length,
      result = false;

  while (++index < length) {
    var key = toKey(path[index]);
    if (!(result = object != null && hasFunc(object, key))) {
      break;
    }
    object = object[key];
  }
  if (result || ++index != length) {
    return result;
  }
  length = object == null ? 0 : object.length;
  return !!length && isLength(length) && isIndex(key, length) &&
    (isArray(object) || isArguments(object));
}

module.exports = hasPath;


/***/ }),

/***/ "./node_modules/lodash/_hashClear.js":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_hashClear.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var nativeCreate = __webpack_require__(/*! ./_nativeCreate */ "./node_modules/lodash/_nativeCreate.js");

/**
 * Removes all key-value entries from the hash.
 *
 * @private
 * @name clear
 * @memberOf Hash
 */
function hashClear() {
  this.__data__ = nativeCreate ? nativeCreate(null) : {};
  this.size = 0;
}

module.exports = hashClear;


/***/ }),

/***/ "./node_modules/lodash/_hashDelete.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_hashDelete.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Removes `key` and its value from the hash.
 *
 * @private
 * @name delete
 * @memberOf Hash
 * @param {Object} hash The hash to modify.
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function hashDelete(key) {
  var result = this.has(key) && delete this.__data__[key];
  this.size -= result ? 1 : 0;
  return result;
}

module.exports = hashDelete;


/***/ }),

/***/ "./node_modules/lodash/_hashGet.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_hashGet.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var nativeCreate = __webpack_require__(/*! ./_nativeCreate */ "./node_modules/lodash/_nativeCreate.js");

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Gets the hash value for `key`.
 *
 * @private
 * @name get
 * @memberOf Hash
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function hashGet(key) {
  var data = this.__data__;
  if (nativeCreate) {
    var result = data[key];
    return result === HASH_UNDEFINED ? undefined : result;
  }
  return hasOwnProperty.call(data, key) ? data[key] : undefined;
}

module.exports = hashGet;


/***/ }),

/***/ "./node_modules/lodash/_hashHas.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_hashHas.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var nativeCreate = __webpack_require__(/*! ./_nativeCreate */ "./node_modules/lodash/_nativeCreate.js");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Checks if a hash value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Hash
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function hashHas(key) {
  var data = this.__data__;
  return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}

module.exports = hashHas;


/***/ }),

/***/ "./node_modules/lodash/_hashSet.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_hashSet.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var nativeCreate = __webpack_require__(/*! ./_nativeCreate */ "./node_modules/lodash/_nativeCreate.js");

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/**
 * Sets the hash `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Hash
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the hash instance.
 */
function hashSet(key, value) {
  var data = this.__data__;
  this.size += this.has(key) ? 0 : 1;
  data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  return this;
}

module.exports = hashSet;


/***/ }),

/***/ "./node_modules/lodash/_isFlattenable.js":
/*!***********************************************!*\
  !*** ./node_modules/lodash/_isFlattenable.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Symbol = __webpack_require__(/*! ./_Symbol */ "./node_modules/lodash/_Symbol.js"),
    isArguments = __webpack_require__(/*! ./isArguments */ "./node_modules/lodash/isArguments.js"),
    isArray = __webpack_require__(/*! ./isArray */ "./node_modules/lodash/isArray.js");

/** Built-in value references. */
var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;

/**
 * Checks if `value` is a flattenable `arguments` object or array.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
 */
function isFlattenable(value) {
  return isArray(value) || isArguments(value) ||
    !!(spreadableSymbol && value && value[spreadableSymbol]);
}

module.exports = isFlattenable;


/***/ }),

/***/ "./node_modules/lodash/_isIndex.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_isIndex.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;

/**
 * Checks if `value` is a valid array-like index.
 *
 * @private
 * @param {*} value The value to check.
 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
 */
function isIndex(value, length) {
  var type = typeof value;
  length = length == null ? MAX_SAFE_INTEGER : length;

  return !!length &&
    (type == 'number' ||
      (type != 'symbol' && reIsUint.test(value))) &&
        (value > -1 && value % 1 == 0 && value < length);
}

module.exports = isIndex;


/***/ }),

/***/ "./node_modules/lodash/_isIterateeCall.js":
/*!************************************************!*\
  !*** ./node_modules/lodash/_isIterateeCall.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var eq = __webpack_require__(/*! ./eq */ "./node_modules/lodash/eq.js"),
    isArrayLike = __webpack_require__(/*! ./isArrayLike */ "./node_modules/lodash/isArrayLike.js"),
    isIndex = __webpack_require__(/*! ./_isIndex */ "./node_modules/lodash/_isIndex.js"),
    isObject = __webpack_require__(/*! ./isObject */ "./node_modules/lodash/isObject.js");

/**
 * Checks if the given arguments are from an iteratee call.
 *
 * @private
 * @param {*} value The potential iteratee value argument.
 * @param {*} index The potential iteratee index or key argument.
 * @param {*} object The potential iteratee object argument.
 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
 *  else `false`.
 */
function isIterateeCall(value, index, object) {
  if (!isObject(object)) {
    return false;
  }
  var type = typeof index;
  if (type == 'number'
        ? (isArrayLike(object) && isIndex(index, object.length))
        : (type == 'string' && index in object)
      ) {
    return eq(object[index], value);
  }
  return false;
}

module.exports = isIterateeCall;


/***/ }),

/***/ "./node_modules/lodash/_isKey.js":
/*!***************************************!*\
  !*** ./node_modules/lodash/_isKey.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isArray = __webpack_require__(/*! ./isArray */ "./node_modules/lodash/isArray.js"),
    isSymbol = __webpack_require__(/*! ./isSymbol */ "./node_modules/lodash/isSymbol.js");

/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
    reIsPlainProp = /^\w*$/;

/**
 * Checks if `value` is a property name and not a property path.
 *
 * @private
 * @param {*} value The value to check.
 * @param {Object} [object] The object to query keys on.
 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
 */
function isKey(value, object) {
  if (isArray(value)) {
    return false;
  }
  var type = typeof value;
  if (type == 'number' || type == 'symbol' || type == 'boolean' ||
      value == null || isSymbol(value)) {
    return true;
  }
  return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
    (object != null && value in Object(object));
}

module.exports = isKey;


/***/ }),

/***/ "./node_modules/lodash/_isKeyable.js":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_isKeyable.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Checks if `value` is suitable for use as unique object key.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
 */
function isKeyable(value) {
  var type = typeof value;
  return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
    ? (value !== '__proto__')
    : (value === null);
}

module.exports = isKeyable;


/***/ }),

/***/ "./node_modules/lodash/_isMasked.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_isMasked.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var coreJsData = __webpack_require__(/*! ./_coreJsData */ "./node_modules/lodash/_coreJsData.js");

/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
  var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  return uid ? ('Symbol(src)_1.' + uid) : '';
}());

/**
 * Checks if `func` has its source masked.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
 */
function isMasked(func) {
  return !!maskSrcKey && (maskSrcKey in func);
}

module.exports = isMasked;


/***/ }),

/***/ "./node_modules/lodash/_isPrototype.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_isPrototype.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used for built-in method references. */
var objectProto = Object.prototype;

/**
 * Checks if `value` is likely a prototype object.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
 */
function isPrototype(value) {
  var Ctor = value && value.constructor,
      proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;

  return value === proto;
}

module.exports = isPrototype;


/***/ }),

/***/ "./node_modules/lodash/_isStrictComparable.js":
/*!****************************************************!*\
  !*** ./node_modules/lodash/_isStrictComparable.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(/*! ./isObject */ "./node_modules/lodash/isObject.js");

/**
 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` if suitable for strict
 *  equality comparisons, else `false`.
 */
function isStrictComparable(value) {
  return value === value && !isObject(value);
}

module.exports = isStrictComparable;


/***/ }),

/***/ "./node_modules/lodash/_listCacheClear.js":
/*!************************************************!*\
  !*** ./node_modules/lodash/_listCacheClear.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */
function listCacheClear() {
  this.__data__ = [];
  this.size = 0;
}

module.exports = listCacheClear;


/***/ }),

/***/ "./node_modules/lodash/_listCacheDelete.js":
/*!*************************************************!*\
  !*** ./node_modules/lodash/_listCacheDelete.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var assocIndexOf = __webpack_require__(/*! ./_assocIndexOf */ "./node_modules/lodash/_assocIndexOf.js");

/** Used for built-in method references. */
var arrayProto = Array.prototype;

/** Built-in value references. */
var splice = arrayProto.splice;

/**
 * Removes `key` and its value from the list cache.
 *
 * @private
 * @name delete
 * @memberOf ListCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function listCacheDelete(key) {
  var data = this.__data__,
      index = assocIndexOf(data, key);

  if (index < 0) {
    return false;
  }
  var lastIndex = data.length - 1;
  if (index == lastIndex) {
    data.pop();
  } else {
    splice.call(data, index, 1);
  }
  --this.size;
  return true;
}

module.exports = listCacheDelete;


/***/ }),

/***/ "./node_modules/lodash/_listCacheGet.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_listCacheGet.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var assocIndexOf = __webpack_require__(/*! ./_assocIndexOf */ "./node_modules/lodash/_assocIndexOf.js");

/**
 * Gets the list cache value for `key`.
 *
 * @private
 * @name get
 * @memberOf ListCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function listCacheGet(key) {
  var data = this.__data__,
      index = assocIndexOf(data, key);

  return index < 0 ? undefined : data[index][1];
}

module.exports = listCacheGet;


/***/ }),

/***/ "./node_modules/lodash/_listCacheHas.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_listCacheHas.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var assocIndexOf = __webpack_require__(/*! ./_assocIndexOf */ "./node_modules/lodash/_assocIndexOf.js");

/**
 * Checks if a list cache value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf ListCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function listCacheHas(key) {
  return assocIndexOf(this.__data__, key) > -1;
}

module.exports = listCacheHas;


/***/ }),

/***/ "./node_modules/lodash/_listCacheSet.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_listCacheSet.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var assocIndexOf = __webpack_require__(/*! ./_assocIndexOf */ "./node_modules/lodash/_assocIndexOf.js");

/**
 * Sets the list cache `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf ListCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the list cache instance.
 */
function listCacheSet(key, value) {
  var data = this.__data__,
      index = assocIndexOf(data, key);

  if (index < 0) {
    ++this.size;
    data.push([key, value]);
  } else {
    data[index][1] = value;
  }
  return this;
}

module.exports = listCacheSet;


/***/ }),

/***/ "./node_modules/lodash/_mapCacheClear.js":
/*!***********************************************!*\
  !*** ./node_modules/lodash/_mapCacheClear.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Hash = __webpack_require__(/*! ./_Hash */ "./node_modules/lodash/_Hash.js"),
    ListCache = __webpack_require__(/*! ./_ListCache */ "./node_modules/lodash/_ListCache.js"),
    Map = __webpack_require__(/*! ./_Map */ "./node_modules/lodash/_Map.js");

/**
 * Removes all key-value entries from the map.
 *
 * @private
 * @name clear
 * @memberOf MapCache
 */
function mapCacheClear() {
  this.size = 0;
  this.__data__ = {
    'hash': new Hash,
    'map': new (Map || ListCache),
    'string': new Hash
  };
}

module.exports = mapCacheClear;


/***/ }),

/***/ "./node_modules/lodash/_mapCacheDelete.js":
/*!************************************************!*\
  !*** ./node_modules/lodash/_mapCacheDelete.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getMapData = __webpack_require__(/*! ./_getMapData */ "./node_modules/lodash/_getMapData.js");

/**
 * Removes `key` and its value from the map.
 *
 * @private
 * @name delete
 * @memberOf MapCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function mapCacheDelete(key) {
  var result = getMapData(this, key)['delete'](key);
  this.size -= result ? 1 : 0;
  return result;
}

module.exports = mapCacheDelete;


/***/ }),

/***/ "./node_modules/lodash/_mapCacheGet.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_mapCacheGet.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getMapData = __webpack_require__(/*! ./_getMapData */ "./node_modules/lodash/_getMapData.js");

/**
 * Gets the map value for `key`.
 *
 * @private
 * @name get
 * @memberOf MapCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function mapCacheGet(key) {
  return getMapData(this, key).get(key);
}

module.exports = mapCacheGet;


/***/ }),

/***/ "./node_modules/lodash/_mapCacheHas.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_mapCacheHas.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getMapData = __webpack_require__(/*! ./_getMapData */ "./node_modules/lodash/_getMapData.js");

/**
 * Checks if a map value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf MapCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function mapCacheHas(key) {
  return getMapData(this, key).has(key);
}

module.exports = mapCacheHas;


/***/ }),

/***/ "./node_modules/lodash/_mapCacheSet.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_mapCacheSet.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getMapData = __webpack_require__(/*! ./_getMapData */ "./node_modules/lodash/_getMapData.js");

/**
 * Sets the map `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf MapCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the map cache instance.
 */
function mapCacheSet(key, value) {
  var data = getMapData(this, key),
      size = data.size;

  data.set(key, value);
  this.size += data.size == size ? 0 : 1;
  return this;
}

module.exports = mapCacheSet;


/***/ }),

/***/ "./node_modules/lodash/_mapToArray.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_mapToArray.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Converts `map` to its key-value pairs.
 *
 * @private
 * @param {Object} map The map to convert.
 * @returns {Array} Returns the key-value pairs.
 */
function mapToArray(map) {
  var index = -1,
      result = Array(map.size);

  map.forEach(function(value, key) {
    result[++index] = [key, value];
  });
  return result;
}

module.exports = mapToArray;


/***/ }),

/***/ "./node_modules/lodash/_matchesStrictComparable.js":
/*!*********************************************************!*\
  !*** ./node_modules/lodash/_matchesStrictComparable.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * A specialized version of `matchesProperty` for source values suitable
 * for strict equality comparisons, i.e. `===`.
 *
 * @private
 * @param {string} key The key of the property to get.
 * @param {*} srcValue The value to match.
 * @returns {Function} Returns the new spec function.
 */
function matchesStrictComparable(key, srcValue) {
  return function(object) {
    if (object == null) {
      return false;
    }
    return object[key] === srcValue &&
      (srcValue !== undefined || (key in Object(object)));
  };
}

module.exports = matchesStrictComparable;


/***/ }),

/***/ "./node_modules/lodash/_memoizeCapped.js":
/*!***********************************************!*\
  !*** ./node_modules/lodash/_memoizeCapped.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var memoize = __webpack_require__(/*! ./memoize */ "./node_modules/lodash/memoize.js");

/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;

/**
 * A specialized version of `_.memoize` which clears the memoized function's
 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
 *
 * @private
 * @param {Function} func The function to have its output memoized.
 * @returns {Function} Returns the new memoized function.
 */
function memoizeCapped(func) {
  var result = memoize(func, function(key) {
    if (cache.size === MAX_MEMOIZE_SIZE) {
      cache.clear();
    }
    return key;
  });

  var cache = result.cache;
  return result;
}

module.exports = memoizeCapped;


/***/ }),

/***/ "./node_modules/lodash/_nativeCreate.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_nativeCreate.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(/*! ./_getNative */ "./node_modules/lodash/_getNative.js");

/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');

module.exports = nativeCreate;


/***/ }),

/***/ "./node_modules/lodash/_nativeKeys.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_nativeKeys.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var overArg = __webpack_require__(/*! ./_overArg */ "./node_modules/lodash/_overArg.js");

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);

module.exports = nativeKeys;


/***/ }),

/***/ "./node_modules/lodash/_nodeUtil.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_nodeUtil.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(/*! ./_freeGlobal */ "./node_modules/lodash/_freeGlobal.js");

/** Detect free variable `exports`. */
var freeExports =  true && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;

/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;

/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
  try {
    // Use `util.types` for Node.js 10+.
    var types = freeModule && freeModule.require && freeModule.require('util').types;

    if (types) {
      return types;
    }

    // Legacy `process.binding('util')` for Node.js < 10.
    return freeProcess && freeProcess.binding && freeProcess.binding('util');
  } catch (e) {}
}());

module.exports = nodeUtil;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/module.js */ "./node_modules/webpack/buildin/module.js")(module)))

/***/ }),

/***/ "./node_modules/lodash/_objectToString.js":
/*!************************************************!*\
  !*** ./node_modules/lodash/_objectToString.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used for built-in method references. */
var objectProto = Object.prototype;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var nativeObjectToString = objectProto.toString;

/**
 * Converts `value` to a string using `Object.prototype.toString`.
 *
 * @private
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 */
function objectToString(value) {
  return nativeObjectToString.call(value);
}

module.exports = objectToString;


/***/ }),

/***/ "./node_modules/lodash/_overArg.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_overArg.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Creates a unary function that invokes `func` with its argument transformed.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {Function} transform The argument transform.
 * @returns {Function} Returns the new function.
 */
function overArg(func, transform) {
  return function(arg) {
    return func(transform(arg));
  };
}

module.exports = overArg;


/***/ }),

/***/ "./node_modules/lodash/_overRest.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_overRest.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var apply = __webpack_require__(/*! ./_apply */ "./node_modules/lodash/_apply.js");

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;

/**
 * A specialized version of `baseRest` which transforms the rest array.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @param {Function} transform The rest array transform.
 * @returns {Function} Returns the new function.
 */
function overRest(func, start, transform) {
  start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  return function() {
    var args = arguments,
        index = -1,
        length = nativeMax(args.length - start, 0),
        array = Array(length);

    while (++index < length) {
      array[index] = args[start + index];
    }
    index = -1;
    var otherArgs = Array(start + 1);
    while (++index < start) {
      otherArgs[index] = args[index];
    }
    otherArgs[start] = transform(array);
    return apply(func, this, otherArgs);
  };
}

module.exports = overRest;


/***/ }),

/***/ "./node_modules/lodash/_root.js":
/*!**************************************!*\
  !*** ./node_modules/lodash/_root.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var freeGlobal = __webpack_require__(/*! ./_freeGlobal */ "./node_modules/lodash/_freeGlobal.js");

/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();

module.exports = root;


/***/ }),

/***/ "./node_modules/lodash/_setCacheAdd.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_setCacheAdd.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/**
 * Adds `value` to the array cache.
 *
 * @private
 * @name add
 * @memberOf SetCache
 * @alias push
 * @param {*} value The value to cache.
 * @returns {Object} Returns the cache instance.
 */
function setCacheAdd(value) {
  this.__data__.set(value, HASH_UNDEFINED);
  return this;
}

module.exports = setCacheAdd;


/***/ }),

/***/ "./node_modules/lodash/_setCacheHas.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_setCacheHas.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Checks if `value` is in the array cache.
 *
 * @private
 * @name has
 * @memberOf SetCache
 * @param {*} value The value to search for.
 * @returns {number} Returns `true` if `value` is found, else `false`.
 */
function setCacheHas(value) {
  return this.__data__.has(value);
}

module.exports = setCacheHas;


/***/ }),

/***/ "./node_modules/lodash/_setToArray.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_setToArray.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Converts `set` to an array of its values.
 *
 * @private
 * @param {Object} set The set to convert.
 * @returns {Array} Returns the values.
 */
function setToArray(set) {
  var index = -1,
      result = Array(set.size);

  set.forEach(function(value) {
    result[++index] = value;
  });
  return result;
}

module.exports = setToArray;


/***/ }),

/***/ "./node_modules/lodash/_setToString.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_setToString.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseSetToString = __webpack_require__(/*! ./_baseSetToString */ "./node_modules/lodash/_baseSetToString.js"),
    shortOut = __webpack_require__(/*! ./_shortOut */ "./node_modules/lodash/_shortOut.js");

/**
 * Sets the `toString` method of `func` to return `string`.
 *
 * @private
 * @param {Function} func The function to modify.
 * @param {Function} string The `toString` result.
 * @returns {Function} Returns `func`.
 */
var setToString = shortOut(baseSetToString);

module.exports = setToString;


/***/ }),

/***/ "./node_modules/lodash/_shortOut.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_shortOut.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
    HOT_SPAN = 16;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;

/**
 * Creates a function that'll short out and invoke `identity` instead
 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
 * milliseconds.
 *
 * @private
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new shortable function.
 */
function shortOut(func) {
  var count = 0,
      lastCalled = 0;

  return function() {
    var stamp = nativeNow(),
        remaining = HOT_SPAN - (stamp - lastCalled);

    lastCalled = stamp;
    if (remaining > 0) {
      if (++count >= HOT_COUNT) {
        return arguments[0];
      }
    } else {
      count = 0;
    }
    return func.apply(undefined, arguments);
  };
}

module.exports = shortOut;


/***/ }),

/***/ "./node_modules/lodash/_stackClear.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_stackClear.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var ListCache = __webpack_require__(/*! ./_ListCache */ "./node_modules/lodash/_ListCache.js");

/**
 * Removes all key-value entries from the stack.
 *
 * @private
 * @name clear
 * @memberOf Stack
 */
function stackClear() {
  this.__data__ = new ListCache;
  this.size = 0;
}

module.exports = stackClear;


/***/ }),

/***/ "./node_modules/lodash/_stackDelete.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_stackDelete.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Removes `key` and its value from the stack.
 *
 * @private
 * @name delete
 * @memberOf Stack
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function stackDelete(key) {
  var data = this.__data__,
      result = data['delete'](key);

  this.size = data.size;
  return result;
}

module.exports = stackDelete;


/***/ }),

/***/ "./node_modules/lodash/_stackGet.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_stackGet.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Gets the stack value for `key`.
 *
 * @private
 * @name get
 * @memberOf Stack
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function stackGet(key) {
  return this.__data__.get(key);
}

module.exports = stackGet;


/***/ }),

/***/ "./node_modules/lodash/_stackHas.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_stackHas.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Checks if a stack value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Stack
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function stackHas(key) {
  return this.__data__.has(key);
}

module.exports = stackHas;


/***/ }),

/***/ "./node_modules/lodash/_stackSet.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_stackSet.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var ListCache = __webpack_require__(/*! ./_ListCache */ "./node_modules/lodash/_ListCache.js"),
    Map = __webpack_require__(/*! ./_Map */ "./node_modules/lodash/_Map.js"),
    MapCache = __webpack_require__(/*! ./_MapCache */ "./node_modules/lodash/_MapCache.js");

/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;

/**
 * Sets the stack `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Stack
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the stack cache instance.
 */
function stackSet(key, value) {
  var data = this.__data__;
  if (data instanceof ListCache) {
    var pairs = data.__data__;
    if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
      pairs.push([key, value]);
      this.size = ++data.size;
      return this;
    }
    data = this.__data__ = new MapCache(pairs);
  }
  data.set(key, value);
  this.size = data.size;
  return this;
}

module.exports = stackSet;


/***/ }),

/***/ "./node_modules/lodash/_stringToPath.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_stringToPath.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var memoizeCapped = __webpack_require__(/*! ./_memoizeCapped */ "./node_modules/lodash/_memoizeCapped.js");

/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;

/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;

/**
 * Converts `string` to a property path array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the property path array.
 */
var stringToPath = memoizeCapped(function(string) {
  var result = [];
  if (string.charCodeAt(0) === 46 /* . */) {
    result.push('');
  }
  string.replace(rePropName, function(match, number, quote, subString) {
    result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
  });
  return result;
});

module.exports = stringToPath;


/***/ }),

/***/ "./node_modules/lodash/_toKey.js":
/*!***************************************!*\
  !*** ./node_modules/lodash/_toKey.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isSymbol = __webpack_require__(/*! ./isSymbol */ "./node_modules/lodash/isSymbol.js");

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;

/**
 * Converts `value` to a string key if it's not a string or symbol.
 *
 * @private
 * @param {*} value The value to inspect.
 * @returns {string|symbol} Returns the key.
 */
function toKey(value) {
  if (typeof value == 'string' || isSymbol(value)) {
    return value;
  }
  var result = (value + '');
  return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}

module.exports = toKey;


/***/ }),

/***/ "./node_modules/lodash/_toSource.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_toSource.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used for built-in method references. */
var funcProto = Function.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;

/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to convert.
 * @returns {string} Returns the source code.
 */
function toSource(func) {
  if (func != null) {
    try {
      return funcToString.call(func);
    } catch (e) {}
    try {
      return (func + '');
    } catch (e) {}
  }
  return '';
}

module.exports = toSource;


/***/ }),

/***/ "./node_modules/lodash/constant.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/constant.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Creates a function that returns `value`.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {*} value The value to return from the new function.
 * @returns {Function} Returns the new constant function.
 * @example
 *
 * var objects = _.times(2, _.constant({ 'a': 1 }));
 *
 * console.log(objects);
 * // => [{ 'a': 1 }, { 'a': 1 }]
 *
 * console.log(objects[0] === objects[1]);
 * // => true
 */
function constant(value) {
  return function() {
    return value;
  };
}

module.exports = constant;


/***/ }),

/***/ "./node_modules/lodash/eq.js":
/*!***********************************!*\
  !*** ./node_modules/lodash/eq.js ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * comparison between two values to determine if they are equivalent.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.eq(object, object);
 * // => true
 *
 * _.eq(object, other);
 * // => false
 *
 * _.eq('a', 'a');
 * // => true
 *
 * _.eq('a', Object('a'));
 * // => false
 *
 * _.eq(NaN, NaN);
 * // => true
 */
function eq(value, other) {
  return value === other || (value !== value && other !== other);
}

module.exports = eq;


/***/ }),

/***/ "./node_modules/lodash/get.js":
/*!************************************!*\
  !*** ./node_modules/lodash/get.js ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGet = __webpack_require__(/*! ./_baseGet */ "./node_modules/lodash/_baseGet.js");

/**
 * Gets the value at `path` of `object`. If the resolved value is
 * `undefined`, the `defaultValue` is returned in its place.
 *
 * @static
 * @memberOf _
 * @since 3.7.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
 * @returns {*} Returns the resolved value.
 * @example
 *
 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
 *
 * _.get(object, 'a[0].b.c');
 * // => 3
 *
 * _.get(object, ['a', '0', 'b', 'c']);
 * // => 3
 *
 * _.get(object, 'a.b.c', 'default');
 * // => 'default'
 */
function get(object, path, defaultValue) {
  var result = object == null ? undefined : baseGet(object, path);
  return result === undefined ? defaultValue : result;
}

module.exports = get;


/***/ }),

/***/ "./node_modules/lodash/hasIn.js":
/*!**************************************!*\
  !*** ./node_modules/lodash/hasIn.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseHasIn = __webpack_require__(/*! ./_baseHasIn */ "./node_modules/lodash/_baseHasIn.js"),
    hasPath = __webpack_require__(/*! ./_hasPath */ "./node_modules/lodash/_hasPath.js");

/**
 * Checks if `path` is a direct or inherited property of `object`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 * @example
 *
 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
 *
 * _.hasIn(object, 'a');
 * // => true
 *
 * _.hasIn(object, 'a.b');
 * // => true
 *
 * _.hasIn(object, ['a', 'b']);
 * // => true
 *
 * _.hasIn(object, 'b');
 * // => false
 */
function hasIn(object, path) {
  return object != null && hasPath(object, path, baseHasIn);
}

module.exports = hasIn;


/***/ }),

/***/ "./node_modules/lodash/identity.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/identity.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * This method returns the first argument it receives.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {*} value Any value.
 * @returns {*} Returns `value`.
 * @example
 *
 * var object = { 'a': 1 };
 *
 * console.log(_.identity(object) === object);
 * // => true
 */
function identity(value) {
  return value;
}

module.exports = identity;


/***/ }),

/***/ "./node_modules/lodash/isArguments.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/isArguments.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsArguments = __webpack_require__(/*! ./_baseIsArguments */ "./node_modules/lodash/_baseIsArguments.js"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "./node_modules/lodash/isObjectLike.js");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;

/**
 * Checks if `value` is likely an `arguments` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 *  else `false`.
 * @example
 *
 * _.isArguments(function() { return arguments; }());
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
  return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
    !propertyIsEnumerable.call(value, 'callee');
};

module.exports = isArguments;


/***/ }),

/***/ "./node_modules/lodash/isArray.js":
/*!****************************************!*\
  !*** ./node_modules/lodash/isArray.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */
var isArray = Array.isArray;

module.exports = isArray;


/***/ }),

/***/ "./node_modules/lodash/isArrayLike.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/isArrayLike.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isFunction = __webpack_require__(/*! ./isFunction */ "./node_modules/lodash/isFunction.js"),
    isLength = __webpack_require__(/*! ./isLength */ "./node_modules/lodash/isLength.js");

/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */
function isArrayLike(value) {
  return value != null && isLength(value.length) && !isFunction(value);
}

module.exports = isArrayLike;


/***/ }),

/***/ "./node_modules/lodash/isBuffer.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/isBuffer.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(/*! ./_root */ "./node_modules/lodash/_root.js"),
    stubFalse = __webpack_require__(/*! ./stubFalse */ "./node_modules/lodash/stubFalse.js");

/** Detect free variable `exports`. */
var freeExports =  true && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;

/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;

/**
 * Checks if `value` is a buffer.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
 * @example
 *
 * _.isBuffer(new Buffer(2));
 * // => true
 *
 * _.isBuffer(new Uint8Array(2));
 * // => false
 */
var isBuffer = nativeIsBuffer || stubFalse;

module.exports = isBuffer;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/module.js */ "./node_modules/webpack/buildin/module.js")(module)))

/***/ }),

/***/ "./node_modules/lodash/isFunction.js":
/*!*******************************************!*\
  !*** ./node_modules/lodash/isFunction.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "./node_modules/lodash/_baseGetTag.js"),
    isObject = __webpack_require__(/*! ./isObject */ "./node_modules/lodash/isObject.js");

/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    proxyTag = '[object Proxy]';

/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction(value) {
  if (!isObject(value)) {
    return false;
  }
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 9 which returns 'object' for typed arrays and other constructors.
  var tag = baseGetTag(value);
  return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}

module.exports = isFunction;


/***/ }),

/***/ "./node_modules/lodash/isLength.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/isLength.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */
function isLength(value) {
  return typeof value == 'number' &&
    value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}

module.exports = isLength;


/***/ }),

/***/ "./node_modules/lodash/isObject.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/isObject.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject(value) {
  var type = typeof value;
  return value != null && (type == 'object' || type == 'function');
}

module.exports = isObject;


/***/ }),

/***/ "./node_modules/lodash/isObjectLike.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/isObjectLike.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return value != null && typeof value == 'object';
}

module.exports = isObjectLike;


/***/ }),

/***/ "./node_modules/lodash/isSymbol.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/isSymbol.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "./node_modules/lodash/_baseGetTag.js"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "./node_modules/lodash/isObjectLike.js");

/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';

/**
 * Checks if `value` is classified as a `Symbol` primitive or object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
 * @example
 *
 * _.isSymbol(Symbol.iterator);
 * // => true
 *
 * _.isSymbol('abc');
 * // => false
 */
function isSymbol(value) {
  return typeof value == 'symbol' ||
    (isObjectLike(value) && baseGetTag(value) == symbolTag);
}

module.exports = isSymbol;


/***/ }),

/***/ "./node_modules/lodash/isTypedArray.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/isTypedArray.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsTypedArray = __webpack_require__(/*! ./_baseIsTypedArray */ "./node_modules/lodash/_baseIsTypedArray.js"),
    baseUnary = __webpack_require__(/*! ./_baseUnary */ "./node_modules/lodash/_baseUnary.js"),
    nodeUtil = __webpack_require__(/*! ./_nodeUtil */ "./node_modules/lodash/_nodeUtil.js");

/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;

/**
 * Checks if `value` is classified as a typed array.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 * @example
 *
 * _.isTypedArray(new Uint8Array);
 * // => true
 *
 * _.isTypedArray([]);
 * // => false
 */
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;

module.exports = isTypedArray;


/***/ }),

/***/ "./node_modules/lodash/keys.js":
/*!*************************************!*\
  !*** ./node_modules/lodash/keys.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var arrayLikeKeys = __webpack_require__(/*! ./_arrayLikeKeys */ "./node_modules/lodash/_arrayLikeKeys.js"),
    baseKeys = __webpack_require__(/*! ./_baseKeys */ "./node_modules/lodash/_baseKeys.js"),
    isArrayLike = __webpack_require__(/*! ./isArrayLike */ "./node_modules/lodash/isArrayLike.js");

/**
 * Creates an array of the own enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects. See the
 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * for more details.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keys(new Foo);
 * // => ['a', 'b'] (iteration order is not guaranteed)
 *
 * _.keys('hi');
 * // => ['0', '1']
 */
function keys(object) {
  return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}

module.exports = keys;


/***/ }),

/***/ "./node_modules/lodash/memoize.js":
/*!****************************************!*\
  !*** ./node_modules/lodash/memoize.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var MapCache = __webpack_require__(/*! ./_MapCache */ "./node_modules/lodash/_MapCache.js");

/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';

/**
 * Creates a function that memoizes the result of `func`. If `resolver` is
 * provided, it determines the cache key for storing the result based on the
 * arguments provided to the memoized function. By default, the first argument
 * provided to the memoized function is used as the map cache key. The `func`
 * is invoked with the `this` binding of the memoized function.
 *
 * **Note:** The cache is exposed as the `cache` property on the memoized
 * function. Its creation may be customized by replacing the `_.memoize.Cache`
 * constructor with one whose instances implement the
 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to have its output memoized.
 * @param {Function} [resolver] The function to resolve the cache key.
 * @returns {Function} Returns the new memoized function.
 * @example
 *
 * var object = { 'a': 1, 'b': 2 };
 * var other = { 'c': 3, 'd': 4 };
 *
 * var values = _.memoize(_.values);
 * values(object);
 * // => [1, 2]
 *
 * values(other);
 * // => [3, 4]
 *
 * object.a = 2;
 * values(object);
 * // => [1, 2]
 *
 * // Modify the result cache.
 * values.cache.set(object, ['a', 'b']);
 * values(object);
 * // => ['a', 'b']
 *
 * // Replace `_.memoize.Cache`.
 * _.memoize.Cache = WeakMap;
 */
function memoize(func, resolver) {
  if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  var memoized = function() {
    var args = arguments,
        key = resolver ? resolver.apply(this, args) : args[0],
        cache = memoized.cache;

    if (cache.has(key)) {
      return cache.get(key);
    }
    var result = func.apply(this, args);
    memoized.cache = cache.set(key, result) || cache;
    return result;
  };
  memoized.cache = new (memoize.Cache || MapCache);
  return memoized;
}

// Expose `MapCache`.
memoize.Cache = MapCache;

module.exports = memoize;


/***/ }),

/***/ "./node_modules/lodash/property.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/property.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseProperty = __webpack_require__(/*! ./_baseProperty */ "./node_modules/lodash/_baseProperty.js"),
    basePropertyDeep = __webpack_require__(/*! ./_basePropertyDeep */ "./node_modules/lodash/_basePropertyDeep.js"),
    isKey = __webpack_require__(/*! ./_isKey */ "./node_modules/lodash/_isKey.js"),
    toKey = __webpack_require__(/*! ./_toKey */ "./node_modules/lodash/_toKey.js");

/**
 * Creates a function that returns the value at `path` of a given object.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {Array|string} path The path of the property to get.
 * @returns {Function} Returns the new accessor function.
 * @example
 *
 * var objects = [
 *   { 'a': { 'b': 2 } },
 *   { 'a': { 'b': 1 } }
 * ];
 *
 * _.map(objects, _.property('a.b'));
 * // => [2, 1]
 *
 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
 * // => [1, 2]
 */
function property(path) {
  return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}

module.exports = property;


/***/ }),

/***/ "./node_modules/lodash/sortBy.js":
/*!***************************************!*\
  !*** ./node_modules/lodash/sortBy.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseFlatten = __webpack_require__(/*! ./_baseFlatten */ "./node_modules/lodash/_baseFlatten.js"),
    baseOrderBy = __webpack_require__(/*! ./_baseOrderBy */ "./node_modules/lodash/_baseOrderBy.js"),
    baseRest = __webpack_require__(/*! ./_baseRest */ "./node_modules/lodash/_baseRest.js"),
    isIterateeCall = __webpack_require__(/*! ./_isIterateeCall */ "./node_modules/lodash/_isIterateeCall.js");

/**
 * Creates an array of elements, sorted in ascending order by the results of
 * running each element in a collection thru each iteratee. This method
 * performs a stable sort, that is, it preserves the original sort order of
 * equal elements. The iteratees are invoked with one argument: (value).
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {...(Function|Function[])} [iteratees=[_.identity]]
 *  The iteratees to sort by.
 * @returns {Array} Returns the new sorted array.
 * @example
 *
 * var users = [
 *   { 'user': 'fred',   'age': 48 },
 *   { 'user': 'barney', 'age': 36 },
 *   { 'user': 'fred',   'age': 40 },
 *   { 'user': 'barney', 'age': 34 }
 * ];
 *
 * _.sortBy(users, [function(o) { return o.user; }]);
 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
 *
 * _.sortBy(users, ['user', 'age']);
 * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
 */
var sortBy = baseRest(function(collection, iteratees) {
  if (collection == null) {
    return [];
  }
  var length = iteratees.length;
  if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
    iteratees = [];
  } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
    iteratees = [iteratees[0]];
  }
  return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
});

module.exports = sortBy;


/***/ }),

/***/ "./node_modules/lodash/stubArray.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/stubArray.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * This method returns a new empty array.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {Array} Returns the new empty array.
 * @example
 *
 * var arrays = _.times(2, _.stubArray);
 *
 * console.log(arrays);
 * // => [[], []]
 *
 * console.log(arrays[0] === arrays[1]);
 * // => false
 */
function stubArray() {
  return [];
}

module.exports = stubArray;


/***/ }),

/***/ "./node_modules/lodash/stubFalse.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/stubFalse.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * This method returns `false`.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {boolean} Returns `false`.
 * @example
 *
 * _.times(2, _.stubFalse);
 * // => [false, false]
 */
function stubFalse() {
  return false;
}

module.exports = stubFalse;


/***/ }),

/***/ "./node_modules/lodash/toString.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/toString.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseToString = __webpack_require__(/*! ./_baseToString */ "./node_modules/lodash/_baseToString.js");

/**
 * Converts `value` to a string. An empty string is returned for `null`
 * and `undefined` values. The sign of `-0` is preserved.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 * @example
 *
 * _.toString(null);
 * // => ''
 *
 * _.toString(-0);
 * // => '-0'
 *
 * _.toString([1, 2, 3]);
 * // => '1,2,3'
 */
function toString(value) {
  return value == null ? '' : baseToString(value);
}

module.exports = toString;


/***/ }),

/***/ "./node_modules/process/browser.js":
/*!*****************************************!*\
  !*** ./node_modules/process/browser.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

// shim for using process in browser
var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;

process.listeners = function (name) { return [] }

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };


/***/ }),

/***/ "./node_modules/webpack/buildin/global.js":
/*!***********************************!*\
  !*** (webpack)/buildin/global.js ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports) {

var g;

// This works in non-strict mode
g = (function() {
	return this;
})();

try {
	// This works if eval is allowed (see CSP)
	g = g || new Function("return this")();
} catch (e) {
	// This works if the window reference is available
	if (typeof window === "object") g = window;
}

// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}

module.exports = g;


/***/ }),

/***/ "./node_modules/webpack/buildin/module.js":
/*!***********************************!*\
  !*** (webpack)/buildin/module.js ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function(module) {
	if (!module.webpackPolyfill) {
		module.deprecate = function() {};
		module.paths = [];
		// module.parent = undefined by default
		if (!module.children) module.children = [];
		Object.defineProperty(module, "loaded", {
			enumerable: true,
			get: function() {
				return module.l;
			}
		});
		Object.defineProperty(module, "id", {
			enumerable: true,
			get: function() {
				return module.i;
			}
		});
		module.webpackPolyfill = 1;
	}
	return module;
};


/***/ }),

/***/ "./node_modules/whatwg-fetch/fetch.js":
/*!********************************************!*\
  !*** ./node_modules/whatwg-fetch/fetch.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

(function(self) {
  'use strict';

  if (self.fetch) {
    return
  }

  var support = {
    searchParams: 'URLSearchParams' in self,
    iterable: 'Symbol' in self && 'iterator' in Symbol,
    blob: 'FileReader' in self && 'Blob' in self && (function() {
      try {
        new Blob()
        return true
      } catch(e) {
        return false
      }
    })(),
    formData: 'FormData' in self,
    arrayBuffer: 'ArrayBuffer' in self
  }

  if (support.arrayBuffer) {
    var viewClasses = [
      '[object Int8Array]',
      '[object Uint8Array]',
      '[object Uint8ClampedArray]',
      '[object Int16Array]',
      '[object Uint16Array]',
      '[object Int32Array]',
      '[object Uint32Array]',
      '[object Float32Array]',
      '[object Float64Array]'
    ]

    var isDataView = function(obj) {
      return obj && DataView.prototype.isPrototypeOf(obj)
    }

    var isArrayBufferView = ArrayBuffer.isView || function(obj) {
      return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
    }
  }

  function normalizeName(name) {
    if (typeof name !== 'string') {
      name = String(name)
    }
    if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
      throw new TypeError('Invalid character in header field name')
    }
    return name.toLowerCase()
  }

  function normalizeValue(value) {
    if (typeof value !== 'string') {
      value = String(value)
    }
    return value
  }

  // Build a destructive iterator for the value list
  function iteratorFor(items) {
    var iterator = {
      next: function() {
        var value = items.shift()
        return {done: value === undefined, value: value}
      }
    }

    if (support.iterable) {
      iterator[Symbol.iterator] = function() {
        return iterator
      }
    }

    return iterator
  }

  function Headers(headers) {
    this.map = {}

    if (headers instanceof Headers) {
      headers.forEach(function(value, name) {
        this.append(name, value)
      }, this)
    } else if (Array.isArray(headers)) {
      headers.forEach(function(header) {
        this.append(header[0], header[1])
      }, this)
    } else if (headers) {
      Object.getOwnPropertyNames(headers).forEach(function(name) {
        this.append(name, headers[name])
      }, this)
    }
  }

  Headers.prototype.append = function(name, value) {
    name = normalizeName(name)
    value = normalizeValue(value)
    var oldValue = this.map[name]
    this.map[name] = oldValue ? oldValue+','+value : value
  }

  Headers.prototype['delete'] = function(name) {
    delete this.map[normalizeName(name)]
  }

  Headers.prototype.get = function(name) {
    name = normalizeName(name)
    return this.has(name) ? this.map[name] : null
  }

  Headers.prototype.has = function(name) {
    return this.map.hasOwnProperty(normalizeName(name))
  }

  Headers.prototype.set = function(name, value) {
    this.map[normalizeName(name)] = normalizeValue(value)
  }

  Headers.prototype.forEach = function(callback, thisArg) {
    for (var name in this.map) {
      if (this.map.hasOwnProperty(name)) {
        callback.call(thisArg, this.map[name], name, this)
      }
    }
  }

  Headers.prototype.keys = function() {
    var items = []
    this.forEach(function(value, name) { items.push(name) })
    return iteratorFor(items)
  }

  Headers.prototype.values = function() {
    var items = []
    this.forEach(function(value) { items.push(value) })
    return iteratorFor(items)
  }

  Headers.prototype.entries = function() {
    var items = []
    this.forEach(function(value, name) { items.push([name, value]) })
    return iteratorFor(items)
  }

  if (support.iterable) {
    Headers.prototype[Symbol.iterator] = Headers.prototype.entries
  }

  function consumed(body) {
    if (body.bodyUsed) {
      return Promise.reject(new TypeError('Already read'))
    }
    body.bodyUsed = true
  }

  function fileReaderReady(reader) {
    return new Promise(function(resolve, reject) {
      reader.onload = function() {
        resolve(reader.result)
      }
      reader.onerror = function() {
        reject(reader.error)
      }
    })
  }

  function readBlobAsArrayBuffer(blob) {
    var reader = new FileReader()
    var promise = fileReaderReady(reader)
    reader.readAsArrayBuffer(blob)
    return promise
  }

  function readBlobAsText(blob) {
    var reader = new FileReader()
    var promise = fileReaderReady(reader)
    reader.readAsText(blob)
    return promise
  }

  function readArrayBufferAsText(buf) {
    var view = new Uint8Array(buf)
    var chars = new Array(view.length)

    for (var i = 0; i < view.length; i++) {
      chars[i] = String.fromCharCode(view[i])
    }
    return chars.join('')
  }

  function bufferClone(buf) {
    if (buf.slice) {
      return buf.slice(0)
    } else {
      var view = new Uint8Array(buf.byteLength)
      view.set(new Uint8Array(buf))
      return view.buffer
    }
  }

  function Body() {
    this.bodyUsed = false

    this._initBody = function(body) {
      this._bodyInit = body
      if (!body) {
        this._bodyText = ''
      } else if (typeof body === 'string') {
        this._bodyText = body
      } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
        this._bodyBlob = body
      } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
        this._bodyFormData = body
      } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
        this._bodyText = body.toString()
      } else if (support.arrayBuffer && support.blob && isDataView(body)) {
        this._bodyArrayBuffer = bufferClone(body.buffer)
        // IE 10-11 can't handle a DataView body.
        this._bodyInit = new Blob([this._bodyArrayBuffer])
      } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
        this._bodyArrayBuffer = bufferClone(body)
      } else {
        throw new Error('unsupported BodyInit type')
      }

      if (!this.headers.get('content-type')) {
        if (typeof body === 'string') {
          this.headers.set('content-type', 'text/plain;charset=UTF-8')
        } else if (this._bodyBlob && this._bodyBlob.type) {
          this.headers.set('content-type', this._bodyBlob.type)
        } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
          this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')
        }
      }
    }

    if (support.blob) {
      this.blob = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return Promise.resolve(this._bodyBlob)
        } else if (this._bodyArrayBuffer) {
          return Promise.resolve(new Blob([this._bodyArrayBuffer]))
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as blob')
        } else {
          return Promise.resolve(new Blob([this._bodyText]))
        }
      }

      this.arrayBuffer = function() {
        if (this._bodyArrayBuffer) {
          return consumed(this) || Promise.resolve(this._bodyArrayBuffer)
        } else {
          return this.blob().then(readBlobAsArrayBuffer)
        }
      }
    }

    this.text = function() {
      var rejected = consumed(this)
      if (rejected) {
        return rejected
      }

      if (this._bodyBlob) {
        return readBlobAsText(this._bodyBlob)
      } else if (this._bodyArrayBuffer) {
        return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
      } else if (this._bodyFormData) {
        throw new Error('could not read FormData body as text')
      } else {
        return Promise.resolve(this._bodyText)
      }
    }

    if (support.formData) {
      this.formData = function() {
        return this.text().then(decode)
      }
    }

    this.json = function() {
      return this.text().then(JSON.parse)
    }

    return this
  }

  // HTTP methods whose capitalization should be normalized
  var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

  function normalizeMethod(method) {
    var upcased = method.toUpperCase()
    return (methods.indexOf(upcased) > -1) ? upcased : method
  }

  function Request(input, options) {
    options = options || {}
    var body = options.body

    if (input instanceof Request) {
      if (input.bodyUsed) {
        throw new TypeError('Already read')
      }
      this.url = input.url
      this.credentials = input.credentials
      if (!options.headers) {
        this.headers = new Headers(input.headers)
      }
      this.method = input.method
      this.mode = input.mode
      if (!body && input._bodyInit != null) {
        body = input._bodyInit
        input.bodyUsed = true
      }
    } else {
      this.url = String(input)
    }

    this.credentials = options.credentials || this.credentials || 'omit'
    if (options.headers || !this.headers) {
      this.headers = new Headers(options.headers)
    }
    this.method = normalizeMethod(options.method || this.method || 'GET')
    this.mode = options.mode || this.mode || null
    this.referrer = null

    if ((this.method === 'GET' || this.method === 'HEAD') && body) {
      throw new TypeError('Body not allowed for GET or HEAD requests')
    }
    this._initBody(body)
  }

  Request.prototype.clone = function() {
    return new Request(this, { body: this._bodyInit })
  }

  function decode(body) {
    var form = new FormData()
    body.trim().split('&').forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
    return form
  }

  function parseHeaders(rawHeaders) {
    var headers = new Headers()
    rawHeaders.split(/\r?\n/).forEach(function(line) {
      var parts = line.split(':')
      var key = parts.shift().trim()
      if (key) {
        var value = parts.join(':').trim()
        headers.append(key, value)
      }
    })
    return headers
  }

  Body.call(Request.prototype)

  function Response(bodyInit, options) {
    if (!options) {
      options = {}
    }

    this.type = 'default'
    this.status = 'status' in options ? options.status : 200
    this.ok = this.status >= 200 && this.status < 300
    this.statusText = 'statusText' in options ? options.statusText : 'OK'
    this.headers = new Headers(options.headers)
    this.url = options.url || ''
    this._initBody(bodyInit)
  }

  Body.call(Response.prototype)

  Response.prototype.clone = function() {
    return new Response(this._bodyInit, {
      status: this.status,
      statusText: this.statusText,
      headers: new Headers(this.headers),
      url: this.url
    })
  }

  Response.error = function() {
    var response = new Response(null, {status: 0, statusText: ''})
    response.type = 'error'
    return response
  }

  var redirectStatuses = [301, 302, 303, 307, 308]

  Response.redirect = function(url, status) {
    if (redirectStatuses.indexOf(status) === -1) {
      throw new RangeError('Invalid status code')
    }

    return new Response(null, {status: status, headers: {location: url}})
  }

  self.Headers = Headers
  self.Request = Request
  self.Response = Response

  self.fetch = function(input, init) {
    return new Promise(function(resolve, reject) {
      var request = new Request(input, init)
      var xhr = new XMLHttpRequest()

      xhr.onload = function() {
        var options = {
          status: xhr.status,
          statusText: xhr.statusText,
          headers: parseHeaders(xhr.getAllResponseHeaders() || '')
        }
        options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')
        var body = 'response' in xhr ? xhr.response : xhr.responseText
        resolve(new Response(body, options))
      }

      xhr.onerror = function() {
        reject(new TypeError('Network request failed'))
      }

      xhr.ontimeout = function() {
        reject(new TypeError('Network request failed'))
      }

      xhr.open(request.method, request.url, true)

      if (request.credentials === 'include') {
        xhr.withCredentials = true
      }

      if ('responseType' in xhr && support.blob) {
        xhr.responseType = 'blob'
      }

      request.headers.forEach(function(value, name) {
        xhr.setRequestHeader(name, value)
      })

      xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
    })
  }
  self.fetch.polyfill = true
})(typeof self !== 'undefined' ? self : this);


/***/ }),

/***/ "./src/analytics/Analytics.js":
/*!************************************!*\
  !*** ./src/analytics/Analytics.js ***!
  \************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _AnalyticsAggregate__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AnalyticsAggregate */ "./src/analytics/AnalyticsAggregate.js");
/* harmony import */ var _AnalyticsEvents__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AnalyticsEvents */ "./src/analytics/AnalyticsEvents.js");
/* harmony import */ var _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./AnalyticsRequest */ "./src/analytics/AnalyticsRequest.js");
/* harmony import */ var _AnalyticsResponse__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./AnalyticsResponse */ "./src/analytics/AnalyticsResponse.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

/**
 * @module analytics
 */




/**
 * @description
 * Analytics class used to request analytics data from Web API.
 *
 * @requires analytics.AnalyticsAggregate
 * @requires analytics.AnalyticsEvents
 * @requires analytics.AnalyticsRequest
 * @requires analytics.AnalyticsResponse
 *
 * @example
 * const d2Analytics = new Analytics(
 *  new AnalyticsAggregate(),
 *  new AnalyticsEvents(),
 *  AnalyticsRequest,
 *  AnalyticsResponse
 * )
 *
 * @memberof module:analytics
 * @see {@link https://docs.dhis2.org/master/en/developer/html/webapi_analytics.html} Analytics API documentation
 * @see {@link https://docs.dhis2.org/master/en/developer/html/webapi_event_analytics.html} Event analytics API documentation
 */

var Analytics =
/*#__PURE__*/
function () {
  /**
   * @param {!module:analytics.AnalyticsAggregate} analyticsAggregate The AnalyticsAggregate instance
   * @param {!module:analytics.AnalyticsEvents} analyticsEvents The AnalyticsEvents instance
   * @param {!module:analytics.AnalyticsRequest} analyticsRequest The AnalyticsRequest class
   * @param {!module:analytics.AnalyticsResponse} analyticsResponse The AnalyticsResponse class
   */
  function Analytics(analyticsAggregate, analyticsEvents, analyticsRequest, analyticsResponse) {
    _classCallCheck(this, Analytics);

    this.aggregate = analyticsAggregate;
    this.events = analyticsEvents;
    this.request = analyticsRequest;
    this.response = analyticsResponse;
  }
  /**
   * @static
   *
   * @description
   * Get a new instance of the Analytics object. This will function as a singleton, once Analytics object
   * has been created when requesting getAnalytics again the original version will be returned.
   *
   * @returns {Analytics} Object with the analytics interaction properties
   *
   * @example
   * const d2Analytics = d2.getAnalytics();
   */


  _createClass(Analytics, null, [{
    key: "getAnalytics",
    value: function getAnalytics() {
      if (!Analytics.getAnalytics.analytics) {
        Analytics.getAnalytics.analytics = new Analytics(new _AnalyticsAggregate__WEBPACK_IMPORTED_MODULE_0__["default"](), new _AnalyticsEvents__WEBPACK_IMPORTED_MODULE_1__["default"](), _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_2__["default"], _AnalyticsResponse__WEBPACK_IMPORTED_MODULE_3__["default"]);
      }

      return Analytics.getAnalytics.analytics;
    }
  }]);

  return Analytics;
}();

/* harmony default export */ __webpack_exports__["default"] = (Analytics);

/***/ }),

/***/ "./src/analytics/AnalyticsAggregate.js":
/*!*********************************************!*\
  !*** ./src/analytics/AnalyticsAggregate.js ***!
  \*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _AnalyticsBase__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AnalyticsBase */ "./src/analytics/AnalyticsBase.js");
function _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); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }


/**
 * @extends module:analytics.AnalyticsBase
 *
 * @description
 * Analytics aggregate class used to request aggregate analytics data from Web API.
 *
 * @memberof module:analytics
 *
 * @see https://docs.dhis2.org/master/en/developer/html/webapi_analytics.html
 */

var AnalyticsAggregate =
/*#__PURE__*/
function (_AnalyticsBase) {
  _inherits(AnalyticsAggregate, _AnalyticsBase);

  function AnalyticsAggregate() {
    _classCallCheck(this, AnalyticsAggregate);

    return _possibleConstructorReturn(this, _getPrototypeOf(AnalyticsAggregate).apply(this, arguments));
  }

  _createClass(AnalyticsAggregate, [{
    key: "getDataValueSet",

    /**
     * @param {!AnalyticsRequest} req Request object
     *
     * @returns {Promise} Promise that resolves with the analytics data value set data from the API.
     *
     * @example
     * const req = new d2.analytics.request()
     *  .addDataDimension(['Uvn6LCg7dVU','OdiHJayrsKo'])
     *  .addPeriodDimension('LAST_4_QUARTERS')
     *  .addOrgUnitDimension(['lc3eMKXaEfw','PMa2VCrupOd'])
     *  .addOrgUnitFilter('O6uvpzGd5pu')
     *  .withStartDate('2017-10-01')
     *  .withEndDate('2017-10-31');
     *
     * d2.analytics.aggregate.getDataValueSet(req)
     * .then(console.log);
     */
    value: function getDataValueSet(req) {
      return this.fetch(req.withPath('dataValueSet'));
    }
    /**
     * @param {!AnalyticsRequest} req Request object
     *
     * @returns {Promise} Promise that resolves with the raw data from the API.
     *
     * @example
     * const req = new d2.analytics.request()
     *  .addDataDimension(['Uvn6LCg7dVU','OdiHJayrsKo'])
     *  .addPeriodDimension('LAST_4_QUARTERS')
     *  .addOrgUnitDimension(['lc3eMKXaEfw', 'PMa2VCrupOd'])
     *  .addOrgUnitFilter('O6uvpzGd5pu');
     *  .withStartDate('2017-10-01')
     *  .withEndDate('2017-10-31')
     *  .withFormat('xml');
     *
     *  d2.analytics.aggregate.getRawData(req)
     *  .then(console.log);
     */

  }, {
    key: "getRawData",
    value: function getRawData(req) {
      return this.fetch(req.withPath('rawData'));
    }
    /**
     * @param {!AnalyticsRequest} req Request object
     *
     * @returns {Promise} Promise that resolves with the SQL statement used to query the database.
     *
     * @example
     * const req = new d2.analytics.request()
     *  .addDataDimension(['Uvn6LCg7dVU','OdiHJayrsKo'])
     *  .addPeriodDimension('LAST_4_QUARTERS')
     *  .addOrgUnitDimension(['lc3eMKXaEfw', 'PMa2VCrupOd'])
     *  .addOrgUnitFilter('O6uvpzGd5pu');
     *  .withStartDate('2017-10-01')
     *  .withEndDate('2017-10-31');
     *
     *  d2.analytics.aggregate.getDebugSql(req);
     *  .then(console.log);
     */

  }, {
    key: "getDebugSql",
    value: function getDebugSql(req) {
      return this.fetch(req.withPath('debug/sql'));
    }
  }]);

  return AnalyticsAggregate;
}(_AnalyticsBase__WEBPACK_IMPORTED_MODULE_0__["default"]);

/* harmony default export */ __webpack_exports__["default"] = (AnalyticsAggregate);

/***/ }),

/***/ "./src/analytics/AnalyticsBase.js":
/*!****************************************!*\
  !*** ./src/analytics/AnalyticsBase.js ***!
  \****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
/* harmony import */ var _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AnalyticsRequest */ "./src/analytics/AnalyticsRequest.js");
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }



/**
 * @private
 * @description
 * Base class for communicating with the analytics API endpoint.
 * Its subclasses can be used to get analytics data.
 *
 * @param {Instance} [api=<Api>] Api instance to use for the requests
 *
 * @requires module:api/Api
 *
 * @memberof module:analytics
 * @abstract
 */

var AnalyticsBase =
/*#__PURE__*/
function () {
  function AnalyticsBase() {
    var api = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi();

    _classCallCheck(this, AnalyticsBase);

    this.api = api;
  }
  /**
   * Loads the analytics data and returns them as an object from the promise.
   * Two parallel requests are made against the analytics api.
   * One for getting only the metaData and one for getting the actual data.
   * This is for caching purposes, as in many situations the metaData request changes while
   * the data one will be the same and thus have the same response.
   * This methods takes care of adding the default extra parameters to both requests.
   *
   * @param {!AnalyticsRequest} req Analytics request object with the request details
   *
   * @returns {Promise} Promise that resolves with the analytics data and metaData from the api.
   *
   * @example
   * const req = new d2.analytics.request()
   *  .addDataDimension(['Uvn6LCg7dVU','OdiHJayrsKo'])
   *  .addPeriodDimension('LAST_4_QUARTERS')
   *  .addOrgUnitDimension(['lc3eMKXaEfw','PMa2VCrupOd']);
   *
   * d2.analytics.aggregate
   *  .get(req)
   *  .then(analyticsData => console.log('Analytics data', analyticsData))
   *
   * // { metaData: { ... }, rows: [ ... ], headers: [ ... ], height: 0, width: 0 }
   */


  _createClass(AnalyticsBase, [{
    key: "get",
    value: function get(req) {
      // keep metaData and data requests separate for caching purposes
      var metaDataReq = new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_1__["default"](req).withSkipMeta(false).withSkipData(true).withIncludeMetadataDetails(true);
      var dataReq = new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_1__["default"](req).withSkipData(false).withSkipMeta(true); // parallelize requests

      return Promise.all([this.fetch(dataReq, {
        sorted: true
      }), this.fetch(metaDataReq)]).then(function (responses) {
        return Promise.resolve(_objectSpread({}, responses[0], {
          metaData: responses[1].metaData
        }));
      });
    }
    /**
     * @private
     * @description
     * This method does not manipulate the request object, but directly requests the data from the api
     * based on the request's configuration.
     *
     * @param {!AnalyticsRequest} req Request object
     * @param {Object} options Optional configurations, ie. for sorting dimensions
     *
     * @returns {Promise} Promise that resolves with the data from the api.
     *
     * @example
     * const req = new d2.analytics.request()
     *  .fromModel(chartModel)
     *  .withSkipData();
     *
     * d2.analytics.aggregate
     *  .fetch(req)
     *  .then(analyticsData => console.log('Analytics data', analyticsData))
     *
     * // { metaData: { ... }, rows: [], height: 0, width: 0 }
     */

  }, {
    key: "fetch",
    value: function fetch(req, options) {
      return this.api.get(req.buildUrl(options), req.buildQuery(options)).then(function (data) {
        return Promise.resolve(data);
      });
    }
  }]);

  return AnalyticsBase;
}();

/* harmony default export */ __webpack_exports__["default"] = (AnalyticsBase);

/***/ }),

/***/ "./src/analytics/AnalyticsEvents.js":
/*!******************************************!*\
  !*** ./src/analytics/AnalyticsEvents.js ***!
  \******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _AnalyticsBase__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AnalyticsBase */ "./src/analytics/AnalyticsBase.js");
function _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); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }


/**
 * @extends module:analytics.AnalyticsBase
 *
 * @description
 * Analytics events class used to request analytics events data from Web API.
 *
 * @memberof module:analytics
 *
 * @see https://docs.dhis2.org/master/en/developer/html/webapi_event_analytics.html
 */

var AnalyticsEvents =
/*#__PURE__*/
function (_AnalyticsBase) {
  _inherits(AnalyticsEvents, _AnalyticsBase);

  function AnalyticsEvents() {
    _classCallCheck(this, AnalyticsEvents);

    return _possibleConstructorReturn(this, _getPrototypeOf(AnalyticsEvents).apply(this, arguments));
  }

  _createClass(AnalyticsEvents, [{
    key: "getAggregate",

    /**
     * @param {!AnalyticsRequest} req Request object
     *
     * @returns {Promise} Promise that resolves with the analytics aggregate data from the api.
     *
     * @example
     * const req = new d2.analytics.request()
     *  .withProgram('eBAyeGv0exc')
     *  .addDataDimension(['Uvn6LCg7dVU','OdiHJayrsKo'])
     *  .addPeriodDimension('LAST_4_QUARTERS')
     *  .addOrgUnitDimension(['lc3eMKXaEfw','PMa2VCrupOd'])
     *  .addOrgUnitFilter('O6uvpzGd5pu')
     *  .withStartDate('2017-10-01')
     *  .withEndDate('2017-10-31');
     *
     *  d2.analytics.events.getAggregate(req)
     *  .then(console.log);
     */
    value: function getAggregate(req) {
      return this.fetch(req.withPath('events/aggregate'));
    }
    /**
     * @param {!AnalyticsRequest} req Request object
     *
     * @returns {Promise} Promise that resolves with the analytics count data from the api.
     *
     * @example
     * const req = new d2.analytics.request()
     *  .withProgram('eBAyeGv0exc')
     *  .addDataDimension(['Uvn6LCg7dVU','OdiHJayrsKo'])
     *  .addPeriodDimension('LAST_4_QUARTERS')
     *  .addOrgUnitDimension(['lc3eMKXaEfw','PMa2VCrupOd'])
     *  .addOrgUnitFilter('O6uvpzGd5pu')
     *  .withStartDate('2017-10-01')
     *  .withEndDate('2017-10-31');
     *
     *  d2.analytics.events.getCount(req)
     *  .then(console.log);
     */

  }, {
    key: "getCount",
    value: function getCount(req) {
      return this.fetch(req.withPath('events/count'));
    }
    /**
     * @param {!AnalyticsRequest} req Request object
     * Must contain clusterSize and bbox parameters.
     *
     * @returns {Promise} Promise that resolves with the analytics cluster data from the api.
     *
     * @example
     * const req = new d2.analytics.request()
     *  .withProgram('eBAyeGv0exc')
     *  .addDataDimension(['Uvn6LCg7dVU','OdiHJayrsKo'])
     *  .addPeriodDimension('LAST_4_QUARTERS')
     *  .addOrgUnitDimension(['lc3eMKXaEfw','PMa2VCrupOd'])
     *  .addOrgUnitFilter('O6uvpzGd5pu')
     *  .withStartDate('2017-10-01')
     *  .withEndDate('2017-10-31')
     *  .withClusterSize(100000)
     *  .withBbox('-13.2682125,7.3721619,-10.4261178,9.904012');
     *
     *  d2.analytics.events.getCluster(req)
     *  .then(console.log);
     */

  }, {
    key: "getCluster",
    value: function getCluster(req) {
      return this.fetch(req.withPath('events/cluster'));
    }
    /**
     * @param {!AnalyticsRequest} req Request object
     *
     * @returns {Promise} Promise that resolves with the analytics query data from the api.
     *
     * @example
     * const req = new d2.analytics.request()
     *  .withProgram('eBAyeGv0exc')
     *  .addDataDimension(['Uvn6LCg7dVU','OdiHJayrsKo'])
     *  .addPeriodDimension('LAST_4_QUARTERS')
     *  .addOrgUnitDimension(['lc3eMKXaEfw','PMa2VCrupOd'])
     *  .addOrgUnitFilter('O6uvpzGd5pu')
     *  .withStartDate('2017-10-01')
     *  .withEndDate('2017-10-31');
     *
     *  d2.analytics.events.getQuery(req)
     *  .then(console.log);
     */

  }, {
    key: "getQuery",
    value: function getQuery(req) {
      return this.fetch(req.withPath('events/query'));
    }
  }]);

  return AnalyticsEvents;
}(_AnalyticsBase__WEBPACK_IMPORTED_MODULE_0__["default"]);

/* harmony default export */ __webpack_exports__["default"] = (AnalyticsEvents);

/***/ }),

/***/ "./src/analytics/AnalyticsRequest.js":
/*!*******************************************!*\
  !*** ./src/analytics/AnalyticsRequest.js ***!
  \*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _AnalyticsRequestDimensionsMixin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AnalyticsRequestDimensionsMixin */ "./src/analytics/AnalyticsRequestDimensionsMixin.js");
/* harmony import */ var _AnalyticsRequestFiltersMixin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AnalyticsRequestFiltersMixin */ "./src/analytics/AnalyticsRequestFiltersMixin.js");
/* harmony import */ var _AnalyticsRequestPropertiesMixin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./AnalyticsRequestPropertiesMixin */ "./src/analytics/AnalyticsRequestPropertiesMixin.js");
/* harmony import */ var _AnalyticsRequestBase__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./AnalyticsRequestBase */ "./src/analytics/AnalyticsRequestBase.js");
function _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); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }





/**
 * @description
 * Class for constructing a request object to use for communicating with the analytics API endpoint.
 *
 * @param {!Object} options Object with analytics request options
 *
 * @memberof module:analytics
 *
 * @extends module:analytics.AnalyticsRequestDisensionsMixin
 * @extends module:analytics.AnalyticsRequestFiltersMixin
 * @extends module:analytics.AnalyticsRequestPropertiesMixin
 * @extends module:analytics.AnalyticsRequestBase
 */

var AnalyticsRequest =
/*#__PURE__*/
function (_AnalyticsRequestDime) {
  _inherits(AnalyticsRequest, _AnalyticsRequestDime);

  function AnalyticsRequest() {
    _classCallCheck(this, AnalyticsRequest);

    return _possibleConstructorReturn(this, _getPrototypeOf(AnalyticsRequest).apply(this, arguments));
  }

  _createClass(AnalyticsRequest, [{
    key: "fromModel",

    /**
     * Extracts dimensions and filters from an analytic object model and add them to the request
     *
     * @param {Object} model The analytics object model from which extract the dimensions/filters
     * @param {Boolean} [passFilterAsDimension=false] Pass filters as dimension in the query string (used in dataValueSet requests)
     *
     * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
     *
     * @example
     * const req = new d2.analytics.request()
     *    .fromModel(model);
     *
     * // dimension=pe:LAST_12_MONTH&dimension=dx:fbfJHSPpUQD;cYeuwXTCPkU;Jtf34kNZhzP;hfdmMSPBgLG&filter=ou:ImspTQPwCqd
     *
     * const req2 = new d2.analytics.request()
     *    .fromModel(model, true);
     *
     * // dimension=pe:LAST_12_MONTH&dimension=dx:fbfJHSPpUQD;cYeuwXTCPkU;Jtf34kNZhzP;hfdmMSPBgLG&dimension=ou:ImspTQPwCqd
     */
    value: function fromModel(model) {
      var passFilterAsDimension = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
      var request = this; // extract dimensions from model

      var columns = model.columns || [];
      var rows = model.rows || [];
      columns.concat(rows).forEach(function (d) {
        var dimension = d.dimension;

        if (d.filter) {
          dimension += ":".concat(d.filter);
        }

        request = request.addDimension(dimension, d.items.map(function (item) {
          return item.id;
        }));
      }); // extract filters from model

      var filters = model.filters || []; // only pass dx/pe/ou as dimension

      var fixedIds = ['dx', 'ou', 'pe'];
      filters.forEach(function (f) {
        request = passFilterAsDimension && fixedIds.includes(f.dimension) ? request.addDimension(f.dimension, f.items.map(function (item) {
          return item.id;
        })) : request.addFilter(f.dimension, f.items.map(function (item) {
          return item.id;
        }));
      });
      return request;
    }
  }]);

  return AnalyticsRequest;
}(Object(_AnalyticsRequestDimensionsMixin__WEBPACK_IMPORTED_MODULE_0__["default"])(Object(_AnalyticsRequestFiltersMixin__WEBPACK_IMPORTED_MODULE_1__["default"])(Object(_AnalyticsRequestPropertiesMixin__WEBPACK_IMPORTED_MODULE_2__["default"])(_AnalyticsRequestBase__WEBPACK_IMPORTED_MODULE_3__["default"]))));

/* harmony default export */ __webpack_exports__["default"] = (AnalyticsRequest);

/***/ }),

/***/ "./src/analytics/AnalyticsRequestBase.js":
/*!***********************************************!*\
  !*** ./src/analytics/AnalyticsRequestBase.js ***!
  \***********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var lodash_sortBy__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash/sortBy */ "./node_modules/lodash/sortBy.js");
/* harmony import */ var lodash_sortBy__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash_sortBy__WEBPACK_IMPORTED_MODULE_0__);
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }


/**
 * @private
 * @description
 * Class for constructing a request object to use for communicating with the analytics API endpoint.
 *
 * @param {!Object} options Object with analytics request options
 *
 * @requires module:lib/utils
 *
 * @memberof module:analytics
 * @abstract
 */

var AnalyticsRequestBase =
/*#__PURE__*/
function () {
  function AnalyticsRequestBase() {
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref$endPoint = _ref.endPoint,
        endPoint = _ref$endPoint === void 0 ? 'analytics' : _ref$endPoint,
        _ref$format = _ref.format,
        format = _ref$format === void 0 ? 'json' : _ref$format,
        path = _ref.path,
        program = _ref.program,
        _ref$dimensions = _ref.dimensions,
        dimensions = _ref$dimensions === void 0 ? [] : _ref$dimensions,
        _ref$filters = _ref.filters,
        filters = _ref$filters === void 0 ? [] : _ref$filters,
        _ref$parameters = _ref.parameters,
        parameters = _ref$parameters === void 0 ? {} : _ref$parameters;

    _classCallCheck(this, AnalyticsRequestBase);

    this.endPoint = endPoint;
    this.format = format.toLowerCase();
    this.path = path;
    this.program = program;
    this.dimensions = dimensions;
    this.filters = filters;
    this.parameters = _objectSpread({}, parameters);
  }
  /**
   * @private
   * @description
   * Builds the URL to pass to the Api object.
   * The URL includes the dimension(s) parameters.
   * Used internally.
   *
   * @param {Object} options Optional configurations
   *
   * @returns {String} URL URL for the request with dimensions included
   */


  _createClass(AnalyticsRequestBase, [{
    key: "buildUrl",
    value: function buildUrl(options) {
      // at least 1 dimension is required
      var dimensions = this.dimensions;

      if (options && options.sorted) {
        dimensions = lodash_sortBy__WEBPACK_IMPORTED_MODULE_0___default()(dimensions, 'dimension');
      }

      var formattedDimensions = dimensions.map(function (_ref2) {
        var dimension = _ref2.dimension,
            items = _ref2.items;

        if (Array.isArray(items) && items.length) {
          if (options && options.sorted) {
            items = lodash_sortBy__WEBPACK_IMPORTED_MODULE_0___default()(items);
          }

          return "".concat(dimension, ":").concat(items.join(';'));
        }

        return dimension;
      });
      var endPoint = [this.endPoint, this.path, this.program].filter(function (e) {
        return !!e;
      }).join('/');
      return "".concat(endPoint, ".").concat(this.format, "?dimension=").concat(formattedDimensions.join('&dimension='));
    }
    /**
     * @private
     * @description
     * Builds the query object passed to the API instance.
     * The object includes all the parameters added via with*() methods
     * and the filters added via addDataFilter(), addPeriodFilter(), addOrgUnitFilter(), addFilter().
     * The filters are handled by the API instance when building the final URL.
     * Used internally.
     *
     * @param {Object} options Optional configurations
     *
     * @returns {Object} Query parameters
     */

  }, {
    key: "buildQuery",
    value: function buildQuery(options) {
      var filters = this.filters;

      if (options && options.sorted) {
        filters = lodash_sortBy__WEBPACK_IMPORTED_MODULE_0___default()(filters, 'dimension');
      }

      var formattedFilters = filters.map(function (_ref3) {
        var dimension = _ref3.dimension,
            items = _ref3.items;

        if (Array.isArray(items) && items.length) {
          if (options && options.sorted) {
            items = lodash_sortBy__WEBPACK_IMPORTED_MODULE_0___default()(items);
          }

          return "".concat(dimension, ":").concat(items.join(';'));
        }

        return dimension;
      });

      if (filters.length) {
        this.parameters.filter = formattedFilters;
      }

      return this.parameters;
    }
  }]);

  return AnalyticsRequestBase;
}();

/* harmony default export */ __webpack_exports__["default"] = (AnalyticsRequestBase);

/***/ }),

/***/ "./src/analytics/AnalyticsRequestDimensionsMixin.js":
/*!**********************************************************!*\
  !*** ./src/analytics/AnalyticsRequestDimensionsMixin.js ***!
  \**********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AnalyticsRequest */ "./src/analytics/AnalyticsRequest.js");
function _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); }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }


/**
 * @private
 * @description
 * AnalyticsRequest dimensions mixin function
 *
 * @param {*} base The base class to mix onto
 * @return {module:analytics.AnalyticsRequestDimensionsMixin} The mixin class
 */

/**
 * @private
 * @description
 * AnalyticsRequest dimensions mixin class
 *
 * @alias module:analytics.AnalyticsRequestDimensionsMixin
 */

var AnalyticsRequestDimensionsMixin = function AnalyticsRequestDimensionsMixin(base) {
  return (
    /*#__PURE__*/
    function (_base) {
      _inherits(_class, _base);

      function _class() {
        _classCallCheck(this, _class);

        return _possibleConstructorReturn(this, _getPrototypeOf(_class).apply(this, arguments));
      }

      _createClass(_class, [{
        key: "addDataDimension",

        /**
         * Adds/updates the dx dimension to use in the request.
         *
         * @param {!(String|Array)} items The dimension items to add to the dx dimension
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .addDataDimension(['fbfJHSPpUQD', 'cYeuwXTCPkU'])
         *    .addDataDimension('BfMAe6Itzgt.REPORTING_RATE');
         *
         * // dimension=dx:fbfJHSPpUQD;cYeuwXTCPkU;BfMAe6Itzgt.REPORTING_RATE
         *
         */
        value: function addDataDimension(items) {
          return this.addDimension('dx', items);
        }
        /**
         * Adds/updates the pe dimension to use in the request.
         *
         * @param {!(String|Array)} items The dimension items to add to the pe dimension
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .addPeriodDimension(['201701', '201702'])
         *    .addPeriodDimension('LAST_4_QUARTERS');
         *
         * // dimension=pe:201701;201702;LAST_4_QUARTERS
         */

      }, {
        key: "addPeriodDimension",
        value: function addPeriodDimension(items) {
          return this.addDimension('pe', items);
        }
        /**
         * Adds/updates the ou dimension to use in the request.
         *
         * @param {!(String|Array)} items The dimension items to add to the ou dimension
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .addOrgUnitDimension(['O6uvpzGd5pu', 'lc3eMKXaEfw'])
         *    .addOrgUnitDimension('OU_GROUP-w0gFTTmsUcF');
         *
         * // dimension=ou:O6uvpzGd5pu;lc3eMKXaEfw;OU_GROUP-w0gFTTmsUcF
         */

      }, {
        key: "addOrgUnitDimension",
        value: function addOrgUnitDimension(items) {
          return this.addDimension('ou', items);
        }
        /**
         * Adds a new dimension or updates an existing one to use in the request.
         *
         * @param {!String} dimension The dimension to add to the request
         * @param {(String|Array)} items The dimension items to add to the dimension
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .addDimension('Bpx0589u8y0', ['oRVt7g429ZO', 'MAs88nJc9nL'])
         *    .addDimension('qrur9Dvnyt5-Yf6UHoPkdS6');
         *
         * // dimension=Bpx0589u8y0:oRVt7g429ZO;MAs88nJc9nL&dimension=qrur9Dvnyt5-Yf6UHoPkdS6
         */
        // eslint-disable-next-line complexity

      }, {
        key: "addDimension",
        value: function addDimension(dimension, items) {
          var dimensionIndex = 0;
          var existingDimension = this.dimensions.find(function (item, index) {
            if (item.dimension === dimension) {
              dimensionIndex = index;
              return item;
            }

            return false;
          });
          var updatedItems = [];
          var existingItems = [];

          if (existingDimension) {
            existingItems = existingDimension.items || [];
          }

          if (typeof items === 'string') {
            updatedItems = _toConsumableArray(new Set([].concat(_toConsumableArray(existingItems), [items])));
          } else if (Array.isArray(items)) {
            updatedItems = _toConsumableArray(new Set([].concat(_toConsumableArray(existingItems), _toConsumableArray(items))));
          }

          if (existingDimension) {
            this.dimensions.splice(dimensionIndex, 1, {
              dimension: dimension,
              items: updatedItems
            });
          } else {
            this.dimensions.push({
              dimension: dimension,
              items: updatedItems
            });
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
      }]);

      return _class;
    }(base)
  );
};

/* harmony default export */ __webpack_exports__["default"] = (AnalyticsRequestDimensionsMixin);

/***/ }),

/***/ "./src/analytics/AnalyticsRequestFiltersMixin.js":
/*!*******************************************************!*\
  !*** ./src/analytics/AnalyticsRequestFiltersMixin.js ***!
  \*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AnalyticsRequest */ "./src/analytics/AnalyticsRequest.js");
function _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); }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }


/**
 * @private
 * @description
 * AnalyticsRequest filters mixin function
 *
 * @param {*} base The base class to mix onto
 * @return {module:analytics.AnalyticsRequestFiltersMixin} The mixin class
 * @mixin
 */

/**
 * @private
 * @description
 * AnalyticsRequest filters mixin class
 *
 * @alias module:analytics.AnalyticsRequestFiltersMixin
 */

var AnalyticsRequestFiltersMixin = function AnalyticsRequestFiltersMixin(base) {
  return (
    /*#__PURE__*/
    function (_base) {
      _inherits(_class, _base);

      function _class() {
        _classCallCheck(this, _class);

        return _possibleConstructorReturn(this, _getPrototypeOf(_class).apply(this, arguments));
      }

      _createClass(_class, [{
        key: "addDataFilter",

        /**
         * Adds/updates the dx dimension filter to use in the request.
         *
         * @param {!(String|Array)} items The dimension items to add to the dx dimension filter
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .addDataFilter(['fbfJHSPpUQD', 'cYeuwXTCPkU'])
         *    .addDataFilter('BfMAe6Itzgt.REPORTING_RATE');
         *
         * // filter=dx:fbfJHSPpUQD;cYeuwXTCPkU;BfMAe6Itzgt.REPORTING_RATE
         */
        value: function addDataFilter(items) {
          return this.addFilter('dx', items);
        }
        /**
         * Adds/updates the pe dimension filter to use in the request.
         *
         * @param {!(String|Array)} items The dimension items to add to the pe dimension filter
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .addPeriodFilter(['201701', '201702'])
         *    .addPeriodFilter('LAST_4_QUARTERS')
         *
         * // filter=pe:201701;201702;LAST_4_QUARTERS
         */

      }, {
        key: "addPeriodFilter",
        value: function addPeriodFilter(items) {
          return this.addFilter('pe', items);
        }
        /**
         * Adds/updates the ou dimension filter to use in the request.
         *
         * @param {!(String|Array)} items The dimension items to add to the ou dimension filter
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .addOrgUnitFilter(['O6uvpzGd5pu', 'lc3eMKXaEfw'])
         *    .addOrgUnitFilter('OU_GROUP-w0gFTTmsUcF')
         *
         * // filter=ou:O6uvpzGd5pu;lc3eMKXaEfw;OU_GROUP-w0gFTTmsUcF
         */

      }, {
        key: "addOrgUnitFilter",
        value: function addOrgUnitFilter(items) {
          return this.addFilter('ou', items);
        }
        /**
         * Adds a filter to the request.
         *
         * @param {!String} dimension The dimension to add as filter to the request
         * @param {(String|Array)} items The dimension items to add to the dimension filter
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .addFilter('Bpx0589u8y0', ['oRVt7g429ZO', 'MAs88nJc9nL'])
         *    .addFilter('qrur9Dvnyt5-Yf6UHoPkdS6');
         *
         * // filter=Bpx0589u8y0:oRVt7g429ZO;MAs88nJc9nL&filter=qrur9Dvnyt5-Yf6UHoPkdS6
         */
        // eslint-disable-next-line complexity

      }, {
        key: "addFilter",
        value: function addFilter(dimension, items) {
          var filterIndex = 0;
          var existingFilter = this.filters.find(function (item, index) {
            if (item.dimension === dimension) {
              filterIndex = index;
              return item;
            }

            return false;
          });
          var updatedItems = [];
          var existingItems = [];

          if (existingFilter) {
            existingItems = existingFilter.items || [];
          }

          if (typeof items === 'string') {
            updatedItems = _toConsumableArray(new Set([].concat(_toConsumableArray(existingItems), [items])));
          } else if (Array.isArray(items)) {
            updatedItems = _toConsumableArray(new Set([].concat(_toConsumableArray(existingItems), _toConsumableArray(items))));
          }

          if (existingFilter) {
            this.filters.splice(filterIndex, 1, {
              dimension: dimension,
              items: updatedItems
            });
          } else {
            this.filters.push({
              dimension: dimension,
              items: updatedItems
            });
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
      }]);

      return _class;
    }(base)
  );
};

/* harmony default export */ __webpack_exports__["default"] = (AnalyticsRequestFiltersMixin);

/***/ }),

/***/ "./src/analytics/AnalyticsRequestPropertiesMixin.js":
/*!**********************************************************!*\
  !*** ./src/analytics/AnalyticsRequestPropertiesMixin.js ***!
  \**********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AnalyticsRequest */ "./src/analytics/AnalyticsRequest.js");
function _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); }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

/* eslint no-console: 0 */

/**
 * @private
 * @description
 * AnalyticsRequest properties mixin function
 *
 * @param {*} base The base class to mix onto
 * @return {module:analytics.AnalyticsRequestPropertiesMixin} The mixin class
 */

/**
 * @private
 * @description
 * AnalyticsRequest properties mixin
 *
 * @alias module:analytics.AnalyticsRequestPropertiesMixin
 */

var AnalyticsRequestPropertiesMixin = function AnalyticsRequestPropertiesMixin(base) {
  return (
    /*#__PURE__*/
    function (_base) {
      _inherits(_class, _base);

      function _class() {
        _classCallCheck(this, _class);

        return _possibleConstructorReturn(this, _getPrototypeOf(_class).apply(this, arguments));
      }

      _createClass(_class, [{
        key: "withParameters",

        /**
         * Sets the query parameters of the request
         *
         * @param {!Object} parameters The query parameters to add/modify to the request
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *   .withParameters({ completedOnly: true, aggregationType: 'AVERAGE' });
         */
        value: function withParameters(params) {
          if (params) {
            this.parameters = _objectSpread({}, this.parameters, params);
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Sets the URL path for the request.
         * It appends the given path to the request's URL.
         *
         * @param {!String} path The path of the response
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withPath('aggregate');
         */

      }, {
        key: "withPath",
        value: function withPath(path) {
          if (path) {
            this.path = path;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Sets the response format for the request.
         * It appends the file extension to the request's path.
         *
         * @param {String} [format=json] The format of the response
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withFormat('xml');
         */

      }, {
        key: "withFormat",
        value: function withFormat() {
          var format = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'json';
          this.format = format;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the aggregationType query parameter to the request.
         *
         * @param {String} aggregationType The aggregationType value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withAggregationType('SUM');
         */

      }, {
        key: "withAggregationType",
        value: function withAggregationType(value) {
          var aggregationType = value.toUpperCase();
          var aggregationTypes = new Set(['AVERAGE', 'AVERAGE_SUM_ORG_UNIT', 'COUNT', 'LAST', 'LAST_AVERAGE_ORG_UNIT', 'MIN', 'MAX', 'STDDEV', 'SUM', 'VARIANCE']);

          if (aggregationTypes.has(aggregationType)) {
            this.parameters.aggregationType = aggregationType;
          } else if (aggregationType !== 'DEFAULT') {
            console.warn("d2.analytics.request.withAggregationType(): \"".concat(value, "\" not listed as possible value"));
            this.parameters.aggregationType = value;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the measureCriteria query parameter to the request.
         *
         * @param {!String} measureCriteria The measureCriteria value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withMeasureCriteria('GE:10;LT:50');
         */

      }, {
        key: "withMeasureCriteria",
        value: function withMeasureCriteria(criteria) {
          if (criteria) {
            this.parameters.measureCriteria = criteria;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the preAggregationMeasureCriteria query parameter to the request.
         *
         * @param {!String} preAggregationMeasureCriteria The preAggregationMeasureCriteria value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withPreAggregationMeasureCriteria('GE:10;LT:50');
         */

      }, {
        key: "withPreAggregationMeasureCriteria",
        value: function withPreAggregationMeasureCriteria(criteria) {
          if (criteria) {
            this.parameters.preAggregationMeasureCriteria = criteria;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the skipMeta query parameter to the request.
         *
         * @param {Boolean} [skipMeta=true] The skipMeta value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withSkipMeta();
         */

      }, {
        key: "withSkipMeta",
        value: function withSkipMeta() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.skipMeta = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the skipData query parameter to the request.
         *
         * @param {Boolean} [skipData=true] The skipData value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withSkipData();
         */

      }, {
        key: "withSkipData",
        value: function withSkipData() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.skipData = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the hierarchyMeta query parameter to the request.
         *
         * @param {Boolean} [hierarchyMeta=true] The hierarchyMeta value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withHierarchyMeta();
         */

      }, {
        key: "withHierarchyMeta",
        value: function withHierarchyMeta() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.hierarchyMeta = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the ignoreLimit query parameter to the request.
         *
         * @param {Boolean} [ignoreLimit=true] The ignoreLimit value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withIgnoreLimit();
         */

      }, {
        key: "withIgnoreLimit",
        value: function withIgnoreLimit() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.ignoreLimit = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the tableLayout query parameter to the request.
         *
         * @param {Boolean} [tableLayout=true] The tableLayout value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withTableLayout();
         */

      }, {
        key: "withTableLayout",
        value: function withTableLayout() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.tableLayout = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the hideEmptyRows query parameter to the request.
         *
         * @param {Boolean} [hideEmptyRows=true] The hideEmptyRows value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withHideEmptyRows();
         */

      }, {
        key: "withHideEmptyRows",
        value: function withHideEmptyRows() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.hideEmptyRows = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the hideEmptyColumns query parameter to the request.
         *
         * @param {Boolean} [hideEmptyColumns=true] The hideEmptyColumns value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withHideEmptyColumns();
         */

      }, {
        key: "withHideEmptyColumns",
        value: function withHideEmptyColumns() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.hideEmptyColumns = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the showHierarchy query parameter to the request.
         *
         * @param {Boolean} [showHierarchy=true] The showHierarchy value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withShowHierarchy();
         */

      }, {
        key: "withShowHierarchy",
        value: function withShowHierarchy() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.showHierarchy = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the includeNumDen query parameter to the request.
         *
         * @param {Boolean} [includeNumDen=true] The includeNumDen value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withIncludeNumDen();
         */

      }, {
        key: "withIncludeNumDen",
        value: function withIncludeNumDen() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.includeNumDen = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the includeMetadataDetails query parameter to the request.
         *
         * @param {Boolean} [includeMetadataDetails=true] The includeMetadataDetails value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withIncludeMetadataDetails();
         */

      }, {
        key: "withIncludeMetadataDetails",
        value: function withIncludeMetadataDetails() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.includeMetadataDetails = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the displayProperty query parameter to the request.
         *
         * @param {!String} displayProperty The displayProperty value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withDisplayProperty('SHORTNAME');
         */

      }, {
        key: "withDisplayProperty",
        value: function withDisplayProperty(value) {
          var displayProperty = value.toUpperCase();
          var displayProperties = new Set(['NAME', 'SHORTNAME']);

          if (displayProperties.has(displayProperty)) {
            this.parameters.displayProperty = displayProperty;
          } else {
            console.warn("d2.analytics.request.withDisplayProperty(): \"".concat(value, "\" not listed as possible value"));
            this.parameters.displayProperty = value;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the displayProperty query parameter to the request.
         *
         * @param {!String} displayProperty The displayProperty value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withDisplayProperty('SHORTNAME');
         */

      }, {
        key: "withOutputIdScheme",
        value: function withOutputIdScheme(scheme) {
          if (scheme) {
            this.parameters.outputIdScheme = scheme;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the inputIdScheme query parameter to the request.
         *
         * @param {!String} inputIdScheme The inputIdScheme value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withInputIdScheme('CODE');
         */

      }, {
        key: "withInputIdScheme",
        value: function withInputIdScheme(scheme) {
          if (scheme) {
            this.parameters.inputIdScheme = scheme;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the approvalLevel query parameter to the request.
         *
         * @param {!String} approvalLevel The approvalLevel value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withApprovalLevel('');
         */

      }, {
        key: "withApprovalLevel",
        value: function withApprovalLevel(level) {
          if (level) {
            this.parameters.approvalLevel = level;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the relativePeriodDate query parameter to the request.
         *
         * @param {!String} relativePeriodDate The relativePeriodDate value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withRelativePeriodDate('LAST_12_MONTHS');
         */

      }, {
        key: "withRelativePeriodDate",
        value: function withRelativePeriodDate(date) {
          if (date) {
            this.parameters.relativePeriodDate = date;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the userOrgUnit query parameter to the request.
         *
         * @param {!String} userOrgUnit The userOrgUnit value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withUserOrgUnit('O6uvpzGd5pu');
         */

      }, {
        key: "withUserOrgUnit",
        value: function withUserOrgUnit(orgUnit) {
          if (orgUnit) {
            this.parameters.userOrgUnit = orgUnit;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the columns query parameter to the request.
         *
         * @param {!String} columns The dimensions identifiers (separated by ;)
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withColumns('dx;ou');
         */

      }, {
        key: "withColumns",
        value: function withColumns(dimensions) {
          if (dimensions) {
            this.parameters.columns = dimensions;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the rows query parameter to the request.
         *
         * @param {!String} rows The dimensions identifiers (separated by ;)
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withRows('pe');
         */

      }, {
        key: "withRows",
        value: function withRows(dimensions) {
          if (dimensions) {
            this.parameters.rows = dimensions;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the startDate query parameter to the request.
         *
         * @param {!String} startDate The startDate value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withStartDate('2017-11-28');
         */

      }, {
        key: "withStartDate",
        value: function withStartDate(date) {
          if (date) {
            this.parameters.startDate = date;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the endDate query parameter to the request.
         *
         * @param {!String} endDate The endDate value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withEndDate('2017-12-31');
         */

      }, {
        key: "withEndDate",
        value: function withEndDate(date) {
          if (date) {
            this.parameters.endDate = date;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Sets the program for the request.
         * It appends the program id to the request's path.
         *
         * @param {!String} program The program id
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withProgram('eBAyeGv0exc');
         */

      }, {
        key: "withProgram",
        value: function withProgram(program) {
          if (program) {
            this.program = program;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the stage query parameter to the request.
         *
         * @param {!String} stage The stage value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withStage('Zj7UnCAulEk');
         */

      }, {
        key: "withStage",
        value: function withStage(stage) {
          if (stage) {
            this.parameters.stage = stage;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the eventStatus query parameter to the request.
         *
         * @param {!String} eventStatus The eventStatus value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withEventStatus('COMPLETED');
         */

      }, {
        key: "withEventStatus",
        value: function withEventStatus(value) {
          var eventStatus = value.toUpperCase();
          var eventStatuses = new Set(['ACTIVE', 'COMPLETED', 'SCHEDULED', 'OVERDUE', 'SKIPPED']);

          if (eventStatuses.has(eventStatus)) {
            this.parameters.eventStatus = eventStatus;
          } else {
            console.warn("d2.analytics.request.withEventStatus(): \"".concat(value, "\" not listed as possible value"));
            this.parameters.eventStatus = value;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the programStatus query parameter to the request.
         *
         * @param {!String} programStatus The programStatus value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withProgramStatus('COMPLETED');
         */

      }, {
        key: "withProgramStatus",
        value: function withProgramStatus(value) {
          var programStatus = value.toUpperCase();
          var programStatuses = new Set(['ACTIVE', 'COMPLETED', 'CANCELLED']);

          if (programStatuses.has(programStatus)) {
            this.parameters.programStatus = programStatus;
          } else {
            console.warn("d2.analytics.request.withProgramStatus(): \"".concat(value, "\" not listed as possible value"));
            this.parameters.programStatus = value;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the ouMode query parameter to the request.
         *
         * @param {!String} ouMode The ouMode value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withOuMode('CHILDREN');
         */

      }, {
        key: "withOuMode",
        value: function withOuMode(value) {
          var ouMode = value.toUpperCase();
          var ouModes = new Set(['DESCENDANTS', 'CHILDREN', 'SELECTED']);

          if (ouModes.has(ouMode)) {
            this.parameters.ouMode = ouMode;
          } else {
            console.warn("d2.analytics.request.withOuMode(): \"".concat(value, "\" not listed as possible value"));
            this.parameters.ouMode = value;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the asc query parameter to the request.
         *
         * @param {!String} value The dimensions to be sorted ascending
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withAsc('EVENTDATE');
         */

      }, {
        key: "withAsc",
        value: function withAsc(value) {
          if (value) {
            this.parameters.asc = value;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the desc query parameter to the request.
         *
         * @param {!String} value The dimensions to be sorted descending
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withDesc('OUNAME');
         */

      }, {
        key: "withDesc",
        value: function withDesc(value) {
          if (value) {
            this.parameters.desc = value;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the coordinatesOnly query parameter to the request.
         *
         * @param {Boolean} [coordinatesOnly=true] The coordinatesOnly value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withCoordinatesOnly();
         */

      }, {
        key: "withCoordinatesOnly",
        value: function withCoordinatesOnly() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.coordinatesOnly = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the page query parameter to the request.
         *
         * @param {!Number} [page=1] The page number
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withPage(2);
         */

      }, {
        key: "withPage",
        value: function withPage() {
          var page = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
          this.parameters.page = page;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the pageSize query parameter to the request.
         *
         * @param {!Number} [size=50] The number of items per page
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withPageSize(10);
         */

      }, {
        key: "withPageSize",
        value: function withPageSize() {
          var size = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50;
          this.parameters.pageSize = size;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the value query parameter to the request.
         *
         * @param {!String} value A data element or attribute identifier
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withValue('UXz7xuGCEhU');
         */

      }, {
        key: "withValue",
        value: function withValue(value) {
          // must be a data element or attribute of numeric value type
          if (value) {
            this.parameters.value = value;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the sortOrder query parameter to the request.
         *
         * @param {!String} sortOrder The sortOrder value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withSortOrder('DESC');
         */

      }, {
        key: "withSortOrder",
        value: function withSortOrder(value) {
          var sortOrder = value.toUpperCase();
          var sortOrders = new Set(['ASC', 'DESC']);

          if (sortOrders.has(sortOrder)) {
            this.parameters.sortOrder = sortOrder;
          } else {
            console.warn("d2.analytics.request.withSortOrder(): \"".concat(value, "\" not listed as possible value"));
            this.parameters.sortOrder = value;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the limit query parameter to the request.
         *
         * @param {!Number} limit The maximum number of records to return
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withLimit('5000');
         */

      }, {
        key: "withLimit",
        value: function withLimit(value) {
          if (value) {
            var limit = value > 10000 ? 10000 : value;
            this.parameters.limit = limit;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the outputType query parameter to the request.
         *
         * @param {!String} outputType The output type
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withOutputType('ENROLLMENT');
         */

      }, {
        key: "withOutputType",
        value: function withOutputType(value) {
          var type = value.toUpperCase();
          var outputTypes = new Set(['EVENT', 'ENROLLMENT', 'TRACKED_ENTITY_INSTANCE']);

          if (outputTypes.has(type)) {
            this.parameters.outputType = type;
          } else {
            console.warn("d2.analytics.request.withOutputType(): \"".concat(value, "\" not listed as possible value"));
            this.parameters.outputType = value;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the collapseDataDimensions query parameter to the request.
         *
         * @param {Boolean} [collapseDataDimensions=true] The collapseDataDimensions value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withCollapseDataDimensions();
         */

      }, {
        key: "withCollapseDataDimensions",
        value: function withCollapseDataDimensions() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.collapseDataDimensions = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the skipRounding query parameter to the request.
         *
         * @param {Boolean} [skipRounding=true] The skipRounding value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withSkipRounding();
         */

      }, {
        key: "withSkipRounding",
        value: function withSkipRounding() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.skipRounding = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the aggregateData query parameter to the request.
         *
         * @param {Boolean} [aggregateData=true] The aggregateData value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withAggregateData();
         */

      }, {
        key: "withAggregateData",
        value: function withAggregateData() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.aggregateData = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the clusterSize query parameter to the request.
         *
         * @param {!Number} clusterSize The size of cluster in meters
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withClusterSize(1000);
         */

      }, {
        key: "withClusterSize",
        value: function withClusterSize(size) {
          if (size) {
            this.parameters.clusterSize = size;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the coordinateField query parameter to the request.
         *
         * @param {!String} [coordinateField=EVENT] The field to base geospatial event analytics on
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withCoordinateField('<attribute-id>');
         */

      }, {
        key: "withCoordinateField",
        value: function withCoordinateField() {
          var field = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'EVENT';
          // EVENT, <attribute-id>, <dataelement-id>
          this.parameters.coordinateField = field;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the bbox query parameter to the request.
         *
         * @param {!String} bbox The bounding box coordinates in the format "min lng, min lat, max lng, max lat"
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withBbox('11.1768827285209, 60.141691309755, 11.1694071634997, 60.287796722512');
         */

      }, {
        key: "withBbox",
        value: function withBbox(bbox) {
          if (bbox) {
            this.parameters.bbox = bbox;
          }

          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
        /**
         * Adds the includeClusterPoints query parameter to the request.
         *
         * @param {Boolean} [includeClusterPoints=true] The includeClusterPoints value
         *
         * @returns {AnalyticsRequest} A new instance of the class for chaining purposes
         *
         * @example
         * const req = new d2.analytics.request()
         *    .withIncludeClusterPoints();
         */

      }, {
        key: "withIncludeClusterPoints",
        value: function withIncludeClusterPoints() {
          var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          this.parameters.includeClusterPoints = flag;
          return new _AnalyticsRequest__WEBPACK_IMPORTED_MODULE_0__["default"](this);
        }
      }]);

      return _class;
    }(base)
  );
};

/* harmony default export */ __webpack_exports__["default"] = (AnalyticsRequestPropertiesMixin);

/***/ }),

/***/ "./src/analytics/AnalyticsResponse.js":
/*!********************************************!*\
  !*** ./src/analytics/AnalyticsResponse.js ***!
  \********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _AnalyticsResponseHeader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AnalyticsResponseHeader */ "./src/analytics/AnalyticsResponseHeader.js");
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }


var booleanMap = {
  0: 'No',
  // XXX i18n.no || 'No',
  1: 'Yes' // i18n.yes || 'Yes',

};
var OUNAME = 'ouname';
var OU = 'ou';
var DEFAULT_COLLECT_IGNORE_HEADERS = ['psi', 'ps', 'eventdate', 'longitude', 'latitude', 'ouname', 'oucode', 'eventdate', 'eventdate'];
var DEFAULT_PREFIX_IGNORE_HEADERS = ['dy'].concat(DEFAULT_COLLECT_IGNORE_HEADERS);

var getParseMiddleware = function getParseMiddleware(type) {
  switch (type) {
    case 'STRING':
    case 'TEXT':
      return function (value) {
        return "".concat(value);
      };

    case 'INTEGER':
    case 'NUMBER':
      return function (value) {
        return !Number.isNaN(+value) && Number.isFinite(+value) ? parseFloat(+value) : value;
      };

    default:
      return function (value) {
        return value;
      };
  }
};

var isPrefixHeader = function isPrefixHeader(header, dimensions) {
  if (DEFAULT_PREFIX_IGNORE_HEADERS.includes(header.name)) {
    return false;
  }

  return Boolean(Array.isArray(dimensions) && dimensions.length === 0);
};

var isCollectHeader = function isCollectHeader(header, dimensions) {
  if (DEFAULT_COLLECT_IGNORE_HEADERS.includes(header.name)) {
    return false;
  }

  return Boolean(Array.isArray(dimensions) && dimensions.length === 0);
};

var getPrefixedId = function getPrefixedId(id, prefix) {
  return "".concat(prefix || '', " ").concat(id);
};

var getNameByIdsByValueType = function getNameByIdsByValueType(id, valueType) {
  if (valueType === 'BOOLEAN') {
    return booleanMap[id];
  }

  return id;
};

var AnalyticsResponse =
/*#__PURE__*/
function () {
  function AnalyticsResponse(response) {
    _classCallCheck(this, AnalyticsResponse);

    if (response) {
      this.response = response;
      this.headers = this.extractHeaders();
      this.rows = this.extractRows();
      this.metaData = this.extractMetadata();
    }
  }

  _createClass(AnalyticsResponse, [{
    key: "extractHeaders",
    value: function extractHeaders() {
      var dimensions = this.response.metaData.dimensions;
      var headers = this.response.headers || [];
      return headers.map(function (header, index) {
        return new _AnalyticsResponseHeader__WEBPACK_IMPORTED_MODULE_0__["default"](header, {
          isPrefix: isPrefixHeader(header, dimensions[header.name]),
          isCollect: isCollectHeader(header, dimensions[header.name]),
          index: index
        });
      });
    }
  }, {
    key: "extractRows",
    value: function extractRows() {
      var headersWithOptionSet = this.headers.filter(function (header) {
        return header.optionSet;
      });
      var rows = this.response.rows;

      if (headersWithOptionSet.length) {
        rows = rows.slice();
        var optionCodeIdMap = this.optionCodeIdMap(); // replace option code with option uid

        headersWithOptionSet.forEach(function (header) {
          rows.forEach(function (row, index) {
            var id = optionCodeIdMap[header.name][row[header.index]];

            if (id) {
              rows[index][header.index] = id;
            }
          });
        });
      }

      return rows;
    }
  }, {
    key: "extractMetadata",
    value: function extractMetadata() {
      var _this = this;

      var metaData = _objectSpread({}, this.response.metaData);

      var dimensions = metaData.dimensions,
          items = metaData.items; // populate metaData dimensions and items

      this.headers.filter(function (header) {
        return !DEFAULT_COLLECT_IGNORE_HEADERS.includes(header.name);
      }).forEach(function (header) {
        var ids; // collect row values

        if (header.isCollect) {
          ids = _this.getSortedUniqueRowIdStringsByHeader(header);
          dimensions[header.name] = ids;
        } else {
          ids = dimensions[header.name];
        }

        if (header.isPrefix) {
          // create prefixed dimensions array
          dimensions[header.name] = ids.map(function (id) {
            return getPrefixedId(id, header.name);
          }); // create items

          dimensions[header.name].forEach(function (prefixedId, index) {
            var id = ids[index];
            var valueType = header.valueType;
            var name = getNameByIdsByValueType(id, valueType);
            items[prefixedId] = {
              name: name
            };
          });
        }
      }); // for events, add items from 'ouname'

      if (this.hasHeader(OUNAME) && this.hasHeader(OU)) {
        var ouNameHeaderIndex = this.getHeader(OUNAME).getIndex();
        var ouHeaderIndex = this.getHeader(OU).getIndex();
        var ouId;
        var ouName;
        this.rows.forEach(function (row) {
          ouId = row[ouHeaderIndex];

          if (items[ouId] === undefined) {
            ouName = row[ouNameHeaderIndex];
            items[ouId] = {
              name: ouName
            };
          }
        });
      }

      return metaData;
    }
  }, {
    key: "getHeader",
    value: function getHeader(name) {
      return this.headers.find(function (header) {
        return header.name === name;
      });
    }
  }, {
    key: "hasHeader",
    value: function hasHeader(name) {
      return this.getHeader(name) !== undefined;
    }
  }, {
    key: "getSortedUniqueRowIdStringsByHeader",
    value: function getSortedUniqueRowIdStringsByHeader(header) {
      var parseByType = getParseMiddleware(header.valueType);
      var parseString = getParseMiddleware('STRING');
      var rowIds = Array.from( // unique values
      new Set(this.rows.map(function (responseRow) {
        return parseByType(responseRow[header.index]);
      })) // remove empty values
      ).filter(function (id) {
        return id !== '';
      });
      return rowIds.sort().map(function (id) {
        return parseString(id);
      });
    }
  }, {
    key: "optionCodeIdMap",
    value: function optionCodeIdMap() {
      var _this$response$metaDa = this.response.metaData,
          dimensions = _this$response$metaDa.dimensions,
          items = _this$response$metaDa.items;
      var map = {};
      this.headers.filter(function (header) {
        return typeof header.optionSet === 'string';
      }).forEach(function (header) {
        var optionIds = dimensions[header.name];
        map[header.name] = optionIds.map(function (id) {
          return _defineProperty({}, items[id].code, id);
        }).reduce(function (acc, obj) {
          return Object.assign(acc, obj);
        }, {});
      });
      return map;
    }
  }, {
    key: "sortOrganisationUnitsHierarchy",
    value: function sortOrganisationUnitsHierarchy() {
      var _this2 = this;

      var organisationUnits = this.metaData.dimensions.ou;
      organisationUnits.forEach(function (organisationUnit, i) {
        var hierarchyPrefix = _this2.metaData.ouHierarchy[organisationUnit];
        var hierarchyIds = [organisationUnit];
        var hierarchyNames = [];
        hierarchyPrefix.split('/').reverse().forEach(function (ouId) {
          hierarchyIds.unshift(ouId);
        });
        hierarchyIds.forEach(function (ouId) {
          if (_this2.metaData.items[ouId]) {
            hierarchyNames.push(_this2.metaData.items[ouId].name);
          }
        });
        organisationUnits[i] = {
          id: organisationUnit,
          fullName: hierarchyNames.join(' / ')
        };
      }); // XXX how does this work with different languages/collations?

      organisationUnits.sort(function (a, b) {
        var aFullName = a.fullName;
        var bFullName = b.fullName;

        if (aFullName < bFullName) {
          return -1;
        }

        return aFullName > bFullName ? 1 : 0;
      });
      this.metaData.dimensions.ou = organisationUnits.map(function (ou) {
        return ou.id;
      });
    }
  }]);

  return AnalyticsResponse;
}();

/* harmony default export */ __webpack_exports__["default"] = (AnalyticsResponse);

/***/ }),

/***/ "./src/analytics/AnalyticsResponseHeader.js":
/*!**************************************************!*\
  !*** ./src/analytics/AnalyticsResponseHeader.js ***!
  \**************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

var AnalyticsResponseHeader =
/*#__PURE__*/
function () {
  function AnalyticsResponseHeader() {
    var header = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
      isPrefix: false,
      isCollect: false,
      index: undefined
    };

    _classCallCheck(this, AnalyticsResponseHeader);

    Object.assign(this, header, options);
  }

  _createClass(AnalyticsResponseHeader, [{
    key: "getIndex",
    value: function getIndex() {
      return this.index;
    }
  }, {
    key: "setIndex",
    value: function setIndex(value) {
      var index = +value;

      if (!Number.isNaN(index) && Number.isFinite(index)) {
        this.index = parseInt(index, 10);
      }
    }
  }]);

  return AnalyticsResponseHeader;
}();

/* harmony default export */ __webpack_exports__["default"] = (AnalyticsResponseHeader);

/***/ }),

/***/ "./src/api/Api.js":
/*!************************!*\
  !*** ./src/api/Api.js ***!
  \************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(global, process) {/* harmony import */ var isomorphic_fetch__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! isomorphic-fetch */ "./node_modules/isomorphic-fetch/fetch-npm-browserify.js");
/* harmony import */ var isomorphic_fetch__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(isomorphic_fetch__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../lib/check */ "./src/lib/check.js");
/* harmony import */ var _lib_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../lib/utils */ "./src/lib/utils.js");
/* harmony import */ var _system_System__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../system/System */ "./src/system/System.js");
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

/**
 * @module api
 */





function getMergeStrategyParam() {
  var mergeType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'REPLACE';
  var system = _system_System__WEBPACK_IMPORTED_MODULE_3__["default"].getSystem();

  if (system.version && Number(system.version.minor) <= 22) {
    return "mergeStrategy=".concat(mergeType);
  }

  return "mergeMode=".concat(mergeType);
}

function getUrl(baseUrl, url) {
  // If we are dealing with an absolute url use that instead
  if (new RegExp('^(:?https?:)?//').test(url)) {
    return url;
  }

  var urlParts = [];

  if (baseUrl) {
    urlParts.push(baseUrl);
  }

  urlParts.push(url);
  return urlParts.join('/').replace(new RegExp('(.(?:[^:]))//+', 'g'), '$1/').replace(new RegExp('/$'), '');
}
/**
 * @description
 * Used for interaction with the dhis2 api.
 *
 * This class is used as the backbone for d2 and handles all the interaction with the server. There is a singleton
 * available to be reused across your applications. The singleton can be grabbed from the d2 instance. The api methods all handle URL-encoding for you, so you can just pass them unencoded strings
 *
 * ```js
 * import { getInstance } from 'd2/lib/d2';
 *
 * getInstance()
 *  .then(d2 => {
 *      const api = d2.Api.getApi() // Returns the Api singleton.
 *
 *      api.get('resources');
 *  });
 * ```
 *
 * Uses {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API|Fetch} to do network requests.
 *
 * @memberof module:api
 */


var Api =
/*#__PURE__*/
function () {
  /**
   * @constructor
   *
   * @param {Fetch} [fetchImpl] The fetch implementation to use. Can be used to pass a different implementation
   * similar to the fetch Api. Will default to `window.fetch` in a browser context.
   */
  function Api(fetchImpl) {
    _classCallCheck(this, Api);

    // Optionally provide fetch to the constructor so it can be mocked during testing
    if (typeof fetchImpl === 'function') {
      this.fetch = fetchImpl.bind(typeof window !== 'undefined' ? window : global);
    } else if (typeof fetch !== 'undefined') {
      this.fetch = fetch.bind(typeof window !== 'undefined' ? window : global);
    } else {
      throw new Error('Failed to initialise D2 Api: No fetch implementation is available');
    }

    this.baseUrl = '/api';
    this.defaultFetchOptions = {
      mode: 'cors',
      // requests to different origins fail
      credentials: 'include',
      // include cookies with same-origin requests
      cache: 'default' // See https://fetch.spec.whatwg.org/#concept-request-cache-mode

    };
    this.defaultHeaders = {
      'X-Requested-With': 'XMLHttpRequest'
    };
    this.unauthorizedCallback = null;
  }
  /**
   * Used for setting default headers that should be send with every request.
   *
   * @example
   * const api = Api.getApi();
   *
   * api.setDefaultHeaders({
   *  'x-requested-with': 'XMLHttpRequest', // Make sure the Api does not redirect when authorization is expired.
   * });
   *
   * @param {Object.<string, string>} headers Default headers that should be set on every request.
   */


  _createClass(Api, [{
    key: "setDefaultHeaders",
    value: function setDefaultHeaders(headers) {
      this.defaultHeaders = headers;
    }
    /**
     * When any request encounters a 401 - Unauthorized. This callback is called.
     * Useful for when you want an session expiration-handler API-wide.
     *
     * @param {*} cb - Function to call when any request recieves a 401. Called with the response from the server.
     */

  }, {
    key: "setUnauthorizedCallback",
    value: function setUnauthorizedCallback(cb) {
      if (typeof cb !== 'function') {
        throw new Error('Callback must be a function.');
      }

      this.unauthorizedCallback = cb;
    }
    /**
     * Performs a GET request.
     *
     * @param {string} url The url for the request, should be unencoded. Will return a rejected promise for malformed urls and urls that contain encoded query strings.
     * @param {*} data Any data that should be sent with the request. For a GET request these are encoded and turned into
     * query parameters. For POST and PUT requests it becomes the body.
     * @param {Object.<string, any>} options The request options are passed as options to the fetch request.
     * These options are passed as the {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init}
     * parameter to the fetch request.
     *
     * @returns {Promise.<*>} The response body.
     */

  }, {
    key: "get",
    value: function get(url, data, options) {
      return this.request('GET', getUrl(this.baseUrl, url), data, options);
    }
    /* eslint-disable complexity */

    /**
     * Performs a POST request.
     *
     * @param {string} url The url for the request
     * @param {*} data Any data that should be send with the request this becomes the body for the POST request
     * @param {Object.<string, any>} options The request options are passed as options to the fetch request.
     * These options are passed as the {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init}
     * parameter to the fetch request.
     *
     * @returns {Promise.<*>} The response body.
     */

  }, {
    key: "post",
    value: function post(url, data) {
      var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
      var requestUrl = getUrl(this.baseUrl, url);
      var payload = data; // Ensure that headers are defined and are treated without case sensitivity

      options.headers = new Headers(options.headers || {});

      if (data !== undefined) {
        if (data.constructor.name === 'FormData') {
          // Ensure that the browser will set the correct Content-Type header for FormData, including boundary
          options.headers.delete('Content-Type');
          payload = data;
        } else if (options.headers.has('Content-Type') && options.headers.get('Content-Type').toLocaleLowerCase().startsWith('text/')) {
          payload = String(data);
        } else {
          // Send JSON data by default
          options.headers.set('Content-Type', 'application/json');
          payload = JSON.stringify(data);
        }
      }

      return this.request('POST', requestUrl, payload, options);
    }
    /**
     * Performs a DELETE request.
     *
     * @param {string} url The url for the request
     * @param {Object.<string, any>} options The request options are passed as options to the fetch request.
     * These options are passed as the {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init}
     * parameter to the fetch request.
     *
     * @returns {Promise.<*>} The response body.
     */

    /* eslint-enable complexity */

  }, {
    key: "delete",
    value: function _delete(url, options) {
      return this.request('DELETE', getUrl(this.baseUrl, url), undefined, options);
    }
    /**
     * Perform a PUT request.
     *
     * @param {string} url The url for the request
     * @param {*} data Any data that should be send with the request. This becomes the body of the PUT request.
     * @param {boolean} [useMergeStrategy=false]
     * @param {Object.<string, any>} options The request options are passed as options to the fetch request.
     *
     * @returns {Promise.<*>} The response body.
     */

  }, {
    key: "update",
    value: function update(url, data) {
      var useMergeStrategy = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
      var payload = data; // Ensure that headers are defined and are treated without case sensitivity

      var requestOptions = _objectSpread({}, options, {
        headers: new Headers(options.headers || {})
      });

      if (data !== undefined) {
        if (!requestOptions.headers.has('Content-Type') && typeof payload === 'string') {
          requestOptions.headers.set('Content-Type', 'text/plain');
        } else {
          payload = JSON.stringify(data);
        }
      }

      var urlForUpdate = useMergeStrategy === true ? "".concat(url, "?").concat(getMergeStrategyParam()) : url;
      return this.request('PUT', getUrl(this.baseUrl, urlForUpdate), payload, requestOptions);
    }
    /**
     * Perform a PATCH request.
     *
     * @param {string} url The url for the request
     * @param {*} data Any data that should be send with the request. This becomes the body of the PATCH request.
     *
     * @returns {Promise.<*>} The response body.
     */

  }, {
    key: "patch",
    value: function patch(url, data) {
      return this.request('PATCH', getUrl(this.baseUrl, url), JSON.stringify(data));
    }
    /**
     * General purpose request function for making http requests.
     *
     * The more specific functions like `delete`, `post` and `get`, utilize this function to make the requests.
     *
     * @param {string} method The HTTP request method (e.g. POST/GET/PATCH)
     * @param {string} url The url for the request
     * @param {*} data Any data that should be send with the request. For a GET request these are turned into
     * query parameters. For POST and PUT requests it becomes the body.
     * @param {Object.<string, any>} options The request options are passed as options to the fetch request.
     * These options are passed as the {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init}
     * parameter to the fetch request.
     *
     * @returns {Promise.<*>} The response body.
     */

    /* eslint-disable complexity */

  }, {
    key: "request",
    value: function request(method, url, data) {
      var _this = this;

      var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
      Object(_lib_check__WEBPACK_IMPORTED_MODULE_1__["checkType"])(method, 'string', 'Request type');
      Object(_lib_check__WEBPACK_IMPORTED_MODULE_1__["checkType"])(url, 'string', 'Url');
      var api = this;
      var requestUrl = url;
      var query = '';

      if (requestUrl.indexOf('?') !== -1) {
        query = requestUrl.substr(requestUrl.indexOf('?') + 1);
        requestUrl = requestUrl.substr(0, requestUrl.indexOf('?'));
      } // Encode existing query parameters, since tomcat does not accept unencoded brackets. Throw
      // an error if they're already encoded to prevent double encoding.


      if (query) {
        var decodedURL;

        try {
          decodedURL = decodeURIComponent(query);
        } catch (err) {
          return Promise.reject(new Error('Query parameters in URL are invalid'));
        }

        var isEncoded = query !== decodedURL;

        if (isEncoded) {
          return Promise.reject(new Error('Cannot process URL-encoded URLs, pass an unencoded URL'));
        }

        query = Object(_lib_utils__WEBPACK_IMPORTED_MODULE_2__["customEncodeURIComponent"])(query);
      } // Transfer filter properties from the data object to the query string


      if (data && Array.isArray(data.filter)) {
        var encodedFilters = data.filter.map(function (filter) {
          return filter.split(':').map(encodeURIComponent).join(':');
        });
        query = "".concat(query).concat(query.length ? '&' : '', "filter=").concat(encodedFilters.join('&filter='));
        delete data.filter;
      } // When using the GET method, transform the data object to query parameters


      if (data && method === 'GET') {
        Object.keys(data).forEach(function (key) {
          query = "".concat(query).concat(query.length > 0 ? '&' : '') + "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(data[key]));
        });
      }

      function getOptions(defaultHeaders, mergeOptions, requestData) {
        var resultOptions = Object.assign({}, api.defaultFetchOptions, mergeOptions);
        var headers = new Headers(mergeOptions.headers || {});
        Object.keys(defaultHeaders).filter(function (header) {
          return !headers.get(header);
        }).forEach(function (header) {
          return headers.set(header, defaultHeaders[header]);
        });
        resultOptions.method = method; // Only set content type when there is data to send
        // GET requests and requests without data do not need a Content-Type header
        // 0 and false are valid requestData values and therefore should have a content type

        if (resultOptions.method === 'GET' || !requestData && requestData !== 0 && requestData !== false) {
          headers.delete('Content-Type');
        } else if (requestData) {
          if (data.constructor.name === 'FormData') {
            headers.delete('Content-Type');
          } else if (!headers.get('Content-Type')) {
            headers.set('Content-Type', 'application/json');
          }

          resultOptions.body = requestData;
        }

        resultOptions.headers = headers;
        return resultOptions;
      }

      if (query.length) {
        requestUrl = "".concat(requestUrl, "?").concat(query);
      }

      var requestOptions = getOptions(this.defaultHeaders, options, data); // If the provided value is valid JSON, return the parsed JSON object. If not, return the raw value as is.

      function parseResponseData(value) {
        try {
          return JSON.parse(value);
        } catch (e) {
          return value;
        }
      }

      return new Promise(function (resolve, reject) {
        // fetch returns a promise that will resolve with any response received from the server
        // It will be rejected ONLY if no response is received from the server, i.e. because there's no internet
        _this.fetch(requestUrl, requestOptions).then(function (response) {
          // If the request failed, response.ok will be false and response.status will be the status code
          if (response.ok) {
            response.text().then(function (text) {
              return resolve(parseResponseData(text));
            });
          } else {
            response.text().then(function (text) {
              var parsedResponseData = parseResponseData(text);

              if (response.status === 401) {
                var request = {
                  method: method,
                  url: url,
                  data: data,
                  options: options
                };

                if (_this.unauthorizedCallback) {
                  _this.unauthorizedCallback(request, parsedResponseData);
                }
              }

              if (!process.env || process.env.npm_lifecycle_event !== 'test') {
                // eslint-disable-next-line
                console.warn("API request failed with status ".concat(response.status, " ").concat(response.statusText, "\n"), "Request: ".concat(requestOptions.method, " ").concat(requestUrl));
              }

              reject(parsedResponseData);
            });
          }
        }).catch(function (err) {
          // It's not usually possible to get much info about the cause of the error programmatically, but
          // the user can check the browser console for more info
          if (!process.env || process.env.npm_lifecycle_event !== 'test') {
            console.error('Server connection error:', err); // eslint-disable-line
          }

          reject("Server connection failed for API request: ".concat(requestOptions.method, " ").concat(requestUrl));
        });
      });
    }
    /* eslint-enable complexity */

    /**
     * Sets the baseUrl that should be used for the api.
     *
     * When working against the dhis2 demo instance at {@link https://play.dhis2.org/demo} the
     * baseUrl would be set as `https://play.dhis2.org/demo/api`.
     *
     * This method is used when calling the `d2.init` method with the `baseUrl` config property
     * to configure the Api singleton.
     *
     * @param {string} baseUrl The base url to be used for the API.
     *
     * @returns {this} Itself for chaining purposes
     */

  }, {
    key: "setBaseUrl",
    value: function setBaseUrl(baseUrl) {
      Object(_lib_check__WEBPACK_IMPORTED_MODULE_1__["checkType"])(baseUrl, 'string', 'Base url');
      this.baseUrl = baseUrl;
      return this;
    }
  }]);

  return Api;
}();
/**
 * Retrieve the Api singleton or create one.
 *
 * When called for the first time it creates and Api singleton object.
 * Any subsequent calls will return the previously created singleton.
 *
 * @returns {Api} The Api singleton.
 * @memberof module:api~Api
 */


function getApi() {
  if (getApi.api) {
    return getApi.api;
  }

  return getApi.api = new Api();
}

Api.getApi = getApi;
/* harmony default export */ __webpack_exports__["default"] = (Api);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"), __webpack_require__(/*! ./../../node_modules/process/browser.js */ "./node_modules/process/browser.js")))

/***/ }),

/***/ "./src/config.js":
/*!***********************!*\
  !*** ./src/config.js ***!
  \***********************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Config; });
/* harmony import */ var _defaultConfig__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./defaultConfig */ "./src/defaultConfig.js");
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./lib/check */ "./src/lib/check.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }




var Config =
/*#__PURE__*/
function () {
  function Config() {
    _classCallCheck(this, Config);
  }

  _createClass(Config, null, [{
    key: "create",
    value: function create() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      var configObjects = args.filter(function (arg) {
        return arg;
      });

      if (!configObjects.every(function (configObject) {
        return Object(_lib_check__WEBPACK_IMPORTED_MODULE_1__["isType"])(configObject, 'object');
      })) {
        throw new Error('Expected Config parameter to have type object');
      }

      return Object.assign.apply(Object, [{}, _defaultConfig__WEBPACK_IMPORTED_MODULE_0__["default"]].concat(args));
    }
  }, {
    key: "processPreInitConfig",
    value: function processPreInitConfig(preinitConfig, api) {
      if (preinitConfig.headers) {
        api.setDefaultHeaders(preinitConfig.headers);
      }

      if (preinitConfig.baseUrl) {
        api.setBaseUrl(preinitConfig.baseUrl);
      }
    } // eslint-disable-next-line complexity

  }, {
    key: "processConfigForD2",
    value: function processConfigForD2(config, d2) {
      var api = d2.Api.getApi();
      d2.model.ModelDefinition.prototype.api = api;
      d2.models = d2.model.ModelDefinitions.getModelDefinitions();

      if (Object(_lib_check__WEBPACK_IMPORTED_MODULE_1__["isString"])(config.baseUrl)) {
        api.setBaseUrl(config.baseUrl);
      } else {
        // default to the current version of the `/api`
        api.setBaseUrl('/api');
      }

      if (config.headers) {
        api.setDefaultHeaders(config.headers);
      }

      if (config.unauthorizedCb) {
        api.setUnauthorizedCallback(config.unauthorizedCb);
      }

      if (config.i18n && config.i18n.sources) {
        Array.from(config.i18n.sources).forEach(function (source) {
          return d2.i18n.addSource(source);
        });
      }

      if (config.i18n && config.i18n.strings) {
        d2.i18n.addStrings(Array.from(config.i18n.strings));
      }
    }
  }]);

  return Config;
}();



/***/ }),

/***/ "./src/current-user/CurrentUser.js":
/*!*****************************************!*\
  !*** ./src/current-user/CurrentUser.js ***!
  \*****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _UserAuthorities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./UserAuthorities */ "./src/current-user/UserAuthorities.js");
/* harmony import */ var _UserSettings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./UserSettings */ "./src/current-user/UserSettings.js");
/* harmony import */ var _defaultConfig__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../defaultConfig */ "./src/defaultConfig.js");
/* harmony import */ var _datastore_UserDataStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../datastore/UserDataStore */ "./src/datastore/UserDataStore.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

/**
 * @module current-user
 */




var models = Symbol('models');
var propertiesToIgnore = new Set(['userCredentials', 'userGroups', 'userRoles', 'organisationUnits', 'dataViewOrganisationUnits']);
/**
 * Authorities lookup map to be used for determining the list of authorities to check.
 *
 * @private
 * @type {Object.<string, string[]>}
 * @readonly
 * @typedef {Object} AuthorityType
 * @memberof module:current-user
 */

var authTypes = {
  READ: ['READ'],
  CREATE: ['CREATE', 'CREATE_PUBLIC', 'CREATE_PRIVATE'],
  CREATE_PUBLIC: ['CREATE_PUBLIC'],
  CREATE_PRIVATE: ['CREATE_PRIVATE'],
  DELETE: ['DELETE'],
  UPDATE: ['UPDATE'],
  EXTERNALIZE: ['EXTERNALIZE']
  /**
   * Create a map of `propertyName` -> `Symbol`. This map is used to hide values for these properties. We will instead add
   * add convenience methods for these properties. (e.g. the `userGroups` property on the currentUser object becomes
   * `getUserGroups()`
   *
   * @private
   * @type {Object.<string, Symbol>}
   */

};
var propertySymbols = Array.from(propertiesToIgnore).reduce(function (result, property) {
  result[property] = Symbol(property);
  return result;
}, {});
/**
 * Creates a map of propertyName and propertyValue pairs of properties to be attached to the currentUser object.
 * These are all the regular properties that are returned when calling `api/27/me` but with the `userCredentials`
 * merged onto the same object.
 *
 * What would originally be `currentUser.userCredentials.username` would just be `currentUser.username`
 *
 * @private
 * @param {Object} currentUserObject The user payload as it is received from the api. https://play.dhis2.org/demo/api/27/me
 * @returns {Object} A map with propertyName/propertyValue pairs.
 */

function getPropertiesForCurrentUserObject(currentUserObject) {
  var properties; // The userCredentials object on the userObject is confusing so we set the properties straight onto the currentUser
  // object itself

  if (currentUserObject.userCredentials) {
    properties = Object.assign({}, currentUserObject.userCredentials, currentUserObject);
  } else {
    properties = Object.assign({}, currentUserObject);
  }

  return Object.keys(properties).reduce(function (result, property) {
    if (propertiesToIgnore.has(property)) {
      if (properties[property].map) {
        result[propertySymbols[property]] = properties[property].map(function (value) {
          return value.id;
        });
      }
    } else {
      result[property] = properties[property];
    }

    return result;
  }, {});
}
/**
 * Checks the noCreateAllowedFor list if the object can be created.
 *
 * @private
 * @param {ModelDefinition} modelDefinition The modelDefinition to check for.
 * @returns {boolean} True when it exists in the list, false otherwise.
 */


function isInNoCreateAllowedForList(modelDefinition) {
  return Boolean(modelDefinition && _defaultConfig__WEBPACK_IMPORTED_MODULE_2__["noCreateAllowedFor"].has(modelDefinition.name));
}
/**
 * Represents the current logged in user
 *
 * @memberof module:current-user
 */


var CurrentUser =
/*#__PURE__*/
function () {
  /**
   * Creates the CurrentUser.
   *
   * @param {Object} userData Payload as returned from the api when requesting the currentUser object.
   * @param {UserAuthorities} userAuthorities The UserAuthorities object for the currentUsers authorities.
   * @param {ModelDefinition[]} modelDefinitions The modelDefinitions that need to be used for checking access.
   * @param {UserSettings} settings The userSettings object to be set onto the current user object.
   */
  function CurrentUser(userData, userAuthorities, modelDefinitions, settings) {
    _classCallCheck(this, CurrentUser);

    Object.assign(this, getPropertiesForCurrentUserObject(userData));
    /**
     *
     * @type {UserAuthorities}
     */

    this.authorities = userAuthorities;
    this[models] = modelDefinitions;
    /**
     * Contains a reference to a `UserSettings` instance that can be used
     * to retrieve and save system settings.
     * @type {UserSettings}
     * @description
     * ```js
     * d2.currentUser.userSettings.get('keyUiLocale')
     *  .then(userSettingsValue => {
     *    console.log('UI Locale: ' + userSettingsValue);
     *  });
     * ```
     */

    this.userSettings = settings;
    /**
     * Contains a reference to {@link module:current-user.UserDataStore UserDataStore}
     * @type UserDataStore
     *
     */

    this.dataStore = _datastore_UserDataStore__WEBPACK_IMPORTED_MODULE_3__["default"].getUserDataStore();
  }
  /**
   * Get a list of group ids the current user belongs to.
   *
   * @returns {Array} The list of ids of all the user's groups.
   */


  _createClass(CurrentUser, [{
    key: "getUserGroupIds",
    value: function getUserGroupIds() {
      return this[propertySymbols.userGroups];
    }
    /**
     * Get a ModelCollection of userGroup models that are assigned to the currentUser
     *
     * The user groups are lazy loaded on init of the library. This method can be used to load the full representation
     * of the userGroups.
     *
     * The request done is equivalent do doing https://play.dhis2.org/demo/api/27/me.json?fields=userGroups[:all]
     *
     * @param {Object} [listOptions={}] Additional query parameters that should be send with the request.
     * @returns {Promise<ModelCollection>} The model collection that contains the user's groups.
     */

  }, {
    key: "getUserGroups",
    value: function getUserGroups() {
      var listOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var userGroupIds = this[propertySymbols.userGroups];
      return this[models].userGroup.list(Object.assign({
        paging: false
      }, listOptions, {
        filter: ["id:in:[".concat(userGroupIds.join(','), "]")]
      }));
    }
    /**
     * Get a ModelCollection of userRole models that are assigned to the currentUser
     *
     * The user roles are lazy loaded on init of the library. This method can be used to load the full representation
     * of the userGroups.
     *
     * The request done is equivalent do doing https://play.dhis2.org/demo/api/27/me.json?fields=userCredentials[userRoles[:all]]
     *
     * @returns {Promise<ModelCollection>} A ModelCollection that contains the user's groups.
     */

  }, {
    key: "getUserRoles",
    value: function getUserRoles() {
      var userRoleIds = this[propertySymbols.userRoles];
      return this[models].userRole.list({
        filter: ["id:in:[".concat(userRoleIds.join(','), "]")],
        paging: false
      });
    }
    /**
     * Requests a users primary organisation units from the api.
     *
     * The users organisation units are lazy loaded on init of the library (just the ids). This method can be used to
     * load the full representation of the organisationUnits.
     *
     * @param {Object} [listOptions={}] Additional query parameters that should be send with the request.
     * @returns {Promise<ModelCollection>} A ModelCollection that contains the user's organisationUnits.
     */

  }, {
    key: "getOrganisationUnits",
    value: function getOrganisationUnits() {
      var listOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var organisationUnitsIds = this[propertySymbols.organisationUnits];
      return this[models].organisationUnit.list(Object.assign({
        fields: ':all,displayName,path,children[id,displayName,path,children::isNotEmpty]',
        paging: false
      }, listOptions, {
        filter: ["id:in:[".concat(organisationUnitsIds.join(','), "]")]
      }));
    }
    /**
     * Requests a users data view organisation units from the api.
     *
     * The users data view organisation units are lazy loaded on init of the library (just the ids). This method can
     * be used to load the full representation of the dataViewOrganisationUnits.
     *
     * @param {Object} [listOptions={}] Additional query parameters that should be send with the request.
     * @returns {Promise<ModelCollection>} A ModelCollection that contains the user's dataViewOrganisationUnits.
     */

  }, {
    key: "getDataViewOrganisationUnits",
    value: function getDataViewOrganisationUnits(listOptions) {
      var organisationUnitsIds = this[propertySymbols.dataViewOrganisationUnits];
      return this[models].organisationUnit.list(Object.assign({
        fields: ':all,displayName,path,children[id,displayName,path,children::isNotEmpty]',
        paging: false
      }, listOptions, {
        filter: ["id:in:[".concat(organisationUnitsIds.join(','), "]")]
      }));
    }
    /**
     * Helper function to check if the currentUser can perform an action.
     *
     * A schema from the api defines the authorities as follows:
     * "authorities": [
     *   {
     *     "type": "CREATE_PUBLIC",
     *     "authorities": [
     *       "F_DATAELEMENT_PUBLIC_ADD"
     *     ]
     *   }, {
     *      "type": "CREATE_PRIVATE",
     *      "authorities": [
     *        "F_DATAELEMENT_PRIVATE_ADD"
     *      ]
     *    }, {
     *      "type": "DELETE",
     *      "authorities": [
     *        "F_DATAELEMENT_DELETE"
     *      ]
     *    }
     *
     * ],
     *
     * So for example, when asking for `currentUser.canCreate(modelDefinition)` we look at the authorities map for CREATE, we
     * collect the authorities from the schema based on the values of `CREATE`. So in the case of above schema authorities
     * we take the authorities for 'CREATE_PUBLIC' and 'CREATE_PRIVATE' and check if the user has at least one of the
     * authorities in the combined list. If we had asked for `currentUser.canCreatePrivate(modelDefinition)` we would only
     * need to check if the user has `F_DATAELEMENT_PRIVATE_ADD` However for just create the user could still create when he
     * has either private or public.
     *
     * @private
     * @param {AuthorityType} authorityType The type of authority to check for.
     * @param {ModelDefinition} modelDefinition The ModelDefinition for the type of object that the authority should
     * be checked for.
     * @returns {boolean} True when the user has the authority to perform the action, otherwise false.
     */

  }, {
    key: "checkAuthorityForType",
    value: function checkAuthorityForType(authorityType, modelDefinition) {
      var _this = this;

      if (!modelDefinition || !Array.isArray(modelDefinition.authorities)) {
        return false;
      }

      return modelDefinition.authorities // Filter the correct authority to check for from the model
      .filter(function (authority) {
        return authorityType.some(function (authToHave) {
          return authToHave === authority.type;
        });
      }) // Check the left over schema authority types
      .some(function (schemaAuthority) {
        return schemaAuthority.authorities.some(function (authorityToCheckFor) {
          return _this.authorities.has(authorityToCheckFor);
        });
      } // Check if one of the schema authorities are available in the users authorities
      );
    }
    /**
     * Helper method to first check the special "not allowed to create list" before checking the users authorities.
     *
     * @private
     * @param {AuthorityType} authType The type of authority that should be checked. (CREATE, CREATE_PRIVATE
     * or CREATE_PUBLIC)
     * @param {ModelDefinition} modelDefinition The modelDefinition that the authorities should be checked for.
     * @returns {boolean} True when the user has the permission to create the object
     */

  }, {
    key: "checkCreateAuthorityForType",
    value: function checkCreateAuthorityForType(authType, modelDefinition) {
      // When the modelDefinition is mentioned in the the list of modelTypes that are not
      // allowed to be created we return false
      if (isInNoCreateAllowedForList(modelDefinition)) {
        return false;
      } // Otherwise we check using the normal procedure for checking authorities


      return this.checkAuthorityForType(authType, modelDefinition);
    }
    /**
     * Check if the user has the authority to create objects of a type of Model (based on it's modelDefinition)
     * If the object supports public and private objects then both are checked, and the method will return true if one
     * of them is true. (e.g. will also return true if the user can only create private objects)
     *
     * @param {ModelDefinition} modelDefinition The modelDefinition that the authorities should be checked for.
     * @returns {boolean} True when the user has the permission to create the object
     */

  }, {
    key: "canCreate",
    value: function canCreate(modelDefinition) {
      return this.checkCreateAuthorityForType(authTypes.CREATE, modelDefinition);
    }
    /**
     * Check if the user has the authority to create public objects of a type of Model (based on it's modelDefinition)
     *
     * @param {ModelDefinition} modelDefinition The modelDefinition that the authorities should be checked for.
     * @returns {boolean} True when the user has the permission to create the object
     */

  }, {
    key: "canCreatePublic",
    value: function canCreatePublic(modelDefinition) {
      return this.checkCreateAuthorityForType(authTypes.CREATE_PUBLIC, modelDefinition);
    }
    /**
     * Check if the user has the authority to create private objects of a type of Model (based on it's modelDefinition)
     *
     * @param {ModelDefinition} modelDefinition The modelDefinition that the authorities should be checked for.
     * @returns {boolean} True when the user has the permission to create the object
     */

  }, {
    key: "canCreatePrivate",
    value: function canCreatePrivate(modelDefinition) {
      return this.checkCreateAuthorityForType(authTypes.CREATE_PRIVATE, modelDefinition);
    }
    /**
     * Check if the user has the authority to delete objects of a type of Model (based on it's modelDefinition)
     *
     * @param {ModelDefinition} modelDefinition The modelDefinition that the authorities should be checked for.
     * @returns {boolean} True when the user has the permission to delete the object
     *
     * @deprecated Delete should be checked through the `Model.access.delete` property instead, as that also takes into
     * account sharing. Just checking if the user has the authority to delete a specific object does not take into account
     * the full ACL.
     */

  }, {
    key: "canDelete",
    value: function canDelete(modelDefinition) {
      return this.checkAuthorityForType(authTypes.DELETE, modelDefinition);
    }
    /**
     * Check if the user has the authority to update objects of a type of Model (based on it's modelDefinition)
     *
     * @param {ModelDefinition} modelDefinition The modelDefinition that the authorities should be checked for.
     * @returns {boolean} True when the user has the permission to update the object
     *
     * @deprecated Update should be checked through the `Model.access.update` property instead, as that also takes into
     * account sharing. Just checking if the user has the authority to update a specific object does not take into account
     * the full ACL.
     */

  }, {
    key: "canUpdate",
    value: function canUpdate(modelDefinition) {
      if (this.checkAuthorityForType(authTypes.UPDATE, modelDefinition)) {
        return true;
      }

      return this.checkAuthorityForType(authTypes.CREATE, modelDefinition);
    }
    /**
     * Factory method for creating a CurrentUser instance
     *
     * @param {Object} userData Payload as returned from the api when requesting the currentUser object.
     * @param {string[]} authorities A list of authorities that the currentUser has.
     * @param {ModelDefinition[]} modelDefinitions The modelDefinitions that need to be used for checking access.
     * @param {Object} userSettings Payload as returned from the api when request the userSettings
     * @returns {CurrentUser} The created CurrentUser object based on the data given.
     */

  }], [{
    key: "create",
    value: function create(userData, authorities, modelDefinitions, userSettings) {
      return new CurrentUser(userData, _UserAuthorities__WEBPACK_IMPORTED_MODULE_0__["default"].create(authorities), modelDefinitions, new _UserSettings__WEBPACK_IMPORTED_MODULE_1__["default"](userSettings));
    }
  }]);

  return CurrentUser;
}();

/* harmony default export */ __webpack_exports__["default"] = (CurrentUser);

/***/ }),

/***/ "./src/current-user/UserAuthorities.js":
/*!*********************************************!*\
  !*** ./src/current-user/UserAuthorities.js ***!
  \*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

var auths = Symbol('authorities');
/**
 * Simple wrapper class for the user authorities list
 *
 * @memberof module:current-user
 */

var UserAuthorities =
/*#__PURE__*/
function () {
  /**
   * Creates the UserAuthorities object based off the given set of the user's authorities.
   *
   * @param {string[]} authorities A set of the user's authorities.
   */
  function UserAuthorities() {
    var authorities = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

    _classCallCheck(this, UserAuthorities);

    this[auths] = new Set(authorities);
  }
  /**
   * Checks if the given authority is in the user's authority list.
   *
   * If the user has the 'ALL' authority any request for a authority will return `true`.
   *
   * @param {string} authority The authority to check for
   */


  _createClass(UserAuthorities, [{
    key: "has",
    value: function has(authority) {
      if (this[auths].has('ALL')) {
        return true;
      }

      return this[auths].has(authority);
    }
    /**
     * Factory method for a UserAuthorities instance
     *
     * @param {string[]} authorities A set of the user's authorities as recieved from the api.
     */

  }], [{
    key: "create",
    value: function create(authorities) {
      return new UserAuthorities(authorities);
    }
  }]);

  return UserAuthorities;
}();

/* harmony default export */ __webpack_exports__["default"] = (UserAuthorities);

/***/ }),

/***/ "./src/current-user/UserSettings.js":
/*!******************************************!*\
  !*** ./src/current-user/UserSettings.js ***!
  \******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../lib/check */ "./src/lib/check.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }



/**
 * @description
 * Handles communication with the userSettings endpoint. Can be used to get or save userSettings.
 *
 * @memberof module:current-user
 */

var UserSettings =
/*#__PURE__*/
function () {
  function UserSettings(userSettings) {
    var api = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi();

    _classCallCheck(this, UserSettings);

    this.api = api;

    if (userSettings) {
      this.settings = userSettings;
    }
  }
  /**
   * @returns {Promise} Promise that resolves with the usersettings object from the api.
   *
   * @description
   * Loads all the user settings of current user and returns them as an object from the promise.
   * ```js
   * d2.currentUser.userSettings.all()
   *  .then(userSettings => {
   *    console.log('UI Locale: ' + userSettings.keyUiLocale);
   *  });
   * ```
   */


  _createClass(UserSettings, [{
    key: "all",
    value: function all() {
      var _this = this;

      return this.settings ? Promise.resolve(this.settings) : this.api.get('userSettings').then(function (userSettings) {
        _this.settings = userSettings;
        return Promise.resolve(_this.settings);
      });
    }
    /**
     * @param {String} key The identifier of the user setting that should be retrieved.
     * @returns {Promise} A promise that resolves with the value or will fail if the value is not available.
     *
     * @description
     * ```js
     * d2.currentUser.userSettings.get('keyUiLocale')
     *  .then(userSettingValue => {
     *    console.log('UI Locale: ' + userSettingValue);
     *  });
     * ```
     */

  }, {
    key: "get",
    value: function get(key) {
      var _this2 = this;

      if (this.settings && this.settings[key]) {
        return Promise.resolve(this.settings[key]);
      }

      function processValue(value) {
        // Attempt to parse the response as JSON. If this fails we return the value as is.
        try {
          return JSON.parse(value);
        } catch (e) {
          return value;
        }
      }

      return new Promise(function (resolve, reject) {
        if (!Object(_lib_check__WEBPACK_IMPORTED_MODULE_1__["isString"])(key)) {
          throw new TypeError('A "key" parameter should be specified when calling get() on userSettings');
        }

        _this2.api.get(['userSettings', key].join('/')).then(function (response) {
          var value = processValue(response); // Store the value on the user settings object

          _this2[key] = value;

          if (value) {
            resolve(value);
          }

          reject(new Error('The requested userSetting has no value or does not exist.'));
        });
      });
    }
    /**
     * @param {String} key The identifier of the user setting that should be saved.
     * @param {String} value The new value of the user setting.
     * @returns {Promise} A promise that will resolve when the new value has been saved, or fail if saving fails.
     *
     * @description
     * ```js
     * d2.currentUser.userSettings.set('keyUiLocale', 'fr')
     *  .then(() => {
     *   console.log('UI Locale is now "fr");
     *  });
     * ```
     */

  }, {
    key: "set",
    value: function set(key, value) {
      delete this.settings;
      var settingUrl = ['userSettings', key].join('/');

      if (value === null || "".concat(value).length === 0) {
        return this.api.delete(settingUrl);
      }

      return this.api.post(settingUrl, value, {
        headers: {
          'Content-Type': 'text/plain'
        }
      });
    }
  }]);

  return UserSettings;
}();

/* harmony default export */ __webpack_exports__["default"] = (UserSettings);

/***/ }),

/***/ "./src/d2.js":
/*!*******************!*\
  !*** ./src/d2.js ***!
  \*******************/
/*! exports provided: getManifest, getUserSettings, init, getInstance, setInstance, config */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getManifest", function() { return getManifest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getUserSettings", function() { return getUserSettings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "init", function() { return init; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getInstance", function() { return getInstance; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setInstance", function() { return setInstance; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "config", function() { return config; });
/* harmony import */ var isomorphic_fetch__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! isomorphic-fetch */ "./node_modules/isomorphic-fetch/fetch-npm-browserify.js");
/* harmony import */ var isomorphic_fetch__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(isomorphic_fetch__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _lib_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./lib/utils */ "./src/lib/utils.js");
/* harmony import */ var _logger_Logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./logger/Logger */ "./src/logger/Logger.js");
/* harmony import */ var _model__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./model */ "./src/model/index.js");
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./api/Api */ "./src/api/Api.js");
/* harmony import */ var _system_System__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./system/System */ "./src/system/System.js");
/* harmony import */ var _i18n_I18n__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./i18n/I18n */ "./src/i18n/I18n.js");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./config */ "./src/config.js");
/* harmony import */ var _current_user_CurrentUser__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./current-user/CurrentUser */ "./src/current-user/CurrentUser.js");
/* harmony import */ var _model_config__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./model/config */ "./src/model/config/index.js");
/* harmony import */ var _datastore_DataStore__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./datastore/DataStore */ "./src/datastore/DataStore.js");
/* harmony import */ var _analytics_Analytics__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./analytics/Analytics */ "./src/analytics/Analytics.js");
/* harmony import */ var _geofeatures_GeoFeatures__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./geofeatures/GeoFeatures */ "./src/geofeatures/GeoFeatures.js");
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

/**
 * @module d2
 *
 * @description
 * Module that contains the entry points for working with the d2 instance. Most of the api related functionality will be available through this package.
 *
 * The most important functions from the module are {@link module:d2.init|init} and {@link module:d2.init|getInstance} these are used to create and to get
 * a hold of the initialized instance of {@link module:d2.init~d2|d2}. The initialized instance is the object that allows you access most of d2's functionality.
 *
 * @example
 * import { init } from 'd2/lib/d2';
 *
 * init({ baseUrl: 'https://play.dhis2.org/demo/api/27/' })
 *  .then(d2 => console.log(d2.currentUser.name));
 */













var firstRun = true;
var deferredD2Init = _lib_utils__WEBPACK_IMPORTED_MODULE_1__["Deferred"].create();
var preInitConfig = _config__WEBPACK_IMPORTED_MODULE_7__["default"].create();
/**
 * Utility function to load the app manifest.
 *
 * The manifest well be enhanced with a `getBaseUrl()` utility function that will return the base url of the DHIS2 instance.
 * This is a simple getter for the `activities.dhis.href` property on the manifest.
 *
 * @example
 * import { getManifest } from 'd2/lib/d2';
 *
 * getManifest()
 *   .then(manifest => {
 *      console.log(manifest.getBaseUrl());
 *   });
 *
 * @param {string} url The location of the manifest. Generally this is located in the root of your app folder. (e.g. './manifest.webapp)
 * @param {Api} [ApiClass] An implementation of the Api class that will be used to fetch the manifest.
 *
 * @returns {Promise} Returns a Promise to  the DHIS2 app manifest with the added `getBaseUrl` method.
 */

function getManifest(url) {
  var ApiClass = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _api_Api__WEBPACK_IMPORTED_MODULE_4__["default"];
  var api = ApiClass.getApi();
  api.setBaseUrl('');
  var manifestUtilities = {
    getBaseUrl: function getBaseUrl() {
      return this.activities.dhis.href;
    }
  };
  return api.get("".concat(url)).then(function (manifest) {
    return Object.assign({}, manifest, manifestUtilities);
  });
}
/**
 * @function getUserSettings
 *
 * @returns {Promise} A promise to the current user settings
 *
 * @description
 * The object that is the result of the promise will have the following properties
 *
 * @example
 * import {getUserSettings} from 'd2/lib/d2';
 *
 * getUserSettings()
 *  .then(userSettings => {
 *      console.log(userSettings);
 *  });
 */

function getUserSettings() {
  var ApiClass = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _api_Api__WEBPACK_IMPORTED_MODULE_4__["default"];
  var api = ApiClass.getApi();

  if (firstRun) {
    _config__WEBPACK_IMPORTED_MODULE_7__["default"].processPreInitConfig(preInitConfig, api);
  }

  return api.get('userSettings');
}

function getModelRequests(api, schemaNames) {
  var modelRequests = [];

  var loadSchemaForName = function loadSchemaForName(schemaName) {
    return api.get("schemas/".concat(schemaName), {
      fields: _model_config__WEBPACK_IMPORTED_MODULE_9__["fieldsForSchemas"]
    });
  };

  if (Array.isArray(schemaNames)) {
    var individualSchemaRequests = schemaNames.map(loadSchemaForName).concat([]);
    var schemasPromise = Promise.all(individualSchemaRequests).then(function (schemas) {
      return {
        schemas: schemas
      };
    });
    modelRequests.push(schemasPromise);

    if (schemaNames.length > 0) {
      // If schemas are loaded, attributes should be as well
      modelRequests.push(api.get('attributes', {
        fields: ':all,optionSet[:all,options[:all]]',
        paging: false
      }));
    } else {
      // Otherwise, just return an empty list of attributes
      modelRequests.push({
        attributes: []
      });
    }
  } else {
    // If no schemas are specified, load all schemas and attributes
    modelRequests.push(api.get('schemas', {
      fields: _model_config__WEBPACK_IMPORTED_MODULE_9__["fieldsForSchemas"]
    }));
    modelRequests.push(api.get('attributes', {
      fields: ':all,optionSet[:all,options[:all]]',
      paging: false
    }));
  }

  return modelRequests;
}
/**
 * Init function that used to initialise {@link module:d2.init~d2|d2}. This will load the schemas from the DHIS2 api and configure your {@link module:d2.init~d2|d2} instance.
 *
 * The `config` object that can be passed into init can have the following properties:
 *
 * baseUrl: Set this when the url is something different then `/api`. If you are running your dhis instance in a subdirectory of the actual domain
 * for example http://localhost/dhis/ you should set the base url to `/dhis/api`
 *
 * unauthorizedCb: A callback function that is called whenever a API-request encounters a 401 - Unauthorized response.
 *  The function is called with (request, response) - the request object that failed, and the parsed response from the server.
 *
 * @param {Object} initConfig Configuration object that will be used to configure to define D2 Setting.
 * See the description for more information on the available settings.
 * @returns {Promise.<D2>} A promise that resolves with the intialized {@link init~d2|d2} object.
 *
 * @example
 * import init from 'd2';
 *
 * init({baseUrl: '/dhis/api'})
 *   .then((d2) => {
 *     console.log(d2.model.dataElement.list());
 *   });
 */


function init(initConfig) {
  var ApiClass = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _api_Api__WEBPACK_IMPORTED_MODULE_4__["default"];
  var logger = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _logger_Logger__WEBPACK_IMPORTED_MODULE_2__["default"].getLogger();
  var api = ApiClass.getApi();
  var config = _config__WEBPACK_IMPORTED_MODULE_7__["default"].create(preInitConfig, initConfig);
  /**
   * @namespace
   */

  var d2 = {
    /**
     * @description
     * This is the entry point for the modelDefinitions that were loaded. To start interacting with the metadata api
     * you would pick a modelDefinition from this object to interact with.
     *
     * @type {Object.<string, ModelDefinition>}
     * @instance
     */
    models: undefined,

    /**
     * Collection of the {@link module:model} classes
     *
     * @deprecated There is probably no point to expose this.
     * @instance
     */
    model: _model__WEBPACK_IMPORTED_MODULE_3__["default"],
    // TODO: Remove (Breaking)

    /**
     * Api class that is used throughout the api interaction. This can be used to get hold of the module:Api singleton.
     *
     * @example
     * d2.Api.getApi()      // Returns the api object
     *  .get('resources')   // Do a get request for /api/resources
     *  .then(resources => {
     *      console.log(resources);
     *  });
     *
     * @see {@link module:api~Api#getApi}
     *
     * @instance
     */
    Api: ApiClass,

    /**
     * System instance to interact with system information like system settings, system info etc.
     *
     * @example
     * console.log(d2.system.version.major); // 2 for DHIS 2.27
     *
     * @see {@link module:system/System~System|System}
     * @instance
     */
    system: _system_System__WEBPACK_IMPORTED_MODULE_5__["default"].getSystem(),

    /**
     * I18n instance with the loaded translations.
     *
     * Usually used for retrieving translations for a given key using `getTranslation(key: string)`
     *
     * @example
     * d2.i18n.getTranslation('success'); // Returns "Success" for the english locale
     *
     * @see {@link module:i18n~I18n#getTranslation|getTranslation}
     *
     * @instance
     */
    i18n: _i18n_I18n__WEBPACK_IMPORTED_MODULE_6__["default"].getI18n(),

    /**
     * Instance of the DataStore class for interaction with the dataStore api.
     *
     * @see {@link module:datastore.DataStore DataStore}
     *
     * @instance
     */
    dataStore: _datastore_DataStore__WEBPACK_IMPORTED_MODULE_10__["default"].getDataStore(),

    /**
     * Analytics instance for requesting analytics data from various endpoints.
     *
     * @example
     * d2.analytics.aggregate
     *  .addDimensions([
     *   'dx:Uvn6LCg7dVU;OdiHJayrsKo',
     *   'pe:LAST_4_QUARTERS',
     *   'ou:lc3eMKXaEfw;PMa2VCrupOd',
     *  ])
     *  .addFilter('pe:2016Q1;2016Q2')
     *  .getRawData({
     *    startDate: '2017-10-01',
     *    endDate: '2017-10-31'
     *  })
     *  .then(console.log)
     *
     * @see {@link module:analytics.Analytics Analytics}
     * @instance
     */
    analytics: _analytics_Analytics__WEBPACK_IMPORTED_MODULE_11__["default"].getAnalytics(),

    /*
     * GeoFeatures instance
     *
     * @see {@link module:geoFeatures.GeoFeatures GeoFeatures}
     * @instance
     */
    geoFeatures: _geofeatures_GeoFeatures__WEBPACK_IMPORTED_MODULE_12__["default"].getGeoFeatures() // Process the config in a the config class to keep all config calls together.

  };
  _config__WEBPACK_IMPORTED_MODULE_7__["default"].processConfigForD2(config, d2); // Because when importing the getInstance method in dependencies the getInstance could run before
  // init we have to resolve the current promise on first run and for consecutive ones replace the
  // old one with a fresh promise.

  if (firstRun) {
    firstRun = false;
  } else {
    deferredD2Init = _lib_utils__WEBPACK_IMPORTED_MODULE_1__["Deferred"].create();
  }

  var modelRequests = getModelRequests(api, config.schemas);
  var userRequests = [api.get('me', {
    fields: ':all,organisationUnits[id],userGroups[id],userCredentials[:all,!user,userRoles[id]'
  }), api.get('me/authorization'), getUserSettings(ApiClass)];
  var systemRequests = [api.get('system/info'), api.get('apps')];
  return Promise.all([].concat(_toConsumableArray(modelRequests), userRequests, systemRequests, [d2.i18n.load()])).then(function (res) {
    var responses = {
      schemas: Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["pick"])('schemas')(res[0]),
      attributes: Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["pick"])('attributes')(res[1]),
      currentUser: res[2],
      authorities: res[3],
      userSettings: res[4],
      systemInfo: res[5],
      apps: res[6]
    };
    responses.schemas // We only deal with metadata schemas
    .filter(function (schema) {
      return schema.metadata;
    }) // TODO: Remove this when the schemas endpoint is versioned or shows the correct urls for the requested version
    // The schemas endpoint is not versioned which will result into the modelDefinitions always using the
    // "default" endpoint, we therefore modify the endpoint url based on the given baseUrl.
    .map(function (schema) {
      schema.apiEndpoint = Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["updateAPIUrlWithBaseUrlVersionNumber"])(schema.apiEndpoint, config.baseUrl);
      return schema;
    }).forEach(function (schema) {
      // Attributes that do not have values do not by default get returned with the data,
      // therefore we need to grab the attributes that are attached to this particular schema to be able to know about them
      var schemaAttributes = responses.attributes.filter(function (attributeDescriptor) {
        var attributeNameFilter = [schema.singular, 'Attribute'].join('');
        return attributeDescriptor[attributeNameFilter] === true;
      });

      if (!Object.prototype.hasOwnProperty.call(d2.models, schema.singular)) {
        d2.models.add(_model__WEBPACK_IMPORTED_MODULE_3__["default"].ModelDefinition.createFromSchema(schema, schemaAttributes));
      }
    });
    /**
     * An instance of {@link module:current-user/CurrentUser~CurrentUser|CurrentUser}
     *
     * The currentUser can be used to retrieve data related to the currentUser.
     *
     * These things primarily include:
     * - currentUser properties retrieved from `/api/me`
     * - Lazily request collections related to the user such as
     *      - userRoles
     *      - userGroups
     *      - organisationUnits
     *      - dataViewOrganisationUnits
     * - authorities
     * - userSettings
     * - utility methods for ACL
     *
     * @example
     * d2.currentUser.canCreate(d2.models.dataElement); // Returns true when the user can create either a private/public dataElement
     * d2.currentUser.canCreate(d2.models.organisationUnit); // Returns true the user can create an organisationUnit
     *
     * @see {@link module:current-user/CurrentUser~CurrentUser|CurrentUser}
     * @instance
     */

    d2.currentUser = _current_user_CurrentUser__WEBPACK_IMPORTED_MODULE_8__["default"].create(responses.currentUser, responses.authorities, d2.models, responses.userSettings);
    d2.system.setSystemInfo(responses.systemInfo);
    d2.system.setInstalledApps(responses.apps);
    deferredD2Init.resolve(d2);
    return deferredD2Init.promise;
  }).catch(function (error) {
    logger.error('Unable to get schemas from the api', JSON.stringify(error), error);
    deferredD2Init.reject('Unable to get schemas from the DHIS2 API');
    return deferredD2Init.promise;
  });
}
/**
 * This function can be used to retrieve the `singleton` instance of d2. The instance is being created by calling
 * the `init` method.
 *
 * @returns {Promise.<D2>} A promise to the initialized {@link module:d2.init~d2|d2} instance.
 *
 * @example
 * import {init, getInstance} from 'd2';
 *
 * init({baseUrl: '/dhis2/api/'});
 * getInstance()
 *   .then(d2 => {
 *      d2.models.dataElement.list();
 *      // and all your other d2 magic.
 *   });
 */

function getInstance() {
  return deferredD2Init.promise;
}
function setInstance(d2) {
  deferredD2Init.resolve(d2);
}
/**
 * Can be used to set config options before initialisation of d2.
 *
 * @example
 * import {config, init} from 'd2';
 *
 * config.baseUrl = '/demo/api';
 * config.i18n.sources.add('i18n/systemsettingstranslations.properties');
 *
 * init()
 *   .then(d2 => {
 *     d2.system.settings.all()
 *       .then(systemSettings => Object.keys())
 *       .then(systemSettingsKey => {
 *         d2.i18n.getTranslation(systemSettingsKey);
 *       });
 *   });
 *   @type Config
 */

var config = preInitConfig; // Alias preInitConfig to be able to `import {config} from 'd2';`

/***/ }),

/***/ "./src/datastore/BaseStore.js":
/*!************************************!*\
  !*** ./src/datastore/BaseStore.js ***!
  \************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _BaseStoreNamespace__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BaseStoreNamespace */ "./src/datastore/BaseStoreNamespace.js");
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../lib/check */ "./src/lib/check.js");
function _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); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

/**
 * @module datastore
 */



/**
 * @private
 * @description
 * Represents a key-value store that can be interacted with. This can be used to get instances of Namespaces, which
 * can be used to interact with the relating namespace API.
 *
 * @memberof module:datastore
 * @abstract
 */

var BaseStore =
/*#__PURE__*/
function () {
  function BaseStore() {
    var api = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _api_Api__WEBPACK_IMPORTED_MODULE_1__["default"].getApi();
    var endPoint = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'dataStore';
    var NamespaceClass = arguments.length > 2 ? arguments[2] : undefined;

    _classCallCheck(this, BaseStore);

    if (this.constructor === BaseStore) {
      throw new Error("Can't instantiate abstract class!");
    }

    if (!(NamespaceClass.prototype instanceof _BaseStoreNamespace__WEBPACK_IMPORTED_MODULE_0__["default"])) {
      throw new Error("NamespaceClass must be subclass of ".concat(_typeof(_BaseStoreNamespace__WEBPACK_IMPORTED_MODULE_0__["default"])));
    }

    this.NamespaceClass = NamespaceClass;
    this.endPoint = endPoint;
    this.api = api;
  }
  /**
   * @description
   * Tries to get the given namespace from the server, and returns an instance of 'RetClass' that
   * may be used to interact with this namespace. See {@link DataStoreNamespace}.
   *
   * @param {string} namespace To get.
   * @param {boolean} [autoLoad=true] If true, autoloads the keys of the namespace from the server.
   * before the namespace is created. If false, an instance of he namespace is returned without any keys.
   * @returns {Promise<BaseStoreNamespace>} An instance of a current store-Namespace-instance representing the namespace that can be interacted with.
   * Or an error if namespace does not exist.
   */


  _createClass(BaseStore, [{
    key: "get",
    value: function get(namespace) {
      var _this = this;

      var autoLoad = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

      if (!autoLoad) {
        return new Promise(function (resolve) {
          resolve(new _this.NamespaceClass(namespace));
        });
      }

      return this.api.get([this.endPoint, namespace].join('/')).then(function (response) {
        if (response && Object(_lib_check__WEBPACK_IMPORTED_MODULE_2__["isArray"])(response)) {
          if (response.length < 1) {
            // fix for api bug returning empty array instead of 404
            return Promise.reject(new Error('The requested namespace has no keys or does not exist.'));
          }

          return new _this.NamespaceClass(namespace, response);
        }

        return Promise.reject(new Error('The requested namespace has no keys or does not exist.'));
      });
    }
    /**
     * Retrieves a list of all namespaces on the server.
     * @returns {Promise} An array of namespaces.
     */

  }, {
    key: "getAll",
    value: function getAll() {
      return this.api.get(this.endPoint).then(function (response) {
        if (response && Object(_lib_check__WEBPACK_IMPORTED_MODULE_2__["isArray"])(response)) {
          return response;
        }

        throw new Error('No namespaces exist.');
      });
    }
    /**
     * Convenience method to check if a namespace exists on the server.
     * @param {string} namespace - Namespace to check.
     * @returns {Promise<boolean>} True if namespace exists, false otherwise.
     */

  }, {
    key: "has",
    value: function has(namespace) {
      return this.api.get([this.endPoint, namespace].join('/')).then(function (response) {
        if (response && Object(_lib_check__WEBPACK_IMPORTED_MODULE_2__["isArray"])(response)) {
          if (response.length < 1) {
            // fix for api bug returning empty array instead of 404
            return Promise.reject(response);
          }

          return true;
        }

        return Promise.reject(new Error('Response is not an array!'));
      }).catch(function (e) {
        if (e.httpStatusCode === 404 || Object(_lib_check__WEBPACK_IMPORTED_MODULE_2__["isArray"])(e) && e.length < 1) {
          return Promise.resolve(false);
        }

        throw e;
      });
    }
    /**
     * Deletes a namespace
     *
     * @param {string} namespace The namespace to delete.
     * @returns {Promise} the response body from the {@link module:api.Api#get API}.
     */

  }, {
    key: "delete",
    value: function _delete(namespace) {
      return this.api.delete([this.endPoint, namespace].join('/'));
    }
    /**
     * Creates a namespace. Ensures that the namespace does not exists on the server.
     * Note that for the namespace to be saved on the server, you need to call {@link module:dataStore.BaseStoreNamespace.set set}.
     *
     * @param {string} namespace The namespace to create.
     * @returns {Promise<BaseStoreNamespace>} An instance of the current store-Namespace-instance representing the namespace that can be interacted with, or
     * an error if namespace exists.
     */

  }, {
    key: "create",
    value: function create(namespace) {
      var _this2 = this;

      return this.has(namespace).then(function (exists) {
        return exists ? Promise.reject(new Error('Namespace already exists.')) : new _this2.NamespaceClass(namespace);
      });
    }
  }]);

  return BaseStore;
}();

/* harmony default export */ __webpack_exports__["default"] = (BaseStore);

/***/ }),

/***/ "./src/datastore/BaseStoreNamespace.js":
/*!*********************************************!*\
  !*** ./src/datastore/BaseStoreNamespace.js ***!
  \*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../lib/check */ "./src/lib/check.js");
function _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); }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }



/**
 * @private
 * @description
 * Represents a namespace in the dataStore that can be used to be used to interact with
 * the remote API.
 *
 * @property {Array} keys an array of the loaded keys.
 * @property {String} namespace name of this namespace as on the server.
 *
 * @memberof module:datastore
 */

var BaseStoreNamespace =
/*#__PURE__*/
function () {
  /**
   * @param {string} namespace - the name of the namespace this represents.
   * @param {string[]} keys - preloaded keys for this namespace.
   * @param {module:api.Api} api - the api implementation, used for testing.
   * @param {string} endPoint - the relative API-endpoint, one of ['dataStore, userDataStore'].
   */
  function BaseStoreNamespace(namespace, keys) {
    var api = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi();
    var endPoint = arguments.length > 3 ? arguments[3] : undefined;

    _classCallCheck(this, BaseStoreNamespace);

    if (!Object(_lib_check__WEBPACK_IMPORTED_MODULE_1__["isString"])(namespace)) {
      throw new Error('BaseStoreNamespace must be called with a string to identify the Namespace');
    }

    if (!Object(_lib_check__WEBPACK_IMPORTED_MODULE_1__["isString"])(endPoint)) {
      throw new Error('BaseStoreNamespace must be called with an endPoint');
    }

    if (this.constructor === BaseStoreNamespace) {
      throw new Error("Can't instantiate abstract class!");
    }

    this.api = api;
    /**
     * The name of the namespace
     * @type {string}
     */

    this.namespace = namespace;
    /**
     * an array of the loaded keys.
     * @type {string[]}
     */

    this.keys = keys || [];
    this.endPoint = endPoint;
  }
  /**
   * Get the keys for this namespace.
   *
   * @returns {Promise} - The internal list of keys for current namespace.
   */


  _createClass(BaseStoreNamespace, [{
    key: "getKeys",
    value: function getKeys() {
      var _this = this;

      return this.api.get([this.endPoint, this.namespace].join('/')).then(function (response) {
        if (response && Object(_lib_check__WEBPACK_IMPORTED_MODULE_1__["isArray"])(response)) {
          _this.keys = response;
          return response;
        }

        return Promise.reject(new Error('The requested namespace has no keys or does not exist.'));
      });
    }
    /**
     * Retrieves the value of given key in current namespace.
     *
     * @param key - key to retrieve.
     * @returns {Promise} - The value of the given key.
     */

  }, {
    key: "get",
    value: function get(key) {
      return this.api.get([this.endPoint, this.namespace, key].join('/'));
    }
    /**
     * Sets the value of given key to given value.
     *
     * This will also create a new namespace on the API-end if it does not exist.
     * If the key exists <a href='#update'> update</a> will be called, unless <code>overrideUpdate</code> equals
     * true.
     *
     * @param key - key in this namespace to set.
     * @param value - JSON-value to be set.
     * @param [overrideUpdate=false] - If true a post-request is sent even if key exists.
     * @param [encrypt=false] - If the value should be encrypted on the server.
     * @returns {Promise} - the response body from the {@link module:api.Api#get API}.
     */

  }, {
    key: "set",
    value: function set(key, value) {
      var _this2 = this;

      var overrideUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      var encrypt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;

      if (!overrideUpdate && this.keys.includes(key)) {
        return this.update(key, value);
      }

      var queryParams = encrypt === true ? '?encrypt=true' : '';
      return this.api.post([this.endPoint, this.namespace, key + queryParams].join('/'), value).then(function (resp) {
        _this2.keys = [].concat(_toConsumableArray(_this2.keys), [key]);
        return resp;
      });
    }
    /**
     * Deletes given key from the API.
     * @param {string} key - key to delete.
     * @returns {Promise} - the response body from the {@link module:api.Api#get API}.
     */

  }, {
    key: "delete",
    value: function _delete(key) {
      var _this3 = this;

      if (!Object(_lib_check__WEBPACK_IMPORTED_MODULE_1__["isString"])(key)) {
        return Promise.reject(new Error("Expected key to be string, but got ".concat(_typeof(key))));
      }

      return this.api.delete([this.endPoint, this.namespace, key].join('/')).then(function (resp) {
        _this3.keys = _this3.keys.filter(function (elem) {
          return elem !== key;
        });
        return resp;
      });
    }
    /**
     * Updates a key with given value.
     * @param key - key to update.
     * @param value - value to update to.
     * @returns {Promise} - the response body from the {@link module:api.Api#get API}.
     */

  }, {
    key: "update",
    value: function update(key, value) {
      return this.api.update([this.endPoint, this.namespace, key].join('/'), value, false, {
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
  }]);

  return BaseStoreNamespace;
}();

/* harmony default export */ __webpack_exports__["default"] = (BaseStoreNamespace);

/***/ }),

/***/ "./src/datastore/DataStore.js":
/*!************************************!*\
  !*** ./src/datastore/DataStore.js ***!
  \************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _BaseStore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BaseStore */ "./src/datastore/BaseStore.js");
/* harmony import */ var _DataStoreNamespace__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DataStoreNamespace */ "./src/datastore/DataStoreNamespace.js");
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
function _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); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }

function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }




/**
 * @augments module:datastore.BaseStore
 * @description
 * Represents the dataStore that can be interacted with. This can be used to get instances of DataStoreNamespace, which
 * can be used to interact with the {@link module:datastore.DataStoreNamespace namespace API}.
 *
 * The store is a key-value store, where a namespace contains a list of keys, and
 * a key corresponds to an arbitrary JSON-object. The dataStore is DHIS2-instance wide.
 *
 * Note that a namespace cannot exist without at least one key-value pair, for this reason
 * you need to call {@link module:datastore.DataStoreNamespace#set set()} after {@link module:datastore.DataStore#create create()} to save a namespace
 * with a key and a value.
 *
 * @example
 * import { init } from 'd2';
 *
 * init({baseUrl: 'https://play.dhis2.org/demo/api'})
 *   .then((d2) => {
 *     d2.dataStore.get('namespace').then(namespace => {
 *          namespace.get('key').then(value => console.log(value))
 *      });
 *   });
 *
 * @memberof module:datastore
 */

var DataStore =
/*#__PURE__*/
function (_BaseStore) {
  _inherits(DataStore, _BaseStore);

  function DataStore() {
    var api = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _api_Api__WEBPACK_IMPORTED_MODULE_2__["default"].getApi();
    var endPoint = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'dataStore';

    _classCallCheck(this, DataStore);

    return _possibleConstructorReturn(this, _getPrototypeOf(DataStore).call(this, api, endPoint, _DataStoreNamespace__WEBPACK_IMPORTED_MODULE_1__["default"]));
  }
  /**
   * @description
   * Tries to get the given namespace from the server, and returns an instance of DataStore that
   * may be used to interact with this namespace. See {@link module:datastore.DataStoreNamespace DataStore}.
   *
   * @example <caption>Getting a namespace</caption>
   * d2.dataStore.get('namespace').then(namespace => {
   *     namespace.set('new key', value);
   *});
   * @param namespace - Namespace to get.
   * @param [autoLoad=true] If true, autoloads the keys of the namespace from the server.
   * If false, an instance of the namespace is returned without any keys (no request is sent to the server).
   * @returns {Promise<DataStoreNamespace>} An instance of a DataStore representing the namespace that can be interacted with,
   * or an error if namespace exists.
   */


  _createClass(DataStore, [{
    key: "get",
    value: function get(namespace) {
      var autoLoad = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
      return _get(_getPrototypeOf(DataStore.prototype), "get", this).call(this, namespace, autoLoad);
    }
    /**
     * Creates a namespace. Ensures that the namespace does not exists on the server.
     * Note that for the namespace to be saved on the server, you need to call {@link module:datastore.DataStoreNamespace#set set}.
     *
     * @example <caption>Creating a namespace</caption>
     * d2.dataStore.create('new namespace').then(namespace => {
     *     namespace.set('new key', value);
     * });
     * @param {string} namespace The namespace to create.
     * @returns {Promise<DataStoreNamespace>} An instance of the current store-Namespace-instance representing the namespace that can be interacted with, or
     * an error if namespace exists.
     */

  }, {
    key: "create",
    value: function create(namespace) {
      return _get(_getPrototypeOf(DataStore.prototype), "create", this).call(this, namespace);
    }
    /**
     * @static
     *
     * @returns {DataStore} Object with the dataStore interaction properties
     *
     * @description
     * Get a new instance of the dataStore object. This will function as a singleton, when a DataStore object has been created
     * when requesting getDataStore again the original version will be returned.
     */

  }], [{
    key: "getDataStore",
    value: function getDataStore() {
      if (!DataStore.getDataStore.dataStore) {
        DataStore.getDataStore.dataStore = new DataStore();
      }

      return DataStore.getDataStore.dataStore;
    }
  }]);

  return DataStore;
}(_BaseStore__WEBPACK_IMPORTED_MODULE_0__["default"]);

/* harmony default export */ __webpack_exports__["default"] = (DataStore);

/***/ }),

/***/ "./src/datastore/DataStoreNamespace.js":
/*!*********************************************!*\
  !*** ./src/datastore/DataStoreNamespace.js ***!
  \*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
/* harmony import */ var _BaseStoreNamespace__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BaseStoreNamespace */ "./src/datastore/BaseStoreNamespace.js");
function _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); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }



/**
 * @augments module:datastore.BaseStoreNamespace
 * @description
 * Represents a namespace in the dataStore that can be used to be used to interact with
 * the remote API.
 *
 * @property {array} keys an array of the loaded keys.
 * @property {string} namespace Name of the namespace as on the server.
 * @memberof module:datastore
 */

var DataStoreNamespace =
/*#__PURE__*/
function (_BaseStoreNamespace) {
  _inherits(DataStoreNamespace, _BaseStoreNamespace);

  function DataStoreNamespace(namespace, keys) {
    var api = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi();
    var endPoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'dataStore';

    _classCallCheck(this, DataStoreNamespace);

    return _possibleConstructorReturn(this, _getPrototypeOf(DataStoreNamespace).call(this, namespace, keys, api, endPoint));
  }
  /**
   * Retrieves metaData of given key in current namespace.
   *
   * @param key - the key to retrieve metaData for.
   */


  _createClass(DataStoreNamespace, [{
    key: "getMetaData",
    value: function getMetaData(key) {
      return this.api.get([this.endPoint, this.namespace, key, 'metaData'].join('/'));
    }
  }]);

  return DataStoreNamespace;
}(_BaseStoreNamespace__WEBPACK_IMPORTED_MODULE_1__["default"]);

/* harmony default export */ __webpack_exports__["default"] = (DataStoreNamespace);

/***/ }),

/***/ "./src/datastore/UserDataStore.js":
/*!****************************************!*\
  !*** ./src/datastore/UserDataStore.js ***!
  \****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _BaseStore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BaseStore */ "./src/datastore/BaseStore.js");
/* harmony import */ var _UserDataStoreNamespace__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./UserDataStoreNamespace */ "./src/datastore/UserDataStoreNamespace.js");
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
function _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); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }

function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }




/**
 * @augments module:datastore.BaseStore
 * @description
 * Represents the UserDataStore that can be interacted with. This can be used to get instances of UserDataStoreNamespace, which
 * can be used to interact with the {@link module:current-user.UserDataStoreNamespace namespace API}.
 *
 * The store is a key-value store, where a namespace contains a list of keys, and
 * a key corresponds to an arbitrary JSON-object. The store is per-user, and only the currently logged-in user
 * has access to the namespaces.
 *
 * Note that a namespace cannot exist without at least one key-value pair, for this reason
 * you need to call {@link module:current-user.UserDataStoreNamespace#set set()} after {@link module:current-user.UserDataStore#create create()} to save a namespace
 * with a key and a value.
 *
 * @example <caption>Getting a value with promise-syntax</caption>
 * import { init } from 'd2';
 *
 * init({baseUrl: 'https://play.dhis2.org/demo/api'})
 *   .then((d2) => {
 *     d2.currentUser.dataStore.get('namespace').then(namespace => {
 *          namespace.get('key').then(value => console.log(value))
 *      });
 *   });
 *
 * @example <caption>Creation of namespace with async-syntax</caption>
 * const namespace = await d2.currentUser.dataStore.create('new namespace', false);
 * // The namespace is not actually created on the server before 'set' is called
 * await namespace.set('new key', value);
 *
 * @memberof module:current-user
 */

var UserDataStore =
/*#__PURE__*/
function (_BaseStore) {
  _inherits(UserDataStore, _BaseStore);

  function UserDataStore() {
    var api = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _api_Api__WEBPACK_IMPORTED_MODULE_2__["default"].getApi();
    var endPoint = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'userDataStore';

    _classCallCheck(this, UserDataStore);

    return _possibleConstructorReturn(this, _getPrototypeOf(UserDataStore).call(this, api, endPoint, _UserDataStoreNamespace__WEBPACK_IMPORTED_MODULE_1__["default"]));
  }
  /**
   * @description
   * Tries to get the given namespace from the server, and returns an instance of 'UserDataStore' that
   * may be used to interact with this namespace. See {@link module:current-user.UserDataStoreNamespace UserDataStoreNamespace}.
   *
   * @example <caption>Getting a namespace</caption>
   * d2.currentUser.dataStore.get('namespace').then(namespace => {
   *     namespace.set('new key', value);
   *});
   *
   * @param {string} namespace - Namespace to get.
   * @param {boolean} [autoLoad=true] - If true, autoloads the keys of the namespace from the server.
   * If false, an instance of the namespace is returned without any keys (no request is sent to the server).
   *
   * @returns {Promise<UserDataStoreNamespace>} An instance of a UserDataStoreNamespace representing the namespace that can be interacted with.
   */


  _createClass(UserDataStore, [{
    key: "get",
    value: function get(namespace) {
      var autoLoad = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
      return _get(_getPrototypeOf(UserDataStore.prototype), "get", this).call(this, namespace, autoLoad);
    }
    /**
     * Creates a namespace. Ensures that the namespace does not exists on the server.
     * Note that for the namespace to be saved on the server, you need to call {@link module:current-user.UserDataStoreNamespace#set set}.
     *
     * @example <caption>Creating a namespace</caption>
     * d2.currentUser.dataStore.create('new namespace').then(namespace => {
     *     namespace.set('new key', value);
     * });
     * @param {string} namespace The namespace to create.
     * @returns {Promise<UserDataStoreNamespace>} An instance of the current store-Namespace-instance representing the namespace that can be interacted with, or
     * an error if namespace exists.
     */

  }, {
    key: "create",
    value: function create(namespace) {
      return _get(_getPrototypeOf(UserDataStore.prototype), "create", this).call(this, namespace);
    }
    /**
     * @static
     *
     * @returns {UserDataStore} Object with the userDataStore interaction properties
     *
     * @description
     * Get a new instance of the userDataStore object. This will function as a singleton - when a UserDataStore object has been created
     * when requesting getUserDataStore again, the original version will be returned.
     */

  }], [{
    key: "getUserDataStore",
    value: function getUserDataStore() {
      if (!UserDataStore.getUserDataStore.dataStore) {
        UserDataStore.getUserDataStore.dataStore = new UserDataStore(_api_Api__WEBPACK_IMPORTED_MODULE_2__["default"].getApi(), 'userDataStore');
      }

      return UserDataStore.getUserDataStore.dataStore;
    }
  }]);

  return UserDataStore;
}(_BaseStore__WEBPACK_IMPORTED_MODULE_0__["default"]);

/* harmony default export */ __webpack_exports__["default"] = (UserDataStore);

/***/ }),

/***/ "./src/datastore/UserDataStoreNamespace.js":
/*!*************************************************!*\
  !*** ./src/datastore/UserDataStoreNamespace.js ***!
  \*************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
/* harmony import */ var _BaseStoreNamespace__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BaseStoreNamespace */ "./src/datastore/BaseStoreNamespace.js");
function _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); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }



/**
 * @augments module:datastore.BaseStoreNamespace
 * @description
 * Represents a namespace in the dataStore that can be used to be used to interact with
 * the remote API.
 *
 * @property {array} keys an array of the loaded keys.
 * @property {string} namespace Name of the namespace as on the server.
 *
 * @memberof module:current-user
 */

var UserDataStoreNamespace =
/*#__PURE__*/
function (_BaseStoreNamespace) {
  _inherits(UserDataStoreNamespace, _BaseStoreNamespace);

  function UserDataStoreNamespace(namespace, keys) {
    var api = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi();
    var endPoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'userDataStore';

    _classCallCheck(this, UserDataStoreNamespace);

    return _possibleConstructorReturn(this, _getPrototypeOf(UserDataStoreNamespace).call(this, namespace, keys, api, endPoint));
  }

  return UserDataStoreNamespace;
}(_BaseStoreNamespace__WEBPACK_IMPORTED_MODULE_1__["default"]);

/* harmony default export */ __webpack_exports__["default"] = (UserDataStoreNamespace);

/***/ }),

/***/ "./src/defaultConfig.js":
/*!******************************!*\
  !*** ./src/defaultConfig.js ***!
  \******************************/
/*! exports provided: noCreateAllowedFor, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "noCreateAllowedFor", function() { return noCreateAllowedFor; });
/**
 * List of modelDefinition names that should not allow create. Even when their schema authorities allows the user
 * to create them, the user should not be allowed to create these objects for some business logic reason.
 *
 * @private
 * @type {Set<string>}
 * @readonly
 */
var noCreateAllowedFor = new Set([// Creating categoryOptionCombos is not allowed because they are generated by the backend.
'categoryOptionCombo']);
/**
 * Default options to be used when running the `d2.init` function.
 */

/* harmony default export */ __webpack_exports__["default"] = ({
  baseUrl: '/api',
  i18n: {
    sources: new Set(),
    strings: new Set()
  }
});

/***/ }),

/***/ "./src/geofeatures/GeoFeatures.js":
/*!****************************************!*\
  !*** ./src/geofeatures/GeoFeatures.js ***!
  \****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
/* harmony import */ var _uid__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../uid */ "./src/uid.js");
function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }



/**
 * @class GeoFeatures
 * @description
 * GeoFeatures class used to request organisation unit coordinates from the Web API.
 */

var GeoFeatures =
/*#__PURE__*/
function () {
  /**
   * @constructor
   *
   * @param {Array} orgUnits Organisation units (UID, level, group, user org. unit) to include in the response.
   * @param {String} displayName The name property to display (NAME|SHORTNAME).
   */
  function GeoFeatures() {
    var orgUnits = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    var displayName = arguments.length > 1 ? arguments[1] : undefined;

    _classCallCheck(this, GeoFeatures);

    this.orgUnits = orgUnits;
    this.displayName = displayName;
  }
  /**
   * @method byOrgUnit
   *
   * @param {Array} orgUnits Organisation units (UID, level, group, user org. unit) to include in the response.
   *
   * @returns {GeoFeatures}
   */


  _createClass(GeoFeatures, [{
    key: "byOrgUnit",
    value: function byOrgUnit(orgUnits) {
      if (!orgUnits) {
        return this;
      }

      var orgUnitsArray = [].concat(orgUnits);

      if (!orgUnitsArray.every(GeoFeatures.isValidOrgUnit)) {
        throw new Error("Invalid organisation unit: ".concat(orgUnits));
      }

      return new GeoFeatures(orgUnitsArray, this.displayName);
    }
    /**
     * @method byOrgUnit
     *
     * @param {String} displayName The name property to display (NAME|SHORTNAME).
     *
     * @returns {GeoFeatures}
     */

  }, {
    key: "displayProperty",
    value: function displayProperty(displayName) {
      if (!displayName) {
        return this;
      }

      if (!GeoFeatures.isValidDisplayName(displayName)) {
        throw new Error("Invalid display property: ".concat(displayName));
      }

      return new GeoFeatures(this.orgUnits, displayName);
    }
    /**
     * @method getAll
     *
     * @param {Object} params Extra URL params to pass to the Web API endpoint.
     *
     * @returns {Promise} with an array of geofeatures.
     */

  }, {
    key: "getAll",
    value: function getAll() {
      var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var api = _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi();
      var urlParams = params;

      if (this.orgUnits.length) {
        urlParams.ou = "ou:".concat(this.orgUnits.join(';'));
      }

      if (this.displayName) {
        urlParams.displayProperty = this.displayName;
      }

      return api.get('geoFeatures', urlParams);
    }
    /**
     * @method isValidOrgUnit
     * @static
     *
     * @returns {boolean} True if the org. unit is valid
     *
     * @description
     * Checks if the org. unit is valid (UID, level, group, user org. unit)
     */

  }], [{
    key: "isValidOrgUnit",
    value: function isValidOrgUnit(orgUnit) {
      return Object(_uid__WEBPACK_IMPORTED_MODULE_1__["isValidUid"])(orgUnit) || GeoFeatures.isValidOrgUnitLevel(orgUnit) || GeoFeatures.isValidOrgUnitGroup(orgUnit) || GeoFeatures.isValidUserOrgUnit(orgUnit);
    }
    /**
     * @method isValidOrgUnitLevel
     * @static
     *
     * @returns {boolean} True if the org. unit level is valid
     *
     * @description
     * Checks if the org. unit level is valid.
     */

  }, {
    key: "isValidOrgUnitLevel",
    value: function isValidOrgUnitLevel(level) {
      var match = level.match(/LEVEL-(.*)$/);
      return Array.isArray(match) && (/^[0-9]+$/.test(match[1]) || Object(_uid__WEBPACK_IMPORTED_MODULE_1__["isValidUid"])(match[1]));
    }
    /**
     * @method isValidOrgUnitGroup
     * @static
     *
     * @returns {boolean} True if the org. unit group is valid
     *
     * @description
     * Checks if the org. unit group is valid.
     */

  }, {
    key: "isValidOrgUnitGroup",
    value: function isValidOrgUnitGroup(group) {
      var match = group.match(/OU_GROUP-(.*)$/);
      return Array.isArray(match) && Object(_uid__WEBPACK_IMPORTED_MODULE_1__["isValidUid"])(match[1]);
    }
    /**
     * @method isValidUserOrgUnit
     * @static
     *
     * @returns {boolean} True if the user org. unit is valid
     *
     * @description
     * Checks if the user org. unit is valid.
     */

  }, {
    key: "isValidUserOrgUnit",
    value: function isValidUserOrgUnit(orgUnit) {
      return orgUnit === GeoFeatures.USER_ORGUNIT || orgUnit === GeoFeatures.USER_ORGUNIT_CHILDREN || orgUnit === GeoFeatures.USER_ORGUNIT_GRANDCHILDREN;
    }
    /**
     * @method isValidDisplayName
     * @static
     *
     * @returns {boolean} True if display name is valid
     *
     * @description
     * Checks if the display name is valid.
     */

  }, {
    key: "isValidDisplayName",
    value: function isValidDisplayName(displayName) {
      return displayName === GeoFeatures.DISPLAY_PROPERTY_NAME || displayName === GeoFeatures.DISPLAY_PROPERTY_SHORTNAME;
    }
    /**
     * @method getGeoFeatures
     * @static
     *
     * @returns {GeoFeatures} Object with interaction properties
     *
     * @description
     * Get a new instance of the GeoFeatures object.
     */

  }, {
    key: "getGeoFeatures",
    value: function getGeoFeatures() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      return _construct(GeoFeatures, args);
    }
  }]);

  return GeoFeatures;
}();

_defineProperty(GeoFeatures, "DISPLAY_PROPERTY_NAME", 'NAME');

_defineProperty(GeoFeatures, "DISPLAY_PROPERTY_SHORTNAME", 'SHORTNAME');

_defineProperty(GeoFeatures, "USER_ORGUNIT", 'USER_ORGUNIT');

_defineProperty(GeoFeatures, "USER_ORGUNIT_CHILDREN", 'USER_ORGUNIT_CHILDREN');

_defineProperty(GeoFeatures, "USER_ORGUNIT_GRANDCHILDREN", 'USER_ORGUNIT_GRANDCHILDREN');

/* harmony default export */ __webpack_exports__["default"] = (GeoFeatures);

/***/ }),

/***/ "./src/i18n/I18n.js":
/*!**************************!*\
  !*** ./src/i18n/I18n.js ***!
  \**************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

/**
 * @module i18n
 */

/**
 * I18n class for dealing with translations
 */

var I18n =
/*#__PURE__*/
function () {
  function I18n() {
    var sources = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    var api = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi();

    _classCallCheck(this, I18n);

    this.sources = sources;
    this.api = api;
    this.strings = new Set();
    this.translations = undefined;
  }
  /**
   * Adds a .properties file to the list of sources to load translations from
   *
   * Files are loaded in the order they're added, and the first translation of each string that's encountered will be
   * used.
   *
   * @param {String} path
   */


  _createClass(I18n, [{
    key: "addSource",
    value: function addSource(path) {
      this.sources.push(path);
    }
    /**
     * Adds one or more strings to the list of strings to translate
     *
     * @param {(String[]|String)} strings
     */

  }, {
    key: "addStrings",
    value: function addStrings(strings) {
      var _this = this;

      if (typeof strings === 'string' && strings.trim().length > 0) {
        this.strings.add(strings.trim());
      } else {
        Array.from(strings).filter(function (string) {
          return string && "".concat(string).trim().length > 0;
        }).forEach(function (string) {
          return _this.strings.add(string);
        });
      }
    }
    /**
     * Load translations
     *
     * First, all properties files (specified with addSource) are loaded.
     * Then, if any untranslated strings remain, these are POSTed to the i18n endpoint of the DHIS2 API.
     *
     * @returns {Promise}
     */

  }, {
    key: "load",
    value: function load() {
      var _this2 = this;

      var i18n = this;
      i18n.translations = {};

      function parseProperties(text) {
        return text.split('\n').reduce(function (props, line) {
          var _line$split$map = line.split('=').map(function (out) {
            return out.trim();
          }),
              _line$split$map2 = _slicedToArray(_line$split$map, 2),
              key = _line$split$map2[0],
              value = _line$split$map2[1];

          if (key !== undefined && value !== undefined && !props.hasOwnProperty(key)) {
            props[key] = value.replace(/\\u([0-9a-f]{4})/gi, function (match, grp) {
              return String.fromCharCode(parseInt(grp, 16));
            });
          }

          return props;
        }, {});
      }

      var propFiles = [];
      this.sources.forEach(function (source) {
        propFiles.push(i18n.api.request('GET', source).then(function (data) {
          return Promise.resolve(parseProperties(data));
        }, // Resolve errors to an empty object, so that one missing file doesn't prevent
        // the rest from being loaded
        function () {
          return Promise.resolve({});
        }));
      });
      return Promise.all(propFiles).then(function (propFile) {
        propFile.forEach(function (props) {
          Object.keys(props).forEach(function (str) {
            if (!i18n.translations.hasOwnProperty(str)) {
              i18n.translations[str] = props[str];
            }

            _this2.strings.delete(str);
          });
        });

        if (_this2.strings.size > 0) {
          return i18n.api.post('i18n', Array.from(i18n.strings)).then(function (res) {
            Object.keys(res).filter(function (str) {
              return str !== res[str];
            }).forEach(function (str) {
              i18n.translations[str] = res[str];
              i18n.strings.delete(str);
            });
            return Promise.resolve(i18n.translations);
          });
        }

        return Promise.resolve(i18n.translations);
      });
    }
    /**
     * Gets the translated version of the specified string
     *
     * If no translation exists for the specified string, the string is returned as is with two asterisks on each side,
     * in order to easily identify missing translations in the UI
     *
     * @param string
     * @returns {String}
     */

  }, {
    key: "getTranslation",
    value: function getTranslation(string) {
      var variables = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      if (this.translations === undefined) {
        throw new Error('Tried to translate before loading translations!');
      }

      var translatedString = this.translations.hasOwnProperty(string) ? this.translations[string] : "** ".concat(string, " **");

      if (Object.keys(variables).length) {
        return translatedString.replace(/\$\$(.+?)\$\$/gi, function (match, partial) {
          return variables[partial] || '';
        });
      }

      return translatedString;
    }
    /**
     * Check if a translation exists for the specified string
     *
     * @param string
     * @returns {boolean} True if a translation exists, false otherwise
     */

  }, {
    key: "isTranslated",
    value: function isTranslated(string) {
      if (this.translations === undefined) {
        throw new Error('Tried to translate before loading translations!');
      }

      return this.translations.hasOwnProperty(string);
    }
    /**
     * Get the list of strings that don't have translations
     *
     * If no translations have been loaded yet, `undefined` is returned in stead.
     *
     * @returns {Array|undefined} Array of untranslated strings, or undefined if translations haven't been loaded
     */

  }, {
    key: "getUntranslatedStrings",
    value: function getUntranslatedStrings() {
      return this.translations ? Array.from(this.strings) : undefined;
    }
    /**
     * Return a new instance of this class
     *
     * @returns {I18n}
     */

  }], [{
    key: "getI18n",
    value: function getI18n() {
      return new I18n();
    }
  }]);

  return I18n;
}();

/* harmony default export */ __webpack_exports__["default"] = (I18n);

/***/ }),

/***/ "./src/lib/SchemaTypes.js":
/*!********************************!*\
  !*** ./src/lib/SchemaTypes.js ***!
  \********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils */ "./src/lib/utils.js");
/* harmony import */ var _check__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./check */ "./src/lib/check.js");



var getTypes = function getTypes() {
  return ['TEXT', 'NUMBER', 'INTEGER', 'BOOLEAN', 'EMAIL', 'PASSWORD', 'URL', 'PHONENUMBER', 'GEOLOCATION', // TODO: Geo location could be an advanced type of 2 numbers / strings?
  'COLOR', 'COMPLEX', 'COLLECTION', 'REFERENCE', 'DATE', 'COMPLEX', 'IDENTIFIER', 'CONSTANT'];
};

var typeLookup = function typeLookup(propertyType) {
  if (getTypes().indexOf(propertyType) >= 0 && Object(_check__WEBPACK_IMPORTED_MODULE_1__["isString"])(propertyType)) {
    return propertyType;
  }

  var message = ['Type from schema "', propertyType, '" not found available type list.'].join('');
  return Object(_utils__WEBPACK_IMPORTED_MODULE_0__["throwError"])(message);
};

var SchemaTypes = {
  getTypes: getTypes,
  typeLookup: typeLookup
};
/* harmony default export */ __webpack_exports__["default"] = (SchemaTypes);

/***/ }),

/***/ "./src/lib/check.js":
/*!**************************!*\
  !*** ./src/lib/check.js ***!
  \**************************/
/*! exports provided: checkDefined, checkType, isType, isString, isArray, isObject, isDefined, isInteger, isNumeric, contains, isEmpty, isValidUid, hasKeys, areDefinedAndEqual, toBe, toBeAny, isNullUndefinedOrEmptyString, isFunction, hasOwnProperty, rootJunctions, isValidRootJunction, checkValidRootJunction */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkDefined", function() { return checkDefined; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkType", function() { return checkType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isType", function() { return isType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isString", function() { return isString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isArray", function() { return isArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isObject", function() { return isObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDefined", function() { return isDefined; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isInteger", function() { return isInteger; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNumeric", function() { return isNumeric; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "contains", function() { return contains; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isEmpty", function() { return isEmpty; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isValidUid", function() { return isValidUid; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasKeys", function() { return hasKeys; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "areDefinedAndEqual", function() { return areDefinedAndEqual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toBe", function() { return toBe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toBeAny", function() { return toBeAny; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNullUndefinedOrEmptyString", function() { return isNullUndefinedOrEmptyString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFunction", function() { return isFunction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasOwnProperty", function() { return hasOwnProperty; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rootJunctions", function() { return rootJunctions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isValidRootJunction", function() { return isValidRootJunction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkValidRootJunction", function() { return checkValidRootJunction; });
function _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); }

/**
 * @module lib/check
 */

/**
 *
 * @param value
 * @param name
 * @returns {boolean}
 */
function checkDefined(value, name) {
  if (value !== undefined) {
    return true;
  }

  throw new Error([name || 'Value', 'should be provided'].join(' '));
} // TODO: Decide if checkType([], 'object') is a 'false' positive
// eslint-disable-next-line complexity

function checkType(value, type, name) {
  checkDefined(value, name);
  checkDefined(type, 'Type');

  if (typeof type === 'function' && value instanceof type || typeof type === 'string' && _typeof(value) === type) {
    return true;
  }

  throw new Error(['Expected', name || value, 'to have type', type].join(' '));
} // TODO: Log type error?

function isType(value, type) {
  function noop() {}

  try {
    checkType(value, type);
    return true;
  } catch (e) {
    noop();
  }

  return false;
}
function isString(value) {
  return isType(value, 'string');
}
function isArray(value) {
  return Array.isArray(value);
}
function isObject(value) {
  return isType(value, Object);
}
function isDefined(value) {
  return value != null;
}
function isInteger(nVal) {
  return typeof nVal === 'number' && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal;
} // Polyfill for the isInteger function that will be added in ES6
// http://wiki.ecmascript.org/doku.php?id=harmony:number.isinteger

/* istanbul ignore if  */

if (!Number.isInteger) {
  Number.isInteger = isInteger;
}

function isNumeric(nVal) {
  return typeof nVal === 'number' && isFinite(nVal) && nVal - parseFloat(nVal) + 1 >= 0;
}
function contains(item, list) {
  var listToCheck = isArray(list) && list || [];
  return listToCheck.indexOf(item) >= 0;
}
var isEmpty = function isEmpty(list) {
  return list.length === 0;
};
/**
 * @deprecated Use isValidUid from the `uid.js` file.
 */

function isValidUid(value) {
  return value && value.length === 11;
}
var hasKeys = function hasKeys(object) {
  return object && Object.keys(object).length > 0;
};
function areDefinedAndEqual(left, right) {
  return isDefined(left) && isDefined(right) && right === left;
}
var toBe = function toBe(left, right) {
  return left === right;
};
var toBeAny = function toBeAny(values) {
  return function (left) {
    return values.some(function (right) {
      return toBe(left, right);
    });
  };
};
var isNullUndefinedOrEmptyString = toBeAny([undefined, null, '']);
var isFunction = function isFunction(fun) {
  return typeof fun === 'function';
};
var hasOwnProperty = function hasOwnProperty(object, propertyName) {
  return Object.prototype.hasOwnProperty.call(object, propertyName);
}; // The logical mode to use when having multiple filters.
// Default is AND.
// See https://docs.dhis2.org/master/en/developer/html/webapi_metadata_object_filter.html

var rootJunctions = ['OR', 'AND'];
var isValidRootJunction = toBeAny(rootJunctions);
function checkValidRootJunction(rootJunction) {
  checkType(rootJunction, 'string', 'rootJunction');

  if (isValidRootJunction(rootJunction)) {
    return true;
  }

  throw new Error("Expected ".concat(rootJunction, " to be one of [").concat(rootJunctions, "]"));
}

/***/ }),

/***/ "./src/lib/utils.js":
/*!**************************!*\
  !*** ./src/lib/utils.js ***!
  \**************************/
/*! exports provided: throwError, curry, addLockedProperty, copyOwnProperties, pick, pickOr, Deferred, updateAPIUrlWithBaseUrlVersionNumber, customEncodeURIComponent, identity */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throwError", function() { return throwError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "curry", function() { return curry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addLockedProperty", function() { return addLockedProperty; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "copyOwnProperties", function() { return copyOwnProperties; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pick", function() { return pick; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pickOr", function() { return pickOr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Deferred", function() { return Deferred; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateAPIUrlWithBaseUrlVersionNumber", function() { return updateAPIUrlWithBaseUrlVersionNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "customEncodeURIComponent", function() { return customEncodeURIComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "identity", function() { return identity; });
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

/**
 * @module lib/utils
 */
function throwError(message) {
  throw new Error(message);
} // TODO: Throw an error when `toCurry` is not a function

function curry(toCurry, parameter) {
  return function curried() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return toCurry.apply(this, [parameter].concat(args));
  };
}
function addLockedProperty(object, name, value) {
  var propertyDescriptor = {
    enumerable: true,
    configurable: false,
    writable: false,
    value: value
  };
  Object.defineProperty(object, name, propertyDescriptor);
}
function copyOwnProperties(to, from) {
  Object.keys(from).filter(function (key) {
    return from.hasOwnProperty(key);
  }).forEach(function (key) {
    to[key] = from[key];
  });
  return to;
}
/**
 * Curried get function to pick a property from an object
 * Will safely pick a property from an object and guards against the infamous "can not read property of undefined".
 *
 * @param {String} propertyPath
 * @param {Any} defaultValue A default value to be returned when no value was found at the path
 * @returns Function
 *
 * get :: String -> Object -> Any
 */

function pick(propertyPath) {
  var propertiesToGet = propertyPath.split('.');
  return function (item) {
    return propertiesToGet.reduce(function (result, property) {
      if (result) {
        return result[property];
      }

      return undefined;
    }, item);
  };
}
var pickOr = function pickOr(pathProperty, defaultValue) {
  return function (item) {
    var pathResult = pick(pathProperty)(item);
    return pathResult !== undefined ? pathResult : defaultValue;
  };
};
var Deferred =
/*#__PURE__*/
function () {
  function Deferred() {
    var _this = this;

    _classCallCheck(this, Deferred);

    this.promise = new Promise(function (resolve, reject) {
      _this.resolve = resolve;
      _this.reject = reject;
    });
  }

  _createClass(Deferred, null, [{
    key: "create",
    value: function create() {
      return new Deferred();
    }
  }]);

  return Deferred;
}(); // eslint-disable-next-line complexity

function updateAPIUrlWithBaseUrlVersionNumber(apiUrl, baseUrl) {
  if (!baseUrl || !apiUrl) {
    return apiUrl;
  }

  var apiUrlWithVersionRexExp = /api\/([1-9][0-9])/;
  var apiVersionMatch = baseUrl.match(apiUrlWithVersionRexExp);
  var baseUrlHasVersion = apiVersionMatch && apiVersionMatch[1];
  var apiUrlHasVersion = apiUrl && !apiUrlWithVersionRexExp.test(apiUrl);

  if (baseUrlHasVersion && apiUrlHasVersion) {
    var version = apiVersionMatch[1]; // Inject the current api version number into the endPoint urls

    return apiUrl.replace(/api/, "api/".concat(version));
  }

  return apiUrl;
} // Define our very own special list of characters that we don't want to encode in the URI

var whitelistURI = ',&$=/;:';
var whitelistURICodes = whitelistURI.split('').map(function (c) {
  return encodeURIComponent(c);
});
var whitelistRegExp = new RegExp("(?:".concat(whitelistURICodes.join('|'), ")"), 'g');
/**
 * Encode all invalid URI characters, except the ones we've decided we don't want to
 */

function customEncodeURIComponent(uri) {
  // return uri;
  return encodeURIComponent(uri).replace(whitelistRegExp, decodeURIComponent);
}
function identity(value) {
  return value;
}

/***/ }),

/***/ "./src/logger/Logger.js":
/*!******************************!*\
  !*** ./src/logger/Logger.js ***!
  \******************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../lib/check */ "./src/lib/check.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }



var Logger =
/*#__PURE__*/
function () {
  function Logger(logging) {
    _classCallCheck(this, Logger);

    Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkType"])(logging, 'object', 'console');
    this.logger = logging;
  }

  _createClass(Logger, [{
    key: "canLog",
    value: function canLog(type) {
      return !!(type && console && Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["isType"])(this.logger[type], 'function'));
    }
  }, {
    key: "logMessage",
    value: function logMessage() {
      var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'log';

      if (this.canLog(type) && this.logger[type]) {
        var _this$logger;

        for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          rest[_key - 1] = arguments[_key];
        }

        (_this$logger = this.logger)[type].apply(_this$logger, rest);

        return true;
      }

      return false;
    }
  }, {
    key: "debug",
    value: function debug() {
      for (var _len2 = arguments.length, rest = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        rest[_key2] = arguments[_key2];
      }

      return this.logMessage.apply(this, ['debug'].concat(rest));
    }
  }, {
    key: "error",
    value: function error() {
      for (var _len3 = arguments.length, rest = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
        rest[_key3] = arguments[_key3];
      }

      return this.logMessage.apply(this, ['error'].concat(rest));
    }
  }, {
    key: "log",
    value: function log() {
      for (var _len4 = arguments.length, rest = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
        rest[_key4] = arguments[_key4];
      }

      return this.logMessage.apply(this, ['log'].concat(rest));
    }
  }, {
    key: "warn",
    value: function warn() {
      for (var _len5 = arguments.length, rest = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
        rest[_key5] = arguments[_key5];
      }

      return this.logMessage.apply(this, ['warn'].concat(rest));
    }
  }], [{
    key: "getLogger",
    value: function getLogger() {
      var logger; // TODO: This is not very clean try to figure out a better way to do this.

      try {
        // Node version
        logger = global.console;
      } catch (e) {
        // Browser version fallback

        /* istanbul ignore next */
        logger = window.console;
      }

      if (this.logger) {
        return this.logger;
      }

      return this.logger = new Logger(logger);
    }
  }]);

  return Logger;
}();

/* harmony default export */ __webpack_exports__["default"] = (Logger);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js")))

/***/ }),

/***/ "./src/model/Filter.js":
/*!*****************************!*\
  !*** ./src/model/Filter.js ***!
  \*****************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../lib/check */ "./src/lib/check.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }


var FILTER_COMPARATORS = {
  /**
   * @function equals
   * @memberof module:model.Filter.prototype
   * @returns {Filter} Returns the modified filter for chaining
   *
   * @description
   * This method can be used to add a equals filter value
   */
  equals: 'eq',

  /**
   * @function like
   * @memberof module:model.Filter.prototype
   * @returns {Filter} Returns the modified filter for chaining
   *
   * @description
   * This method can be used to add a like filter value
   */
  like: 'like',

  /**
   * @function ilike
   * @memberof module:model.Filter.prototype
   * @returns {Filter} Returns the modified filter for chaining
   *
   * @description
   * This method can be used to add a ilike filter value
   */
  ilike: 'ilike',

  /**
   * @function
   * @memberof module:model.Filter.prototype
   * @returns {Filter} Returns the modified filter for chaining
   *
   * @description
   * This method can be used to add a ne filter value
   */
  notEqual: 'ne',

  /**
   * @function
   * @memberof module:model.Filter.prototype
   * @returns {Filter} Returns the modified filter for chaining
   *
   * @description
   * This method can be used to add a in filter value
   */
  in: 'in',

  /**
   * @function
   * @memberof module:model.Filter.prototype
   * @returns {Filter} Returns the modified filter for chaining
   *
   * @description
   * This method can be used to add a tokens filter value
   */
  token: 'token',

  /**
   * @function
   * @memberof module:model.Filter.prototype
   * @returns {Filter} Returns the modified filter for chaining
   *
   * @description
   * This method can be used to add a !in filter value
   */
  notIn: '!in',

  /**
   * @function
   * @memberof module:model.Filter.prototype
   * @returns {Filter} Returns the modified filter for chaining
   *
   * @description
   * This method can be used to add a !token filter value
   */
  nToken: '!token'
  /**
   * Filter class that can be used to build api endpoint filters using a semi-natural language style.
   *
   * @memberof module:model
   */

};

var Filter =
/*#__PURE__*/
function () {
  /**
   * @constructor
   * @param {Function} addFilterCallback Callback that will be used to notify Filters that the filter is completed
   * so it can be added to the list of filters.
   */
  function Filter(addFilterCallback) {
    _classCallCheck(this, Filter);

    this.addFilterCallback = addFilterCallback;
    this.propertyName = 'name';
    this.comparator = 'like';
    this.filterValue = undefined;
  }
  /**
   * @param {String} propertyName Property name that the filter should be applied on.
   * @returns {Filter}
   */


  _createClass(Filter, [{
    key: "on",
    value: function on(propertyName) {
      Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkDefined"])(propertyName, 'Property name to filter on');
      this.propertyName = propertyName;
      return this;
    }
    /**
     * Utility function used to get the query parameter value in a DHIS2 metadata filter format that can be
     * send to the api. This returned value is appended to the `filter=` part of the query.
     *
     * @private
     * @note {warning} Usually not used directly and only used by Filters to create the query param values.
     *
     * @returns {string} The query param value to be appended to `filter=`
     */

  }, {
    key: "getQueryParamFormat",
    value: function getQueryParamFormat() {
      return [this.propertyName, this.comparator, this.filterValue].join(':');
    }
    /**
     * @static
     *
     * @param {Function} addFilterCallback Callback to be called when the filter is completed.
     *
     * @returns {Filter} A instance of the Filter class that can be used to create
     * filters.
     *
     * @description
     * Create a filter instance
     */

  }, {
    key: "operator",

    /**
     * Utility function to add an operator with filterValue
     * @param {*} operator to use
     * @param {*} filterValue to filter on
     */
    value: function operator(_operator, filterValue) {
      Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkDefined"])(_operator, 'operator');
      Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkDefined"])(filterValue, 'filterValue');
      this.comparator = _operator;
      this.filterValue = filterValue;
      return this.addFilterCallback(this);
    }
  }], [{
    key: "getFilter",
    value: function getFilter(addFilterCallback) {
      return new Filter(addFilterCallback);
    }
  }]);

  return Filter;
}(); // Add the filters to the Filter prototype


Object.keys(FILTER_COMPARATORS).forEach(function (filter) {
  Object.defineProperty(Filter.prototype, filter, {
    value: function filterGetter(filterValue) {
      Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkDefined"])(filterValue, 'filterValue');
      this.comparator = FILTER_COMPARATORS[filter];
      this.filterValue = [FILTER_COMPARATORS.in, FILTER_COMPARATORS.notIn].includes(this.comparator) ? "[".concat(filterValue.join(','), "]") : filterValue;
      return this.addFilterCallback(this);
    }
  });
});
/* harmony default export */ __webpack_exports__["default"] = (Filter);

/***/ }),

/***/ "./src/model/Filters.js":
/*!******************************!*\
  !*** ./src/model/Filters.js ***!
  \******************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../lib/check */ "./src/lib/check.js");
/* harmony import */ var _lib_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../lib/utils */ "./src/lib/utils.js");
/* harmony import */ var _Filter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Filter */ "./src/model/Filter.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }




/**
 * @description
 * Collection class that contains filters that are to be applied when loading Model objects from the api.
 *
 * @memberof module:model
 */

var Filters =
/*#__PURE__*/
function () {
  /**
   * Creates a new Filters instance.
   *
   * The Filters instance keeps a list of all the applied filters for a modelDefinition.
   *
   * @param {ModelDefinition} modelDefinition The ModelDefinition for which this Filters object should create filters.
   * @param {Filter[]} filters A list of Filter objects
   */
  function Filters(modelDefinition) {
    var filters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

    _classCallCheck(this, Filters);

    /**
     * @type {Array<Filter>}
     * @private
     */
    this.filters = filters;
    this.modelDefinition = modelDefinition;
    this.rootJunction = null;
  }
  /**
   * Shortcut for triggering the creation of a Filter. This is the function that is triggered when creating new
   * filters on a ModelDefinition. The Filter will receive a callback that can be used to add the finalized filter
   * to the list of filters.
   *
   * @param {string} propertyName The property that the filter should apply to. (e.g. `name`)
   * @returns {Filter} The created filter object for `propertyName`.
   */


  _createClass(Filters, [{
    key: "on",
    value: function on(propertyName) {
      var addFilter = this.add.bind(this);
      return _Filter__WEBPACK_IMPORTED_MODULE_2__["default"].getFilter(addFilter).on(propertyName);
    }
    /**
     * Utility method to add a filter to the list of filters.
     *
     * @private
     * @param {Filter} filter The Filter to be added to the list of current filters.
     * @returns {ModelDefinition} The modelDefiniton that the filter applies to. This is used to support calling `.list()`
     * on the modelDefinition after the filter was created.
     * @throws {TypeError} Thrown when the given filter is not a Filter object.
     */

  }, {
    key: "add",
    value: function add(filter) {
      if (!Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["isType"])(filter, _Filter__WEBPACK_IMPORTED_MODULE_2__["default"])) {
        throw new TypeError('filter should be an instance of Filter');
      }

      this.filters.push(filter);
      return this.modelDefinition;
    }
    /**
     * @deprecated
     * @returns {Promise} Proxy the list() call on the filters object.
     */

  }, {
    key: "list",
    value: function list() {
      return this.modelDefinition.list();
    }
    /**
     * Get an array of DHIS2 metadata filter values to send to the API.
     *
     * This will return ['id:eq:UYXOT4A7JMI', 'name:like:ANC'] for filters created as follows
     * dataElement
     *  .filter().on('id').equals(UYXOT4A7JMI)
     *  .filter().on('name').like('ANC')
     *
     * @returns {Array<string>} A list of query param values to be used with the filter key.
     */

  }, {
    key: "getQueryFilterValues",
    value: function getQueryFilterValues() {
      return this.filters.map(function (filter) {
        return filter.getQueryParamFormat();
      });
    }
    /**
     * @deprecated Deprecated since 2.28, use getQueryFilterValues instead.
     * @returns {Array.<string>}
     */

  }, {
    key: "getFilters",
    value: function getFilters() {
      return this.getQueryFilterValues();
    }
    /**
     * Get a list of Filter objects that are in applied in this Filters instance
     *
     * @returns {Array<Filter>} The list of Filter objects.
     */

  }, {
    key: "getFilterList",
    value: function getFilterList() {
      return this.filters.map(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["identity"]);
    }
    /**
     * The logic mode to use on the filters.
     *
     * Default behavior is AND.
     * Note that the logic will be used across all the filters, which
     * means with OR, results will be returned when any of the filter match.
     * It MUST be called last on the chain of filters when called
     * through modelDefinition.filter().
     * @see {@link https://docs.dhis2.org/master/en/developer/html/webapi_metadata_object_filter.html|Object filter Docs }
     * @example
     * d2.programs.filter().on('name').like('Child')
     * .filter().logicMode('OR').on('code').equals('Child')
     * @param {string} junction The logic operator to use. One of ['OR', 'AND'];
     */

  }, {
    key: "logicMode",
    value: function logicMode(junction) {
      Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkValidRootJunction"])(junction);
      this.rootJunction = junction;
      return this;
    }
    /**
     * Factory method to create a Filters object.
     *
     * @param {ModelDefinition} modelDefinition The modelDefinition that the filters should apply to.
     * @param {Filter[]} priorFilters List of previously applied filters that the new filter list should start with.
     * @returns {Filters} A Filters object for the given modelDefinition.
     */

  }], [{
    key: "getFilters",
    value: function getFilters(modelDefinition) {
      var priorFilters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
      return new Filters(modelDefinition, priorFilters);
    }
  }]);

  return Filters;
}();

/* harmony default export */ __webpack_exports__["default"] = (Filters);

/***/ }),

/***/ "./src/model/Model.js":
/*!****************************!*\
  !*** ./src/model/Model.js ***!
  \****************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../lib/check */ "./src/lib/check.js");
/* harmony import */ var _lib_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../lib/utils */ "./src/lib/utils.js");
/* harmony import */ var _ModelBase__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ModelBase */ "./src/model/ModelBase.js");
/* harmony import */ var _helpers_attibutes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./helpers/attibutes */ "./src/model/helpers/attibutes.js");
function _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); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }





var pickAttributeValues = Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["pickOr"])('attributeValues', []); // TODO: Perhaps we can generate model classes dynamically based on the schemas and inherit from this.

/**
 * @extends ModelBase
 *
 * @description
 * A Model represents an object from the DHIS2 Api. A model is created based of a ModelDefinition. The ModelDefinition
 * has the properties that the model should have.
 *
 * @memberof module:model
 */

var Model =
/*#__PURE__*/
function (_ModelBase) {
  _inherits(Model, _ModelBase);

  /**
   * @constructor
   *
   * @param {ModelDefinition} modelDefinition The model definition that corresponds with the model.
   * This is essential defining what type the model is representing.
   *
   * @description
   * Will create a new model instanced based on the model definition. When creating a new instance the model
   * definition needs to have both the modelValidations and modelProperties.
   *
   * The model properties will depend on the ModelDefinition. A model definition is based on a DHIS2 Schema.
   */
  function Model(modelDefinition) {
    var _this;

    _classCallCheck(this, Model);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(Model).call(this));
    Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkType"])(modelDefinition, 'object', 'modelDefinition');
    Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkType"])(modelDefinition.modelProperties, 'object', 'modelProperties');
    /**
     * @property {ModelDefinition} modelDefinition Stores reference to the modelDefinition that was used when
     * creating the model. This property is not enumerable or writable and will therefore not show up when looping
     * over the object properties.
     */

    Object.defineProperty(_assertThisInitialized(_this), 'modelDefinition', {
      value: modelDefinition
    });
    /**
     * @property {Boolean} dirty Represents the state of the model. When the model is concidered `dirty`
     * there are pending changes.
     * This property is not enumerable or writable and will therefore not show up when looping
     * over the object properties.
     */

    Object.defineProperty(_assertThisInitialized(_this), 'dirty', {
      writable: true,
      value: false
    });
    /**
     * @private
     * @property {Object} dataValues Values object used to store the actual model values. Normally access to the
     * Model data will be done through accessor properties that are generated from the modelDefinition.
     *
     * @note {warning} This should not be accessed directly.
     */

    Object.defineProperty(_assertThisInitialized(_this), 'dataValues', {
      configurable: true,
      writable: true,
      value: {}
    });
    /**
     * Attach the modelDefinition modelProperties (the properties from the schema) onto the Model.
     *
     * For a data element model the modelProperties would be the following
     * https://play.dhis2.org/demo/api/schemas/dataElement.json?fields=properties
     */

    Object.defineProperties(_assertThisInitialized(_this), modelDefinition.modelProperties);
    var attributes = {};
    var attributeProperties = modelDefinition.attributeProperties;

    if (Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["hasKeys"])(attributeProperties)) {
      /**
       * @property {Object} attributes The attributes objects contains references to custom attributes defined
       * on the metadata object.
       *
       * @description
       * These properties are generated based of the attributes that are created for the the specific schema.
       * As these properties are not defined on the schemas they're put on a separate attributes object.
       * When there are no attributes defined for the object type, the attributes property will not be attached
       * to the model.
       *
       * @see https://docs.dhis2.org/2.27/en/user/html/dhis2_user_manual_en_full.html#manage_attribute
       */
      Object.defineProperty(_assertThisInitialized(_this), 'attributes', {
        value: attributes
      });

      var getAttributeValues = function getAttributeValues() {
        return pickAttributeValues(_assertThisInitialized(_this));
      };

      var setAttributeValues = function setAttributeValues(attributeValues) {
        return _this.attributeValues = attributeValues;
      };

      var setDirty = function setDirty() {
        return _this.dirty = true;
      };

      var attributeDefinitions = Object(_helpers_attibutes__WEBPACK_IMPORTED_MODULE_3__["default"])(attributeProperties, getAttributeValues, setAttributeValues, setDirty);
      Object.defineProperties(attributes, attributeDefinitions);
    }

    _this[_ModelBase__WEBPACK_IMPORTED_MODULE_2__["DIRTY_PROPERTY_LIST"]] = new Set([]);
    return _this;
  }
  /**
   * @static
   *
   * @param {ModelDefinition} modelDefinition ModelDefinition from which the model should be created
   * @returns {Model} Returns an instance of the model.
   *
   * @description The static method is a factory method to create Model objects. It calls `new Model()` with the passed `ModelDefinition`.
   *
   * ```js
   * let myModel = Model.create(modelDefinition);
   * ```
   */


  _createClass(Model, null, [{
    key: "create",
    value: function create(modelDefinition) {
      return new Model(modelDefinition);
    }
  }]);

  return Model;
}(_ModelBase__WEBPACK_IMPORTED_MODULE_2__["default"]);

/* harmony default export */ __webpack_exports__["default"] = (Model);

/***/ }),

/***/ "./src/model/ModelBase.js":
/*!********************************!*\
  !*** ./src/model/ModelBase.js ***!
  \********************************/
/*! exports provided: DIRTY_PROPERTY_LIST, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DIRTY_PROPERTY_LIST", function() { return DIRTY_PROPERTY_LIST; });
/* harmony import */ var _ModelValidation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ModelValidation */ "./src/model/ModelValidation.js");
/* harmony import */ var _helpers_json__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./helpers/json */ "./src/model/helpers/json.js");
/* harmony import */ var _helpers_models__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./helpers/models */ "./src/model/helpers/models.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }




var modelValidator = _ModelValidation__WEBPACK_IMPORTED_MODULE_0__["default"].getModelValidation();
var DIRTY_PROPERTY_LIST = Symbol('List to keep track of dirty properties');
/**
 * Base class that supplies functionality to the Model classes
 *
 * @memberof module:model
 */

var ModelBase =
/*#__PURE__*/
function () {
  function ModelBase() {
    _classCallCheck(this, ModelBase);

    var modelValidations = {
      modelValidations: {}
    };
    Object.defineProperty(this, 'modelDefinition', {
      writable: true,
      value: modelValidations
    });
  }
  /**
   * @returns {Promise} Returns a promise that resolves when the model has been saved or rejected with the result from
   * the `validate()` call.
   *
   * @definition
   * Will save model as a new object to the server using a POST request. This method would generally be used if
   * you're creating models with pre-specified IDs. Note that this does not check if the model is marked as dirty.
   */


  _createClass(ModelBase, [{
    key: "create",
    value: function create() {
      var _this = this;

      return this.validate().then(function (validationState) {
        if (!validationState.status) {
          return Promise.reject(validationState);
        }

        return _this.modelDefinition.saveNew(_this).then(function (apiResponse) {
          return _helpers_models__WEBPACK_IMPORTED_MODULE_2__["updateModelFromResponseStatus"].call(_this, apiResponse);
        });
      });
    }
    /**
     * @returns {Promise} Returns a promise that resolves when the model has been saved
     * or rejects with the result from the `validate()` call.
     *
     * @description
     * Checks if the model is dirty. When the model is dirty it will check if the values of the model are valid by calling
     * `validate`. If this is correct it will attempt to save the [Model](#/model/Model) to the api.
     *
     * ```js
     * myModel.save()
     *   .then((message) => console.log(message));
     * ```
     */

  }, {
    key: "save",
    value: function save(includeChildren) {
      var _this2 = this;

      // Calling save when there's nothing to be saved is a no-op
      if (!this.isDirty(includeChildren)) {
        return Promise.resolve({});
      }

      return this.validate().then(function (validationState) {
        if (!validationState.status) {
          return Promise.reject(validationState);
        }

        return _this2.modelDefinition.save(_this2).then(function (apiResponse) {
          return _helpers_models__WEBPACK_IMPORTED_MODULE_2__["updateModelFromResponseStatus"].call(_this2, apiResponse);
        });
      });
    }
    /**
     * @returns {Promise} Promise that resolves with an object with a status property that represents if the model
     * is valid or not the fields array will return the names of the fields that are invalid.
     *
     * @description
     * This will run the validations on the properties which have validations set. Normally these validations are defined
     * through the DHIS2 schema. It will check min/max for strings/numbers etc. Additionally it will
     * run model validations against the schema.
     *
     * ```js
     * myModel.validate()
     *  .then(myModelStatus => {
     *    if (myModelStatus.status === false) {
     *      myModelStatus.fields.forEach((fieldName) => console.log(fieldName));
     *    }
     * });
     * ```
     *
     * @deprecated The api now validates the object on save, so doing the additional request to validate the object
     * is not very useful anymore as the validation on POST/PUT is more extensive than the /api/schemas validation.
     */

  }, {
    key: "validate",
    value: function validate() {
      var _this3 = this;

      return new Promise(function (resolve, reject) {
        var validationMessages = [];

        function unique(current, property) {
          if (property && current.indexOf(property) === -1) {
            current.push(property);
          }

          return current;
        }

        function asyncRemoteValidation(model) {
          return modelValidator.validateAgainstSchema(model);
        } // Run async validation against the api


        asyncRemoteValidation(_this3).catch(function (remoteMessages) {
          // Errors are ok in this case
          if (Array.isArray(remoteMessages)) {
            return remoteMessages;
          }

          return Promise.reject(remoteMessages);
        }).then(function (remoteMessages) {
          validationMessages = validationMessages.concat(remoteMessages);
          var validationState = {
            status: remoteMessages.length === 0,
            fields: validationMessages.map(function (validationMessage) {
              return validationMessage.property;
            }).reduce(unique, []),
            messages: validationMessages
          };
          resolve(validationState);
        }).catch(function (message) {
          return reject(message);
        });
      });
    } // TODO: Cloning large graphs is very slow

  }, {
    key: "clone",
    value: function clone() {
      var modelClone = this.modelDefinition.create(Object(_helpers_json__WEBPACK_IMPORTED_MODULE_1__["getJSONForProperties"])(this, Object.keys(this.modelDefinition.modelValidations), true));

      if (this.isDirty()) {
        modelClone.dirty = this.isDirty(true);
      }

      return modelClone;
    }
    /**
     * Deletes the object from the server.
     *
     * This will fire a DELETE request to have the object be removed from the system.
     *
     * @returns {Promise} Resolves when the object was successfully deleted.
     */

  }, {
    key: "delete",
    value: function _delete() {
      return this.modelDefinition.delete(this);
    }
    /**
     * Check if the model is in a dirty state and is a candidate to be saved.
     *
     * It will check for direct properties that have been changed and if any of the children have been changed.
     *
     * @param {boolean} includeChildren If set to false only the models direct properties will be checked.
     * @returns {boolean} Returns true when the model is in a dirty state.
     */

  }, {
    key: "isDirty",
    value: function isDirty() {
      var includeChildren = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      return this.dirty || includeChildren === true && this.hasDirtyChildren();
    }
    /**
     * Utility method to reset the dirty state of the object.
     *
     * This is called after a successful save operation was done.
     *
     * @returns {ModelBase} Returns itself for potential chaining
     */

  }, {
    key: "resetDirtyState",
    value: function resetDirtyState() {
      this.dirty = false; // Also set it's children to be clean

      this.getDirtyChildren().forEach(function (value) {
        if (value.resetDirtyState) {
          value.resetDirtyState();
        } else {
          value.dirty = false;
        }
      });
      this[DIRTY_PROPERTY_LIST].clear();
      return this;
    }
    /**
     * Returns a list of properties that have been changed.
     *
     * @returns {Array<string>} The names of the properties that were changed.
     */

  }, {
    key: "getDirtyPropertyNames",
    value: function getDirtyPropertyNames() {
      return Array.from(this[DIRTY_PROPERTY_LIST].values());
    }
    /**
     * This will return the properties that are marked as `owner: true` in the schema definition for the model.
     *
     * @returns {Array<any>} Returns an array of properties that are owned by the object
     */
    // TODO: This name is very misleading and should probably be renamed to something like `getOwnerProperties` (would be a breaking change)

  }, {
    key: "getCollectionChildren",
    value: function getCollectionChildren() {
      var _this4 = this;

      return Object.keys(this).filter(function (propertyName) {
        return _this4[propertyName] && Object(_helpers_models__WEBPACK_IMPORTED_MODULE_2__["hasModelValidationForProperty"])(_this4, propertyName) && Object(_helpers_models__WEBPACK_IMPORTED_MODULE_2__["pickOwnerFromModelValidation"])(propertyName, _this4);
      }).map(function (propertyName) {
        return _this4[propertyName];
      });
    }
    /**
     * Gets the names of the properties that are collections on the object.
     *
     * These are usually the properties that contain ModelCollectionProperties.
     *
     * @returns {Array<string>} A list of property names that are marked as type `COLLECTION` in the schema.
     */

  }, {
    key: "getCollectionChildrenPropertyNames",
    value: function getCollectionChildrenPropertyNames() {
      var _this5 = this;

      return Object.keys(this).filter(function (propertyName) {
        return Object(_helpers_models__WEBPACK_IMPORTED_MODULE_2__["pickTypeFromModelValidation"])(propertyName, _this5) === 'COLLECTION';
      });
    }
    /**
     * Gets the names of the properties that are references on the object.
     *
     * These are usually the properties that contain a Model of a different type. (e.g DataElement -> CategoryCombo)
     *
     * @returns {Array<string>} A list of property names that are marked as type `REFERENCE` in the schema.
     */

  }, {
    key: "getReferenceProperties",
    value: function getReferenceProperties() {
      var _this6 = this;

      return Object.keys(this).filter(function (propertyName) {
        return Object(_helpers_models__WEBPACK_IMPORTED_MODULE_2__["pickTypeFromModelValidation"])(propertyName, _this6) === 'REFERENCE' && Object(_helpers_models__WEBPACK_IMPORTED_MODULE_2__["pickEmbeddedObjectFromModelValidation"])(propertyName, _this6) === false;
      });
    }
    /**
     * Gets the names of the properties that are embedded objects.
     *
     * These the properties that are not represented by a different Model, but are just plain objects that are
     * embedded within the current object.
     *
     * @returns {Array<string>} A list of property names of embedded objects.
     */

  }, {
    key: "getEmbeddedObjectCollectionPropertyNames",
    value: function getEmbeddedObjectCollectionPropertyNames() {
      var _this7 = this;

      return this.getCollectionChildrenPropertyNames().filter(function (propertyName) {
        return Object(_helpers_models__WEBPACK_IMPORTED_MODULE_2__["pickEmbeddedObjectFromModelValidation"])(propertyName, _this7);
      });
    }
    /**
     * Returns a list of child properties that are marked as dirty. This uses the `getCollectionChildren()` method
     * to retrieve the children properties and then checks if they are marked as dirty.
     *
     * The method does not check if direct properties are dirty as those are tracked on the Model itself.
     *
     * @returns {Array<any>}
     */

  }, {
    key: "getDirtyChildren",
    value: function getDirtyChildren() {
      return this.getCollectionChildren().filter(function (property) {
        return property && property.dirty === true;
      });
    }
    /**
     * Check if any of the Model's child collections are dirty.
     *
     * @returns {boolean} True when one of the children is dirty.
     */

  }, {
    key: "hasDirtyChildren",
    value: function hasDirtyChildren() {
      return this.getDirtyChildren().length > 0;
    }
    /**
     * This method is generally intended to, by default, usefully serialize Model objects during JSON serialization.
     *
     * This method will take all the properties that are defined on the schema and create an object with the keys and
     * values for those properties. This will remove any circular dependencies that could have occurred otherwise.
     *
     * @returns {Object}
     */

  }, {
    key: "toJSON",
    value: function toJSON() {
      return Object(_helpers_json__WEBPACK_IMPORTED_MODULE_1__["getJSONForProperties"])(this, Object.keys(this.modelDefinition.modelValidations));
    }
  }]);

  return ModelBase;
}();

/* harmony default export */ __webpack_exports__["default"] = (ModelBase);

/***/ }),

/***/ "./src/model/ModelCollection.js":
/*!**************************************!*\
  !*** ./src/model/ModelCollection.js ***!
  \**************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../lib/check */ "./src/lib/check.js");
/* harmony import */ var _lib_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../lib/utils */ "./src/lib/utils.js");
/* harmony import */ var _Model__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Model */ "./src/model/Model.js");
/* harmony import */ var _ModelDefinition__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ModelDefinition */ "./src/model/ModelDefinition.js");
/* harmony import */ var _pager_Pager__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../pager/Pager */ "./src/pager/Pager.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }







function _throwIfContainsOtherThanModelObjects(values) {
  if (values && values[Symbol.iterator]) {
    var toCheck = _toConsumableArray(values);

    toCheck.forEach(function (value) {
      if (!(value instanceof _Model__WEBPACK_IMPORTED_MODULE_2__["default"])) {
        Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["throwError"])('Values of a ModelCollection must be instances of Model');
      }
    });
  }
}

function _throwIfContainsModelWithoutUid(values) {
  if (values && values[Symbol.iterator]) {
    var toCheck = _toConsumableArray(values);

    toCheck.forEach(function (value) {
      if (!Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["isValidUid"])(value.id)) {
        Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["throwError"])('Can not add a Model without id to a ModelCollection');
      }
    });
  }
}
/**
 * Collection of `Model` objects that can be interacted upon. Can contain a pager object to easily navigate
 * pages within the system.
 *
 * @memberof module:model
 */


var ModelCollection =
/*#__PURE__*/
function () {
  /**
   * @constructor
   *
   * @param {ModelDefinition} modelDefinition The `ModelDefinition` that this collection is for. This defines the type of models that
   * are allowed to be added to the collection.
   * @param {Model[]} values Initial values that should be added to the collection.
   * @param {Object} pagerData Object with pager data. This object contains data that will be put into the `Pager` instance.
   *
   * @description
   *
   * Creates a new `ModelCollection` object based on the passed `modelDefinition`. Additionally values can be added by passing
   * `Model` objects in the `values` parameter. The collection also exposes a pager object which can be used to navigate through
   * the pages in the collection. For more information see the `Pager` class.
   */
  function ModelCollection(modelDefinition, values, pagerData) {
    var _this = this;

    _classCallCheck(this, ModelCollection);

    Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkType"])(modelDefinition, _ModelDefinition__WEBPACK_IMPORTED_MODULE_3__["default"]);
    /**
     * @property {ModelDefinition} modelDefinition The `ModelDefinition` that this collection is for. This defines the type of models that
     * are allowed to be added to the collection.
     */

    this.modelDefinition = modelDefinition;
    /**
     * @property {Pager} pager Pager object that is created from the pagerData that was passed when the collection was constructed. If no pager data was present
     * the pager will have default values.
     */

    this.pager = new _pager_Pager__WEBPACK_IMPORTED_MODULE_4__["default"](pagerData, modelDefinition); // We can not extend the Map object right away in v8 contexts.

    this.valuesContainerMap = new Map();
    this[Symbol.iterator] = this.valuesContainerMap[Symbol.iterator].bind(this.valuesContainerMap);

    _throwIfContainsOtherThanModelObjects(values);

    _throwIfContainsModelWithoutUid(values); // Add the values separately as not all Iterators return the same values


    if (Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["isArray"])(values)) {
      values.forEach(function (value) {
        return _this.valuesContainerMap.set(value.id, value);
      });
    }
  }
  /**
   * @property {Number} size The number of Model objects that are in the collection.
   *
   * @description
   * Contains the number of Model objects that are in this collection. If the collection is a collection with a pager. This
   * does not take into account all the items in the database. Therefore when a pager is present on the collection
   * the size will return the items on that page. To get the total number of items consult the pager.
   */


  _createClass(ModelCollection, [{
    key: "add",

    /**
     * Adds a Model instance to the collection. The model is checked if it is a correct instance of `Model` and if it has
     * a valid id. A valid id is a uid string of 11 alphanumeric characters.
     *
     * @param {Model} value Model instance to add to the collection.
     * @returns {ModelCollection} Returns itself for chaining purposes.
     *
     * @throws {Error} When the passed value is not an instance of `Model`
     * @throws {Error} Throws error when the passed value does not have a valid id.
     */
    value: function add(value) {
      _throwIfContainsOtherThanModelObjects([value]);

      _throwIfContainsModelWithoutUid([value]);

      this.set(value.id, value);
      return this;
    }
    /**
     * If working with the Map type object is inconvenient this method can be used to return the values
     * of the collection as an Array object.
     *
     * @returns {Array} Returns the values of the collection as an array.
     */

  }, {
    key: "toArray",
    value: function toArray() {
      var resultArray = [];
      this.forEach(function (model) {
        resultArray.push(model);
      });
      return resultArray;
    }
  }, {
    key: "clear",

    /**
     * Clear the collection and remove all it's values.
     *
     * @returns {this} Returns itself for chaining purposes;
     */
    // TODO: Reset the pager?
    value: function clear() {
      return this.valuesContainerMap.clear.call(this.valuesContainerMap);
    }
  }, {
    key: "delete",
    value: function _delete() {
      var _this$valuesContainer;

      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      return (_this$valuesContainer = this.valuesContainerMap.delete).call.apply(_this$valuesContainer, [this.valuesContainerMap].concat(args));
    }
  }, {
    key: "entries",
    value: function entries() {
      return this.valuesContainerMap.entries.call(this.valuesContainerMap);
    } // FIXME: This calls the forEach function with the values Map and not with the ModelCollection as the third argument

  }, {
    key: "forEach",
    value: function forEach() {
      var _this$valuesContainer2;

      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }

      return (_this$valuesContainer2 = this.valuesContainerMap.forEach).call.apply(_this$valuesContainer2, [this.valuesContainerMap].concat(args));
    }
  }, {
    key: "get",
    value: function get() {
      var _this$valuesContainer3;

      for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
        args[_key3] = arguments[_key3];
      }

      return (_this$valuesContainer3 = this.valuesContainerMap.get).call.apply(_this$valuesContainer3, [this.valuesContainerMap].concat(args));
    }
  }, {
    key: "has",
    value: function has() {
      var _this$valuesContainer4;

      for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
        args[_key4] = arguments[_key4];
      }

      return (_this$valuesContainer4 = this.valuesContainerMap.has).call.apply(_this$valuesContainer4, [this.valuesContainerMap].concat(args));
    }
  }, {
    key: "keys",
    value: function keys() {
      return this.valuesContainerMap.keys.call(this.valuesContainerMap);
    }
  }, {
    key: "set",
    value: function set() {
      var _this$valuesContainer5;

      for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
        args[_key5] = arguments[_key5];
      }

      return (_this$valuesContainer5 = this.valuesContainerMap.set).call.apply(_this$valuesContainer5, [this.valuesContainerMap].concat(args));
    }
  }, {
    key: "values",
    value: function values() {
      return this.valuesContainerMap.values.call(this.valuesContainerMap);
    }
  }, {
    key: "size",
    get: function get() {
      return this.valuesContainerMap.size;
    }
  }], [{
    key: "create",
    value: function create(modelDefinition, values, pagerData) {
      return new ModelCollection(modelDefinition, values, pagerData);
    }
  }, {
    key: "throwIfContainsOtherThanModelObjects",
    value: function throwIfContainsOtherThanModelObjects(value) {
      return _throwIfContainsOtherThanModelObjects(value);
    }
  }, {
    key: "throwIfContainsModelWithoutUid",
    value: function throwIfContainsModelWithoutUid(value) {
      return _throwIfContainsModelWithoutUid(value);
    }
  }]);

  return ModelCollection;
}();

/* harmony default export */ __webpack_exports__["default"] = (ModelCollection);

/***/ }),

/***/ "./src/model/ModelCollectionProperty.js":
/*!**********************************************!*\
  !*** ./src/model/ModelCollectionProperty.js ***!
  \**********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
/* harmony import */ var _ModelCollection__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ModelCollection */ "./src/model/ModelCollection.js");
function _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); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }

function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }



/**
 * A ModelCollectionProperty instance is a ModelCollection that is a property of
 * a model instance. ModelCollectionProperties can be operated on independently of
 * the Model that owns them.
 *
 * @memberof module:model
 */

var ModelCollectionProperty =
/*#__PURE__*/
function (_ModelCollection) {
  _inherits(ModelCollectionProperty, _ModelCollection);

  /**
   * @constructor
   *
   * @param {Model} parentModel The `Model` of the parent of this `ModelCollectionProperty`
   * @param {ModelDefinition} modelDefinition The `ModelDefinition` that this `ModelCollection` property is for
   * @param {String} propName The name of this property on the parent model
   * @param {Model[]|boolean} values Initial values that should be added to the collection property
   * @param {Api} api The class to use for API calls
   *
   * @description
   *
   * Creates a new `ModelCollectionProperty` object. This is a subclass of `ModelCollection`, which adds logic
   * for adding and removing elements to the collection and saving the changes to the API.
   *
   * If the value is `true` or `undefined` is specified instead of an array of data values, this indicates that the
   * collection contains (or may contain) data that has not yet been loaded from the API.
   */
  function ModelCollectionProperty(parentModel, modelDefinition, propName, values, api) {
    var _this;

    _classCallCheck(this, ModelCollectionProperty);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(ModelCollectionProperty).call(this, modelDefinition, values, undefined)); // The name of this property on the parent object - necessary for loading values lazily

    _this.propName = propName; // Dirty bit - true if any models have been added to or removed from the collection

    _this.dirty = false; // Keep track of added and removed elements

    _this.added = new Set();
    _this.removed = new Set(); // Using field transformers, it's possible to query the API for the presence of data without actually fetching
    // the data. For instance this is used to determine if an organization unit has any children without actually
    // loading the children. If yes, it will be displayed as an expandable branch within the tree.
    // For more information, see the documentation about field transformers, specifically the isNotEmpty operator:
    // https://docs.dhis2.org/master/en/developer/html/dhis2_developer_manual_full.html#webapi_field_transformers

    _this.hasUnloadedData = values === true || values === undefined;
    _this.api = api; // Store the parent model of this collection so we can construct the URI for API calls

    _this.parentModel = parentModel;
    return _this;
  }
  /**
   * @param {Model} value Model instance to add to the collection.
   * @returns {ModelCollectionProperty} Returns itself for chaining purposes.
   *
   * @description
   * Calls the `add` method on the parent `ModelCollection` class, and then performs checks to keep track of
   * what, if any, changes that have been made to the collection.
   */


  _createClass(ModelCollectionProperty, [{
    key: "add",
    value: function add(value) {
      if (this.valuesContainerMap.has(value.id)) {
        return this;
      }

      _get(_getPrototypeOf(ModelCollectionProperty.prototype), "add", this).call(this, value);

      if (this.removed.has(value.id)) {
        this.removed.delete(value.id);
      } else {
        this.added.add(value.id);
      }

      this.updateDirty();
      return this;
    }
    /**
     * If the collection contains an object with the same id as the `value` parameter, that object is removed
     * from the collection. Checks are then performed to keep track of what, if any, changes that have been
     * made to the collection.
     *
     * @param {Model} value Model instance to remove from the collection.
     * @returns {ModelCollectionProperty} Returns itself for chaining purposes.
     */

  }, {
    key: "remove",
    value: function remove(value) {
      _ModelCollection__WEBPACK_IMPORTED_MODULE_1__["default"].throwIfContainsOtherThanModelObjects([value]);
      _ModelCollection__WEBPACK_IMPORTED_MODULE_1__["default"].throwIfContainsModelWithoutUid([value]);

      if (this.delete(value.id)) {
        if (this.added.has(value.id)) {
          this.added.delete(value.id);
        } else {
          this.removed.add(value.id);
        }
      }

      this.updateDirty();
      return this;
    }
    /**
     * Checks whether any changes have been made to the collection, and updates the dirty flag accordingly.
     *
     * @returns {boolean} True if the collection has changed, false otherwise.
     */

  }, {
    key: "updateDirty",
    value: function updateDirty() {
      this.dirty = this.added.size > 0 || this.removed.size > 0;
      return this.dirty;
    }
    /**
     * Sets dirty=false and resets the added and removed sets used for dirty state tracking.
     */

  }, {
    key: "resetDirtyState",
    value: function resetDirtyState() {
      this.dirty = false;
      this.added = new Set();
      this.removed = new Set();
    }
    /**
     * Checks if the collection property has been modified.
     * @param {boolean} [includeValues=true] If true, also checks if any models in the collection
     * has been edited by checking the dirty flag on each model.
     * @returns {boolean} true if any elements have been added to or removed from the collection
     */

  }, {
    key: "isDirty",
    value: function isDirty() {
      var includeValues = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;

      if (includeValues) {
        return this.dirty || this.toArray().filter(function (model) {
          return model && model.isDirty() === true;
        }).length > 0;
      }

      return this.dirty;
    }
    /**
     * If any changes have been made to the collection, these changes will be submitted to the API. The returned
     * promise will resolve successfully when the changes have been saved to the API, and will be rejected if
     * either the changes weren't saved or if there were no changes to save.
     *
     * @returns {Promise} A `Promise`
     */

  }, {
    key: "save",
    value: function save() {
      var _this2 = this;

      // Calling save when there's nothing to be saved is a no-op (not an error)
      if (!this.isDirty()) {
        return Promise.resolve({});
      }

      var url = [this.parentModel.href, this.modelDefinition.plural].join('/');
      var data = {
        additions: Array.from(this.added).map(function (id) {
          return {
            id: id
          };
        }),
        deletions: Array.from(this.removed).map(function (id) {
          return {
            id: id
          };
        })
      };
      return this.api.post(url, data).then(function () {
        _this2.resetDirtyState();

        return Promise.resolve({});
      }).catch(function (err) {
        return Promise.reject('Failed to alter collection:', err);
      });
    }
  }, {
    key: "load",
    value: function load(options) {
      var _this3 = this;

      var forceReload = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

      if (!this.hasUnloadedData && !forceReload) {
        return Promise.resolve(this);
      }

      var url = [this.parentModel.modelDefinition.apiEndpoint, this.parentModel.id].join('/');
      var requestOptions = Object.assign({
        paging: false
      }, options, {
        fields: "".concat(this.propName, "[").concat(options && options.fields || ':all', "]")
      });
      return this.api.get(url, requestOptions).then(function (data) {
        return data[_this3.propName];
      }).then(function (values) {
        if (Array.isArray(values)) {
          _this3.valuesContainerMap.clear();

          values.forEach(function (value) {
            return _this3.valuesContainerMap.set(value.id, _this3.modelDefinition.create(value));
          });
        }

        _this3.hasUnloadedData = false;
        return Promise.resolve(_this3);
      });
    }
    /**
     * See `ModelCollectionProperty.constructor`.
     *
     * @param {Model} parentModel
     * @param {ModelDefinition} modelDefinition
     * @param {Model[]} values
     * @returns {ModelCollectionProperty}
     */

  }], [{
    key: "create",
    value: function create(parentModel, modelDefinition, propName, values) {
      return new ModelCollectionProperty(parentModel, modelDefinition, propName, values, _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi());
    }
  }]);

  return ModelCollectionProperty;
}(_ModelCollection__WEBPACK_IMPORTED_MODULE_1__["default"]);

/* harmony default export */ __webpack_exports__["default"] = (ModelCollectionProperty);

/***/ }),

/***/ "./src/model/ModelDefinition.js":
/*!**************************************!*\
  !*** ./src/model/ModelDefinition.js ***!
  \**************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../lib/check */ "./src/lib/check.js");
/* harmony import */ var _lib_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../lib/utils */ "./src/lib/utils.js");
/* harmony import */ var _ModelDefinitions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ModelDefinitions */ "./src/model/ModelDefinitions.js");
/* harmony import */ var _Model__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Model */ "./src/model/Model.js");
/* harmony import */ var _ModelCollection__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ModelCollection */ "./src/model/ModelCollection.js");
/* harmony import */ var _ModelCollectionProperty__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./ModelCollectionProperty */ "./src/model/ModelCollectionProperty.js");
/* harmony import */ var _lib_SchemaTypes__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../lib/SchemaTypes */ "./src/lib/SchemaTypes.js");
/* harmony import */ var _Filters__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Filters */ "./src/model/Filters.js");
/* harmony import */ var _ModelBase__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./ModelBase */ "./src/model/ModelBase.js");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./config */ "./src/model/config/index.js");
/* harmony import */ var _helpers_json__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./helpers/json */ "./src/model/helpers/json.js");
function _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); }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }

function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }













function createModelPropertyDescriptor(propertiesObject, schemaProperty) {
  var propertyName = schemaProperty.collection ? schemaProperty.collectionName : schemaProperty.name;
  var propertyDetails = {
    // Actual property descriptor properties
    configurable: false,
    enumerable: true,
    get: function get() {
      return this.dataValues[propertyName];
    }
  }; // Store available constants for ENUM type properties

  if (schemaProperty.constants) {
    propertyDetails.constants = schemaProperty.constants;
  } // Only add a setter for writable properties


  if (schemaProperty.writable) {
    propertyDetails.set = function dynamicPropertySetter(value) {
      // TODO: Objects and Arrays are considered unequal when their data is the same and therefore trigger a dirty
      if (!Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["isObject"])(value) && value !== this.dataValues[propertyName] || Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["isObject"])(value)) {
        this.dirty = true;
        this[_ModelBase__WEBPACK_IMPORTED_MODULE_8__["DIRTY_PROPERTY_LIST"]].add(propertyName);
        this.dataValues[propertyName] = value;
      }
    };
  }

  if (propertyName) {
    propertiesObject[propertyName] = propertyDetails;
  }
}

function createPropertiesObject(schemaProperties) {
  var propertiesObject = {};
  var createModelPropertyDescriptorOn = Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["curry"])(createModelPropertyDescriptor, propertiesObject);
  (schemaProperties || []).forEach(createModelPropertyDescriptorOn);
  return propertiesObject;
} // eslint-disable-next-line complexity


function createValidationSetting(validationObject, schemaProperty) {
  var propertyName = schemaProperty.collection ? schemaProperty.collectionName : schemaProperty.name;
  var validationDetails = {
    persisted: schemaProperty.persisted,
    type: _lib_SchemaTypes__WEBPACK_IMPORTED_MODULE_6__["default"].typeLookup(schemaProperty.propertyType),
    required: schemaProperty.required,
    min: schemaProperty.min,
    max: schemaProperty.max,
    owner: schemaProperty.owner,
    unique: schemaProperty.unique,
    writable: schemaProperty.writable,
    ordered: Boolean(schemaProperty.ordered),
    embeddedObject: Boolean(schemaProperty.embeddedObject)
  };

  function getReferenceTypeFrom(property) {
    if (property.href) {
      return property.href.split('/').pop();
    }

    return undefined;
  } // Add a referenceType to be able to get a hold of the reference objects model.


  if (validationDetails.type === 'REFERENCE' || validationDetails.type === 'COLLECTION' && schemaProperty.itemPropertyType === 'REFERENCE') {
    validationDetails.referenceType = getReferenceTypeFrom(schemaProperty);
  }

  if (propertyName) {
    validationObject[propertyName] = validationDetails;
  }
}

function createValidations(schemaProperties) {
  var validationsObject = {};
  var createModelPropertyOn = Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["curry"])(createValidationSetting, validationsObject);
  (schemaProperties || []).forEach(createModelPropertyOn);
  return validationsObject;
}

function shouldBeModelCollectionProperty(model, models) {
  // eslint-disable-next-line complexity
  return function shouldBeModelCollectionPropertyIterator(modelProperty) {
    return model && models && model.modelDefinition && model.modelDefinition.modelValidations && model.modelDefinition.modelValidations[modelProperty] && model.modelDefinition.modelValidations[modelProperty].type === 'COLLECTION' && models.hasOwnProperty(model.modelDefinition.modelValidations[modelProperty].referenceType);
  };
}

function isAnUpdate(modelToCheck) {
  return Boolean(modelToCheck.id);
}

var translatableProperties = new WeakMap();
/**
 * Definition of a Model. Basically this object contains the meta data related to the Model. Like `name`, `apiEndPoint`, `modelValidation`, etc.
 * It also has methods to create and load Models that are based on this definition. The Data element `ModelDefinition` would be used to create Data Element `Model`s
 *
 * Note: ModelDefinition has a property `api` that is used for the communication with the dhis2 api. The value of this
 * property is an instance of `Api`.
 *
 * @memberof module:model
 */

var ModelDefinition =
/*#__PURE__*/
function () {
  // eslint-disable-next-line complexity
  function ModelDefinition() {
    var schema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var properties = arguments.length > 1 ? arguments[1] : undefined;
    var validations = arguments.length > 2 ? arguments[2] : undefined;
    var attributes = arguments.length > 3 ? arguments[3] : undefined;
    var authorities = arguments.length > 4 ? arguments[4] : undefined;

    _classCallCheck(this, ModelDefinition);

    Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkType"])(schema.singular, 'string');
    Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkType"])(schema.plural, 'string', 'Plural');
    Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["addLockedProperty"])(this, 'name', schema.singular);
    Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["addLockedProperty"])(this, 'displayName', schema.displayName);
    Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["addLockedProperty"])(this, 'plural', schema.plural);
    Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["addLockedProperty"])(this, 'isShareable', schema.shareable || false);
    Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["addLockedProperty"])(this, 'isMetaData', schema.metadata || false);
    Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["addLockedProperty"])(this, 'apiEndpoint', schema.apiEndpoint);
    Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["addLockedProperty"])(this, 'javaClass', schema.klass);
    Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["addLockedProperty"])(this, 'identifiableObject', schema && schema.identifiableObject);
    Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["addLockedProperty"])(this, 'modelProperties', properties);
    Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["addLockedProperty"])(this, 'modelValidations', validations);
    Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["addLockedProperty"])(this, 'attributeProperties', attributes);
    Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["addLockedProperty"])(this, 'authorities', authorities);
    Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["addLockedProperty"])(this, 'translatable', schema.translatable || false);
    this.filters = _Filters__WEBPACK_IMPORTED_MODULE_7__["default"].getFilters(this);
    translatableProperties.set(this, (schema.properties || []).filter(function (prop) {
      return prop.translationKey;
    }).map(function (_ref) {
      var name = _ref.name,
          translationKey = _ref.translationKey;
      return {
        name: name,
        translationKey: translationKey
      };
    })); // TODO: The function getOwnedPropertyJSON should probably not be exposed, perhaps we could have a getJSONForModel(ownedPropertiesOnly=true) method.

    this.getOwnedPropertyJSON = _helpers_json__WEBPACK_IMPORTED_MODULE_10__["getOwnedPropertyJSON"].bind(this);
  }

  _createClass(ModelDefinition, [{
    key: "filter",
    value: function filter() {
      return this.clone().filters;
    }
    /**
     * Creates a fresh Model instance based on the `ModelDefinition`. If data is passed into the method that
     * data will be loaded into the matching properties of the model.
     *
     * @param {Object} [data] Data values that should be loaded into the model.
     *
     * @returns {Model} Returns the newly created model instance.
     *
     * @example
     * dataElement.create({name: 'ANC', id: 'd2sf33s3ssf'});
     */

  }, {
    key: "create",
    value: function create(data) {
      var model = _Model__WEBPACK_IMPORTED_MODULE_3__["default"].create(this);
      var models = _ModelDefinitions__WEBPACK_IMPORTED_MODULE_2__["default"].getModelDefinitions();
      var dataValues = data ? Object.assign({}, data) : Object(_config__WEBPACK_IMPORTED_MODULE_9__["getDefaultValuesForModelType"])(model.modelDefinition.name);
      Object.keys(model).filter(shouldBeModelCollectionProperty(model, models)).forEach(function (modelProperty) {
        var referenceType = model.modelDefinition.modelValidations[modelProperty].referenceType;
        var values = [];

        if (Array.isArray(dataValues[modelProperty])) {
          values = dataValues[modelProperty].map(function (value) {
            return models[referenceType].create(value);
          });
        } else if (dataValues[modelProperty] === true || dataValues[modelProperty] === undefined) {
          values = dataValues[modelProperty];
        }

        dataValues[modelProperty] = _ModelCollectionProperty__WEBPACK_IMPORTED_MODULE_5__["default"].create(model, models[referenceType], modelProperty, values);
        model.dataValues[modelProperty] = dataValues[modelProperty];
      });
      Object.keys(model).filter(function (modelProperty) {
        return !shouldBeModelCollectionProperty(model, models)(modelProperty);
      }).forEach(function (modelProperty) {
        model.dataValues[modelProperty] = dataValues[modelProperty];
      });
      return model;
    }
  }, {
    key: "clone",
    value: function clone() {
      var ModelDefinitionPrototype = Object.getPrototypeOf(this);
      var priorFilters = this.filters.getFilterList();
      var clonedDefinition = Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["copyOwnProperties"])(Object.create(ModelDefinitionPrototype), this);
      clonedDefinition.filters = _Filters__WEBPACK_IMPORTED_MODULE_7__["default"].getFilters(clonedDefinition, priorFilters);
      return clonedDefinition;
    }
    /**
     * Get a `Model` instance from the api loaded with data that relates to `identifier`.
     * This will do an API call and return a Promise that resolves with a `Model` or rejects with the api error message.
     *
     * @param {String} identifier
     * @param {Object} [queryParams={fields: ':all'}] Query parameters that should be passed to the GET query.
     * @returns {Promise} Resolves with a `Model` instance or an error message.
     *
     * @example
     * //Do a get request for the dataElement with given id (d2sf33s3ssf) and print it's name
     * //when that request is complete and the model is loaded.
     * dataElement.get('d2sf33s3ssf')
     *   .then(model => console.log(model.name));
     */

  }, {
    key: "get",
    value: function get(identifier) {
      var _this = this;

      var queryParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
        fields: ':all,attributeValues[:all,attribute[id,name,displayName]]'
      };
      Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkDefined"])(identifier, 'Identifier');

      if (Array.isArray(identifier)) {
        return this.list({
          filter: ["id:in:[".concat(identifier.join(','), "]")]
        });
      } // TODO: should throw error if API has not been defined


      return this.api.get([this.apiEndpoint, identifier].join('/'), queryParams).then(function (data) {
        return _this.create(data);
      }).catch(function (response) {
        if (response.message) {
          return Promise.reject(response.message);
        }

        return Promise.reject(response);
      });
    }
    /**
     * Loads a list of models.
     *
     * @param {Object} [listParams={fields: ':all'}] Query parameters that should be passed to the GET query.
     * @returns {Promise} ModelCollection collection of models objects of the `ModelDefinition` type.
     *
     * @example
     * // Loads a list of models and prints their name.
     * dataElement.list()
     *   .then(modelCollection => {
     *     modelCollection.forEach(model => console.log(model.name));
     *   });
     */

  }, {
    key: "list",
    value: function list() {
      var _this2 = this;

      var listParams = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      var apiEndpoint = listParams.apiEndpoint,
          extraParams = _objectWithoutProperties(listParams, ["apiEndpoint"]);

      var definedRootJunction = this.filters.rootJunction ? {
        rootJunction: this.filters.rootJunction
      } : {};
      var params = Object.assign({
        fields: ':all'
      }, definedRootJunction, extraParams);
      var definedFilters = this.filters.getQueryFilterValues();

      if (!Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["isDefined"])(params.filter)) {
        delete params.filter;

        if (definedFilters.length) {
          params.filter = definedFilters;
        }
      } // If listParams.apiEndpoint exists, send the request there in stead of this.apiEndpoint


      return this.api.get(apiEndpoint || this.apiEndpoint, params).then(function (responseData) {
        return _ModelCollection__WEBPACK_IMPORTED_MODULE_4__["default"].create(_this2, responseData[_this2.plural].map(function (data) {
          return _this2.create(data);
        }), Object.assign(responseData.pager || {}, {
          query: params
        }));
      });
    }
    /**
     * This method is used by the `Model` instances to save the model when calling `model.save()`.
     *
     * @param {Model} model The model that should be saved to the server.
     * @returns {Promise} A promise which resolves when the save was successful
     * or rejects when it failed. The promise will resolve with the data that is
     * returned from the server.
     *
     * @note {warning} This should generally not be called directly.
     */
    // TODO: check the return status of the save to see if it was actually successful and not ignored

  }, {
    key: "save",
    value: function save(model) {
      if (isAnUpdate(model)) {
        var jsonPayload = _helpers_json__WEBPACK_IMPORTED_MODULE_10__["getOwnedPropertyJSON"].bind(this)(model); // Fallback to modelDefinition if href is unavailable

        var updateUrl = model.dataValues.href ? Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["updateAPIUrlWithBaseUrlVersionNumber"])(model.dataValues.href, this.api.baseUrl) : [model.modelDefinition.apiEndpoint, model.dataValues.id].join('/'); // Save the existing model

        return this.api.update(updateUrl, jsonPayload, true);
      }

      return this.saveNew(model);
    }
  }, {
    key: "saveNew",
    value: function saveNew(model) {
      var jsonPayload = _helpers_json__WEBPACK_IMPORTED_MODULE_10__["getOwnedPropertyJSON"].bind(this)(model); // Its a new object

      return this.api.post(this.apiEndpoint, jsonPayload);
    }
    /**
     * This method returns a list of property names that that are defined
     * as "owner" properties on this schema. This means these properties are used
     * when saving the model to the server.
     *
     * @returns {String[]} Returns an array of property names.
     *
     * @example
     * dataElement.getOwnedPropertyNames()
     */

  }, {
    key: "getOwnedPropertyNames",
    value: function getOwnedPropertyNames() {
      var _this3 = this;

      return Object.keys(this.modelValidations).filter(function (propertyName) {
        return _this3.modelValidations[propertyName].owner;
      });
    }
    /**
     * This method is used by the `Model` instances to delete the model when calling `model.delete()`.
     *
     * @returns {Promise} Returns a promise to the deletion operation
     *
     * @note {warning} This should generally not be called directly.
     */

  }, {
    key: "delete",
    value: function _delete(model) {
      if (model.dataValues.href) {
        return this.api.delete(model.dataValues.href);
      }

      return this.api.delete([model.modelDefinition.apiEndpoint, model.dataValues.id].join('/'));
    }
    /**
     * Check for if the Model supports translations
     *
     * @returns {Boolean} True when the schema can be translated, false otherwise
     */

  }, {
    key: "isTranslatable",
    value: function isTranslatable() {
      return this.translatable;
    }
    /**
     * These properties can be translated using the DHIS2 _database_ translations.
     *
     * @returns {String[]} Returns a list of property names on the object that are translatable.
     */

  }, {
    key: "getTranslatableProperties",
    value: function getTranslatableProperties() {
      return translatableProperties.get(this).map(Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["pick"])('name'));
    }
    /**
     * This method is similar to getTranslatableProperties() but in addition to the property names also returns the
     * `translationKey` that is used to save the translations for the property names.
     *
     * @returns {Object[]} Returns an array with objects that have `name` and `translationKey` properties.
     */

  }, {
    key: "getTranslatablePropertiesWithKeys",
    value: function getTranslatablePropertiesWithKeys() {
      return translatableProperties.get(this);
    }
    /**
     * @static
     *
     * This method creates a new `ModelDefinition` based on a JSON structure called
     * a schema. A schema represents the structure of a domain model as it is
     * required by DHIS. Since these schemas can not be altered on the server from
     * the modelDefinition is frozen to prevent accidental changes to the definition.
     *
     * @param {Object} schema A schema definition received from the web api (/api/schemas)
     * @param {Object[]} attributes A list of attribute objects that describe custom attributes (/api/attributes)
     *
     * @returns {ModelDefinition} Frozen model definition object.
     *
     * @example
     * ModelDefinition.createFromSchema(schemaDefinition, attributes);
     *
     * @note {info} An example of a schema definition can be found on
     * https://apps.dhis2.org/demo/api/schemas/dataElement
     */

  }], [{
    key: "createFromSchema",
    value: function createFromSchema(schema) {
      var attributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
      var ModelDefinitionClass;
      Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkType"])(schema, Object, 'Schema');

      if (typeof ModelDefinition.specialClasses[schema.singular] === 'function') {
        ModelDefinitionClass = ModelDefinition.specialClasses[schema.singular];
      } else {
        ModelDefinitionClass = ModelDefinition;
      }

      return Object.freeze(new ModelDefinitionClass(schema, Object.freeze(createPropertiesObject(schema.properties)), Object.freeze(createValidations(schema.properties)), attributes.reduce(function (current, attributeDefinition) {
        current[attributeDefinition.name] = attributeDefinition;
        return current;
      }, {}), schema.authorities));
    }
  }]);

  return ModelDefinition;
}();

var UserModelDefinition =
/*#__PURE__*/
function (_ModelDefinition) {
  _inherits(UserModelDefinition, _ModelDefinition);

  function UserModelDefinition() {
    _classCallCheck(this, UserModelDefinition);

    return _possibleConstructorReturn(this, _getPrototypeOf(UserModelDefinition).apply(this, arguments));
  }

  _createClass(UserModelDefinition, [{
    key: "get",
    // TODO: userCredentials should always be included, no matter what the query params, that is currently not the case
    value: function get(identifier) {
      var queryParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
        fields: ':all,userCredentials[:owner]'
      };
      return _get(_getPrototypeOf(UserModelDefinition.prototype), "get", this).call(this, identifier, queryParams);
    }
  }]);

  return UserModelDefinition;
}(ModelDefinition);

var DataSetModelDefinition =
/*#__PURE__*/
function (_ModelDefinition2) {
  _inherits(DataSetModelDefinition, _ModelDefinition2);

  function DataSetModelDefinition() {
    _classCallCheck(this, DataSetModelDefinition);

    return _possibleConstructorReturn(this, _getPrototypeOf(DataSetModelDefinition).apply(this, arguments));
  }

  _createClass(DataSetModelDefinition, [{
    key: "create",
    value: function create() {
      var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var hasData = Boolean(Object.keys(data).length); // Filter out the compulsoryDataElementOperands structure from the retrieved data
      // This structure does not follow the convention of a typical reference. We can not create a proper
      // ModelCollection for this collection.

      var dataClone = Object.keys(data).filter(function (key) {
        return key !== 'compulsoryDataElementOperands';
      }).reduce(function (obj, key) {
        obj[key] = data[key];
        return obj;
      }, {}); // Create the model using the usual way of creating a model
      // Only pass data when there is data in the object passed to the constructor. This will guarantee
      // that the empty ModelCollections are created properly.

      var model = _get(_getPrototypeOf(DataSetModelDefinition.prototype), "create", this).call(this, hasData ? dataClone : undefined); // Set the compulsoryDataElementOperands onto the dataValues so it will be included during the save operations


      model.dataValues.compulsoryDataElementOperands = data.compulsoryDataElementOperands;
      return model;
    }
  }]);

  return DataSetModelDefinition;
}(ModelDefinition);

var OrganisationUnitModelDefinition =
/*#__PURE__*/
function (_ModelDefinition3) {
  _inherits(OrganisationUnitModelDefinition, _ModelDefinition3);

  function OrganisationUnitModelDefinition() {
    _classCallCheck(this, OrganisationUnitModelDefinition);

    return _possibleConstructorReturn(this, _getPrototypeOf(OrganisationUnitModelDefinition).apply(this, arguments));
  }

  _createClass(OrganisationUnitModelDefinition, [{
    key: "list",
    // If a 'root' is specified when listing organisation units the results will be limited to the root and its
    // descendants. This is special behavior for the organisation unit API endpoint, which is documented here:
    // https://dhis2.github.io/dhis2-docs/master/en/developer/html/webapi_organisation_units.html
    value: function list() {
      var extraParams = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      var root = extraParams.root,
          params = _objectWithoutProperties(extraParams, ["root"]);

      if (extraParams.hasOwnProperty('root') && root) {
        params.apiEndpoint = "".concat(this.apiEndpoint, "/").concat(root);
      }

      return _get(_getPrototypeOf(OrganisationUnitModelDefinition.prototype), "list", this).call(this, params);
    }
  }]);

  return OrganisationUnitModelDefinition;
}(ModelDefinition);

ModelDefinition.specialClasses = {
  user: UserModelDefinition,
  dataSet: DataSetModelDefinition,
  organisationUnit: OrganisationUnitModelDefinition
};
/* harmony default export */ __webpack_exports__["default"] = (ModelDefinition);

/***/ }),

/***/ "./src/model/ModelDefinitions.js":
/*!***************************************!*\
  !*** ./src/model/ModelDefinitions.js ***!
  \***************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../lib/check */ "./src/lib/check.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }


/**
 * Contains all the `ModelDefinition`s that are available. The definitions are properties on the object.
 * This would be used as a main entry point to do any interaction.
 *
 * After calling the initialise function `d2({baseUrl: 'dhis/api'})` this object is the `models` property
 * that allows you to access
 *
 * @example
 * models.dataElement.getList();
 *
 * @memberof module:model
 */

var ModelDefinitions =
/*#__PURE__*/
function () {
  function ModelDefinitions() {
    _classCallCheck(this, ModelDefinitions);
  }

  _createClass(ModelDefinitions, [{
    key: "add",
    // TODO: Elaborate this documentation

    /**
     * This will allow you to add your own custom ModelDefinitions.
     *
     * The Definition object should have the following properties
     * `modelName, modelNamePlural, modelOptions, properties, validations`
     *
     * @param {ModelDefinition} modelDefinition Add a model definition to the definitions collection
     *
     * @example
     * models.add({name: 'MyDefinition', plural: 'MyDefinitions', endPointname: '/myDefinition'});
     */
    value: function add(modelDefinition) {
      try {
        Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkType"])(modelDefinition.name, 'string');
      } catch (e) {
        throw new Error('Name should be set on the passed ModelDefinition to add one');
      }

      if (this[modelDefinition.name]) {
        throw new Error(['Model', modelDefinition.name, 'already exists'].join(' '));
      }

      this[modelDefinition.name] = modelDefinition;

      if (Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["isType"])(modelDefinition.plural, 'string')) {
        this[modelDefinition.plural] = modelDefinition;
      }
    }
    /**
     * Map through the modelDefinitions like you would with a simple `Array.map()`
     *
     * @param {Function} transformer Transformer function that will be run for each `ModelDefinition`
     * @returns {Array} Array with the `ModelDefinition` objects.
     *
     * @example
     * models.mapThroughDefinitions(definition => console.log(definition.name);
     *
     * @note {info} When mapping through the definition list `transformer` is called with the just the definition
     * Unlike other map functions, no index or the full object is being passed.
     *
     * @note {warn} The resulting array contains references to the actual objects. It does not work like immutable array functions.
     *
     */

  }, {
    key: "mapThroughDefinitions",
    value: function mapThroughDefinitions(transformer) {
      var _this = this;

      Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkType"])(transformer, 'function', 'transformer');
      return Object.keys(this).filter(function (modelDefinition) {
        return _this.hasOwnProperty(modelDefinition) && !(_this[modelDefinition].plural === modelDefinition);
      }).map(function (modelDefinition) {
        return transformer(_this[modelDefinition]);
      });
    }
  }]);

  return ModelDefinitions;
}(); // Model definitions singleton!


function getModelDefinitions() {
  if (getModelDefinitions.modelDefinitions) {
    return getModelDefinitions.modelDefinitions;
  }

  return getModelDefinitions.modelDefinitions = new ModelDefinitions();
}

ModelDefinitions.getModelDefinitions = getModelDefinitions;
/* harmony default export */ __webpack_exports__["default"] = (ModelDefinitions);

/***/ }),

/***/ "./src/model/ModelValidation.js":
/*!**************************************!*\
  !*** ./src/model/ModelValidation.js ***!
  \**************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../lib/check */ "./src/lib/check.js");
/* harmony import */ var _logger_Logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../logger/Logger */ "./src/logger/Logger.js");
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
/* harmony import */ var _helpers_json__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./helpers/json */ "./src/model/helpers/json.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }






function extractValidationViolations(webmessage) {
  if (webmessage.response && webmessage.response.errorReports) {
    return webmessage.response.errorReports;
  }

  throw new Error('Response was not a WebMessage with the expected format');
}
/**
 * Handles validation of Model objects based on their modelDefinition.
 *
 * @memberof module:model
 */


var ModelValidation =
/*#__PURE__*/
function () {
  function ModelValidation(providedLogger) {
    _classCallCheck(this, ModelValidation);

    Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["checkType"])(providedLogger, 'object', 'logger (Logger)');
    this.logger = providedLogger;
  }
  /**
   * @deprecated Client side model validation is deprecated in favour of server side validation only.
   *
   * @returns {{status: boolean, messages: Array}} Returns {status: true, messages: []}
   */


  _createClass(ModelValidation, [{
    key: "validate",
    value: function validate() {
      this.logger.warn('Client side model validation is deprecated');
      throw new Error('Client side model validation is deprecated');
    }
    /**
     * Sends a POST request against the `api/schemas` endpoint to check if the model is valid.
     *
     * @param {Model} model The model that should be validated.
     * @returns {Array} Returns an array with validation messages if there are any.
     *
     * @note {warn} Currently only checks
     */

  }, {
    key: "validateAgainstSchema",
    value: function validateAgainstSchema(model) {
      if (!(model && model.modelDefinition && model.modelDefinition.name)) {
        return Promise.reject('model.modelDefinition.name can not be found');
      }

      var url = "schemas/".concat(model.modelDefinition.name); // TODO: The function getOwnedPropertyJSON should probably not be exposed, perhaps we could have a getJSONForModel(ownedPropertiesOnly=true) method.

      return _api_Api__WEBPACK_IMPORTED_MODULE_2__["default"].getApi().post(url, Object(_helpers_json__WEBPACK_IMPORTED_MODULE_3__["getOwnedPropertyJSON"])(model)).then(function (webMessage) {
        if (webMessage.status === 'OK') {
          return [];
        }

        return Promise.reject(webMessage);
      }).catch(extractValidationViolations);
    }
    /**
     * Returns the `ModelValidation` singleton. Creates a new one if it does not yet exist.
     * Grabs a logger instance by calling `Logger.getLogger`
     *
     * @returns {ModelValidation} New or memoized instance of `ModelInstance`
     */

  }], [{
    key: "getModelValidation",
    value: function getModelValidation() {
      if (this.modelValidation) {
        return this.modelValidation;
      }

      return this.modelValidation = new ModelValidation(_logger_Logger__WEBPACK_IMPORTED_MODULE_1__["default"].getLogger(console));
    }
  }]);

  return ModelValidation;
}();

/* harmony default export */ __webpack_exports__["default"] = (ModelValidation);

/***/ }),

/***/ "./src/model/config/index.js":
/*!***********************************!*\
  !*** ./src/model/config/index.js ***!
  \***********************************/
/*! exports provided: defaultValues, getDefaultValuesForModelType, fieldsForSchemas */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultValues", function() { return defaultValues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDefaultValuesForModelType", function() { return getDefaultValuesForModelType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fieldsForSchemas", function() { return fieldsForSchemas; });
/* harmony import */ var _model_defaults_organisationUnitGroupSet__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./model-defaults/organisationUnitGroupSet */ "./src/model/config/model-defaults/organisationUnitGroupSet.js");
/* harmony import */ var _model_defaults_category__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./model-defaults/category */ "./src/model/config/model-defaults/category.js");
/* harmony import */ var _model_defaults_categoryOptionGroupSet__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./model-defaults/categoryOptionGroupSet */ "./src/model/config/model-defaults/categoryOptionGroupSet.js");
/* harmony import */ var _model_defaults_dataElement__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./model-defaults/dataElement */ "./src/model/config/model-defaults/dataElement.js");
/* harmony import */ var _model_defaults_dataElementGroupSet__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./model-defaults/dataElementGroupSet */ "./src/model/config/model-defaults/dataElementGroupSet.js");
/* harmony import */ var _model_defaults_dataSet__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./model-defaults/dataSet */ "./src/model/config/model-defaults/dataSet.js");
/* harmony import */ var _model_defaults_externalMapLayer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./model-defaults/externalMapLayer */ "./src/model/config/model-defaults/externalMapLayer.js");
/* harmony import */ var _model_defaults_validationNotificationTemplate__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./model-defaults/validationNotificationTemplate */ "./src/model/config/model-defaults/validationNotificationTemplate.js");
/* harmony import */ var _model_defaults_validationRule__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./model-defaults/validationRule */ "./src/model/config/model-defaults/validationRule.js");
/* harmony import */ var _model_defaults_program__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./model-defaults/program */ "./src/model/config/model-defaults/program.js");
/* harmony import */ var _model_defaults_programNotificationTemplate__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./model-defaults/programNotificationTemplate */ "./src/model/config/model-defaults/programNotificationTemplate.js");











var defaultValues = new Map([['organisationUnitGroupSet', _model_defaults_organisationUnitGroupSet__WEBPACK_IMPORTED_MODULE_0__["default"]], ['category', _model_defaults_category__WEBPACK_IMPORTED_MODULE_1__["default"]], ['categoryOptionGroupSet', _model_defaults_categoryOptionGroupSet__WEBPACK_IMPORTED_MODULE_2__["default"]], ['dataElement', _model_defaults_dataElement__WEBPACK_IMPORTED_MODULE_3__["default"]], ['dataElementGroupSet', _model_defaults_dataElementGroupSet__WEBPACK_IMPORTED_MODULE_4__["default"]], ['dataSet', _model_defaults_dataSet__WEBPACK_IMPORTED_MODULE_5__["default"]], ['externalMapLayer', _model_defaults_externalMapLayer__WEBPACK_IMPORTED_MODULE_6__["default"]], ['validationNotificationTemplate', _model_defaults_validationNotificationTemplate__WEBPACK_IMPORTED_MODULE_7__["default"]], ['validationRule', _model_defaults_validationRule__WEBPACK_IMPORTED_MODULE_8__["default"]], ['program', _model_defaults_program__WEBPACK_IMPORTED_MODULE_9__["default"]], ['programNotificationTemplate', _model_defaults_programNotificationTemplate__WEBPACK_IMPORTED_MODULE_10__["default"]]]);
function getDefaultValuesForModelType(modelDefinitionName) {
  if (defaultValues.has(modelDefinitionName)) {
    return defaultValues.get(modelDefinitionName);
  }

  return {};
}
var schemaFields = ['apiEndpoint', 'name', 'displayName', 'authorities', 'singular', 'plural', 'shareable', 'metadata', 'klass', 'identifiableObject', 'translatable'];
var schemaPropertyFields = ['href', 'writable', 'collection', 'collectionName', 'name', 'propertyType', 'persisted', 'required', 'min', 'max', 'ordered', 'unique', 'constants', 'owner', 'itemPropertyType', 'translationKey', 'embeddedObject'];
var fieldsForSchemas = schemaFields.concat("properties[".concat(schemaPropertyFields.join(','), "]")).join(',');

/***/ }),

/***/ "./src/model/config/model-defaults/category.js":
/*!*****************************************************!*\
  !*** ./src/model/config/model-defaults/category.js ***!
  \*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
  dataDimension: true
});

/***/ }),

/***/ "./src/model/config/model-defaults/categoryOptionGroupSet.js":
/*!*******************************************************************!*\
  !*** ./src/model/config/model-defaults/categoryOptionGroupSet.js ***!
  \*******************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
  dataDimension: true
});

/***/ }),

/***/ "./src/model/config/model-defaults/dataElement.js":
/*!********************************************************!*\
  !*** ./src/model/config/model-defaults/dataElement.js ***!
  \********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
  aggregationType: 'SUM',
  valueType: 'NUMBER'
});

/***/ }),

/***/ "./src/model/config/model-defaults/dataElementGroupSet.js":
/*!****************************************************************!*\
  !*** ./src/model/config/model-defaults/dataElementGroupSet.js ***!
  \****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
  dataDimension: true
});

/***/ }),

/***/ "./src/model/config/model-defaults/dataSet.js":
/*!****************************************************!*\
  !*** ./src/model/config/model-defaults/dataSet.js ***!
  \****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
  expiryDays: 0,
  openFuturePeriods: 0,
  timelyDays: 15,
  periodType: 'Monthly'
});

/***/ }),

/***/ "./src/model/config/model-defaults/externalMapLayer.js":
/*!*************************************************************!*\
  !*** ./src/model/config/model-defaults/externalMapLayer.js ***!
  \*************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
  mapService: 'WMS',
  imageFormat: 'PNG',
  mapLayerPosition: 'BASEMAP'
});

/***/ }),

/***/ "./src/model/config/model-defaults/organisationUnitGroupSet.js":
/*!*********************************************************************!*\
  !*** ./src/model/config/model-defaults/organisationUnitGroupSet.js ***!
  \*********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
  dataDimension: true
});

/***/ }),

/***/ "./src/model/config/model-defaults/program.js":
/*!****************************************************!*\
  !*** ./src/model/config/model-defaults/program.js ***!
  \****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
  version: 0,
  completeEventsExpiryDays: 0,
  expiryDays: 0
});

/***/ }),

/***/ "./src/model/config/model-defaults/programNotificationTemplate.js":
/*!************************************************************************!*\
  !*** ./src/model/config/model-defaults/programNotificationTemplate.js ***!
  \************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
  notificationTrigger: 'COMPLETION',
  notificationRecipient: 'USERS_AT_ORGANISATION_UNIT'
});

/***/ }),

/***/ "./src/model/config/model-defaults/validationNotificationTemplate.js":
/*!***************************************************************************!*\
  !*** ./src/model/config/model-defaults/validationNotificationTemplate.js ***!
  \***************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
  notificationRecipient: 'ORGANISATION_UNIT_CONTACT',
  deliveryChannels: [],
  notifyUsersInHierarchyOnly: false
});

/***/ }),

/***/ "./src/model/config/model-defaults/validationRule.js":
/*!***********************************************************!*\
  !*** ./src/model/config/model-defaults/validationRule.js ***!
  \***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
  importance: 'MEDIUM',
  periodType: 'Monthly',
  operator: 'not_equal_to',
  leftSide: {
    missingValueStrategy: 'NEVER_SKIP',
    description: '',
    expression: ''
  },
  rightSide: {
    missingValueStrategy: 'NEVER_SKIP',
    description: '',
    expression: ''
  }
});

/***/ }),

/***/ "./src/model/helpers/attibutes.js":
/*!****************************************!*\
  !*** ./src/model/helpers/attibutes.js ***!
  \****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../lib/check */ "./src/lib/check.js");
/* harmony import */ var _lib_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../lib/utils */ "./src/lib/utils.js");


var getValue = Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["pick"])('value');
var getAttributeValueAttributeName = Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["pick"])('attribute.name');

function createPropertyDefinitionsForAttributes(attributeProperties, getAttributeValues, setAttributeValues, setDirty) {
  return Object.keys(attributeProperties).reduce(function (propertyDefinitions, attributeName) {
    propertyDefinitions[attributeName] = {
      enumerable: true,
      get: function get() {
        var attributeValues = getAttributeValues();
        return attributeValues.filter(function (attributeValue) {
          return getAttributeValueAttributeName(attributeValue) === attributeName;
        }).reduce(function (current, attributeValue) {
          return attributeValue.value;
        }, undefined);
      },
      set: function set(value) {
        var attributeValue = getAttributeValues().filter(function (av) {
          return av.attribute.name === attributeName;
        }).reduce(function (current, av) {
          return av;
        }, undefined);

        if (Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["areDefinedAndEqual"])(getValue(attributeValue), value)) {
          return; // Don't do anything if the value stayed the same
        }

        if (attributeValue) {
          // Remove the attributeValue from the array of attributeValues on the object
          // This is done because the server can not handle them properly when empty strings
          // as values are sent. It will properly remove the attributeValue
          // on the server side when they are not being send to the server at all.
          if (Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["isNullUndefinedOrEmptyString"])(value)) {
            var remainingAttributeValues = getAttributeValues().filter(function (av) {
              return av !== attributeValue;
            });
            setAttributeValues(remainingAttributeValues);
          }

          attributeValue.value = value;
        } else {
          // Add the new attribute value to the attributeValues collection
          setAttributeValues(getAttributeValues().concat({
            value: value,
            attribute: {
              id: attributeProperties[attributeName].id,
              name: attributeProperties[attributeName].name
            }
          }));
        } // Set the model to be dirty


        setDirty();
      }
    };
    return propertyDefinitions;
  }, {});
}

/* harmony default export */ __webpack_exports__["default"] = (createPropertyDefinitionsForAttributes);

/***/ }),

/***/ "./src/model/helpers/json.js":
/*!***********************************!*\
  !*** ./src/model/helpers/json.js ***!
  \***********************************/
/*! exports provided: getJSONForProperties, getOwnedPropertyJSON */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getJSONForProperties", function() { return getJSONForProperties; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getOwnedPropertyJSON", function() { return getOwnedPropertyJSON; });
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../lib/check */ "./src/lib/check.js");
/* harmony import */ var _lib_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../lib/utils */ "./src/lib/utils.js");


/**
 * Map propertyName to modelType
 * The model with propertyName will be treated as a regular array
 * (no collection) if the combination of [propertyName, modelType] exists in the object
 * Empty arrays means it applies to any modelType.
 *
 * @private
 */

var NON_MODEL_COLLECTIONS = {
  aggregationLevels: ['dataElement'],
  grantTypes: ['oAuth2Client'],
  translations: [],
  deliveryChannels: ['programNotificationTemplate', 'dataSetNotificationTemplate'],
  redirectUris: ['oAuth2Client'],
  organisationUnitLevels: ['validationRule'],
  favorites: [],
  columns: [],
  rows: [],
  filters: [],
  yearlySeries: [],
  interpretations: ['chart'],
  userGroupAccesses: [],
  userAccesses: []
};

var isNonModelCollection = function isNonModelCollection(propertyName, modelType) {
  var modelTypes = NON_MODEL_COLLECTIONS[propertyName];

  if (!modelTypes) {
    return false;
  }

  return Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["contains"])(modelType, modelTypes) || Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["isEmpty"])(modelTypes);
};

function isPlainValue(collection) {
  return function isPlainValueInCollection(property) {
    return collection.indexOf(property) === -1;
  };
}

function isCollectionProperty(collection) {
  return function (property) {
    return !isPlainValue(collection)(property);
  };
}

function isReferenceProperty(collection) {
  return function (property) {
    return collection.indexOf(property) >= 0;
  };
} // TODO: Misnamed as it does not actually return JSON


function getJSONForProperties(model, properties) {
  var keepFullModels = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  var objectToSave = {};
  var collectionPropertiesNames = model.getCollectionChildrenPropertyNames() // Even though attributeValues are considered collections, they are handled separately due to their
  // difference in structure.
  .filter(function (propertyName) {
    return propertyName !== 'attributeValues';
  });
  var propertyNames = Object.keys(model.modelDefinition.modelValidations).filter(function (propertyName) {
    return properties.indexOf(propertyName) >= 0;
  }).filter(function (propertyName) {
    return model.dataValues[propertyName] !== undefined && model.dataValues[propertyName] !== null;
  }); // Handle plain values

  propertyNames.filter(isPlainValue(collectionPropertiesNames)).filter(function (v) {
    return !isReferenceProperty(model.getReferenceProperties())(v);
  }).forEach(function (propertyName) {
    objectToSave[propertyName] = model.dataValues[propertyName];
  }); // Handle reference properties

  propertyNames.filter(isPlainValue(collectionPropertiesNames)).filter(isReferenceProperty(model.getReferenceProperties())).forEach(function (propertyName) {
    objectToSave[propertyName] = {
      id: model.dataValues[propertyName].id
    };
  }); // Handle non-embedded collection properties

  propertyNames.filter(isCollectionProperty(collectionPropertiesNames)).forEach(function (propertyName) {
    // TODO: This is not the proper way to do this. We should check if the array contains Models
    // These objects are not marked as embedded objects but they behave like they are
    if (isNonModelCollection(propertyName, model.modelDefinition.name)) {
      objectToSave[propertyName] = Array.from(model.dataValues[propertyName]);
      return;
    }

    var values = Array.isArray(model.dataValues[propertyName]) ? model.dataValues[propertyName] : Array.from(model.dataValues[propertyName].values()); // If the collection is a embedded collection we can save it as is.

    if (model.getEmbeddedObjectCollectionPropertyNames().indexOf(propertyName) !== -1) {
      objectToSave[propertyName] = values;
      return;
    } // Transform an object collection to an array of objects with id properties


    objectToSave[propertyName] = values.filter(Object(_lib_utils__WEBPACK_IMPORTED_MODULE_1__["pick"])('id')) // For any other types we return an object with just an id
    .map(function (childModel) {
      if (keepFullModels && Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(childModel.clone)) {
        return childModel.clone();
      }

      return {
        id: childModel.id
      };
    });
  });
  return objectToSave;
} // TODO: Misnamed as it does not actually return JSON

function getOwnedPropertyJSON(model) {
  var ownedProperties = model.modelDefinition.getOwnedPropertyNames();
  return getJSONForProperties(model, ownedProperties);
}

/***/ }),

/***/ "./src/model/helpers/models.js":
/*!*************************************!*\
  !*** ./src/model/helpers/models.js ***!
  \*************************************/
/*! exports provided: hasModelValidationForProperty, pickTypeFromModelValidation, pickEmbeddedObjectFromModelValidation, pickOwnerFromModelValidation, updateModelFromResponseStatus */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasModelValidationForProperty", function() { return hasModelValidationForProperty; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pickTypeFromModelValidation", function() { return pickTypeFromModelValidation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pickEmbeddedObjectFromModelValidation", function() { return pickEmbeddedObjectFromModelValidation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pickOwnerFromModelValidation", function() { return pickOwnerFromModelValidation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateModelFromResponseStatus", function() { return updateModelFromResponseStatus; });
/* harmony import */ var _uid__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../uid */ "./src/uid.js");
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../lib/check */ "./src/lib/check.js");
/* harmony import */ var _lib_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../lib/utils */ "./src/lib/utils.js");




var hasPropertyOnModelValidation = function hasPropertyOnModelValidation(property, model) {
  return Boolean(Object(_lib_utils__WEBPACK_IMPORTED_MODULE_2__["pick"])("modelDefinition.modelValidations.".concat(property))(model));
};

function hasModelValidationForProperty(model, property) {
  return Boolean(hasPropertyOnModelValidation(property, model) && Object(_lib_check__WEBPACK_IMPORTED_MODULE_1__["hasOwnProperty"])(model.modelDefinition.modelValidations, property));
}
var pickHttpStatus = Object(_lib_utils__WEBPACK_IMPORTED_MODULE_2__["pick"])('httpStatus');
var pickResponseUid = Object(_lib_utils__WEBPACK_IMPORTED_MODULE_2__["pick"])('response.uid');

var getModelValidationForProperty = function getModelValidationForProperty(propertyName) {
  return Object(_lib_utils__WEBPACK_IMPORTED_MODULE_2__["pick"])("modelDefinition.modelValidations.".concat(propertyName));
};

var pickType = Object(_lib_utils__WEBPACK_IMPORTED_MODULE_2__["pick"])('type');
var pickEmbeddedObject = Object(_lib_utils__WEBPACK_IMPORTED_MODULE_2__["pick"])('embeddedObject');
var pickOwner = Object(_lib_utils__WEBPACK_IMPORTED_MODULE_2__["pick"])('owner');
var pickTypeFromModelValidation = function pickTypeFromModelValidation(property, model) {
  return pickType(getModelValidationForProperty(property)(model));
};
var pickEmbeddedObjectFromModelValidation = function pickEmbeddedObjectFromModelValidation(property, model) {
  return pickEmbeddedObject(getModelValidationForProperty(property)(model));
};
var pickOwnerFromModelValidation = function pickOwnerFromModelValidation(property, model) {
  return pickOwner(getModelValidationForProperty(property)(model));
}; // This function is called with `.call` with the Model as it's `this`

function updateModelFromResponseStatus(result) {
  var responseUid = pickResponseUid(result); // Set the id and href of the newly created object if we got an id in the response

  if (pickHttpStatus(result) === 'Created' && Object(_uid__WEBPACK_IMPORTED_MODULE_0__["isValidUid"])(responseUid)) {
    this.dataValues.id = responseUid;
    this.dataValues.href = [this.modelDefinition.apiEndpoint, this.dataValues.id].join('/');
  } // Object is saved to the api, so it's now clean


  this.resetDirtyState();
  return result;
}

/***/ }),

/***/ "./src/model/index.js":
/*!****************************!*\
  !*** ./src/model/index.js ***!
  \****************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _ModelBase__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ModelBase */ "./src/model/ModelBase.js");
/* harmony import */ var _Model__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Model */ "./src/model/Model.js");
/* harmony import */ var _ModelDefinition__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ModelDefinition */ "./src/model/ModelDefinition.js");
/* harmony import */ var _ModelDefinitions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ModelDefinitions */ "./src/model/ModelDefinitions.js");
/* harmony import */ var _ModelValidation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ModelValidation */ "./src/model/ModelValidation.js");
/**
 * @module model
 *
 * @description
 *
 * This page will give you an introduction on one of the largest and more complex parts of d2, the metadata models.
 *
 * Models are an abstraction on top of the dhis2 metadata api. We can use these models to interact with the dhis2 api.
 * The models are accessible on the `.models` property that is attached to the d2 instance (that is retrieved by calling
 * `getInstance()`).
 *
 * A schema is a description of a type of metadata object. To find out which schemas are available for you to use with
 * d2 take a look at https://play.dhis2.org/demo/api/schemas.json?fields=name,metadata. Any schema that is marked as
 * `metadata: true` can be used with d2.
 *
 * There are a few concepts that you should familiarise yourself with before you start. (More documentation on the following
 * concepts can be found on the classes that represent them.)
 *
 * ### ModelDefinitions
 *
 * A {@link module:model.ModelDefinition} is where it all starts. In d2 the schemas you have loaded are represented by a `ModelDefinition`.
 * A `ModelDefinition` is essentially a wrapper around the schemas that allows you to create `Model` instances for that
 * specific schema (e.g. the dataElementModelDefinition allows you to create dataElement Models).
 * ```js
 * d2.models.dataElement // This is the dataElement ModelDefinition
 *  .create()            // Creates a Model object based of the dataElement ModelDefinition
 * ```
 *
 * When working with the d2 object the `d2.models` object contains modelDefinitions for the schemas that you have loaded.
 * (by default that is all schemas). To get a modelDefinition for a specific schema you ask for it by the name of the schema.
 * A few examples other than the dataElement one from above would be:
 *
 * ```js
 * d2.models.user
 * d2.models.legendSet
 * d2.models.organisationUnit
 * ```
 *
 * The ModelDefinition allows you to load objects from the api. You can either load individual items or items in bulk.
 *
 * We can use it to get specific objects
 * ```js
 * d2.models.organisationUnit.get('ImspTQPwCqd')
 *  .then(organisationUnitModel => console.log(organisationUnitModel));
 * ```
 *
 * or to load a list of objects (by default paging is enabled and it will only load the first 50 entries).
 * ```js
 * d2.models.organisationUnit.list()
 *  .then(organisationUnitCollection => console.log(organisationUnitCollection));
 * ```
 *
 * The ModelDefinition also allows you to filter on properties using a programatic syntax. To find out which
 * filter methods are available you can a look at the {@link module:model.Filter|Filter} class.
 * ```js
 * d2.models.organisationUnit
 *  .filter().on('level').equals(2)
 *  .list()
 *  .then(organisationUnitCollection => console.log(organisationUnitCollection));
 * ```
 * Applying a filter like this will create a clone of the modelDefinition with the filter applied, so you can
 * store the reference to the cloned modelDefinition and use it later, without globally applying the filter everywhere.
 *
 * ```js
 * const organisationUnitsOnLevel3 = d2.models.organisationUnit
 *  .filter().on('level').equals(3);
 *
 * const organisationUnitsOnLevel3WithParent = organisationUnitsOnLevel3
 *  .filter().on('parent.id').equals('O6uvpzGd5pu);
 *
 * organisationUnitsOnLevel3
 *  .list({ paging: false }) // Loads all organisation units on level 3
 *  .then(organisationUnitCollection => console.log(organisationUnitCollection));
 *
 * organisationUnitsOnLevel3WithParent
 *  .list({ paging: false }) // Loads all organisation units on level 3 with O6uvpzGd5pu as their parent
 *   .then(organisationUnitCollection => console.log(organisationUnitCollection));
 * ```
 *
 * As you might have noticed we passed `{ paging: false }` to the `.list` method. Any options passed to the list method
 * (with the exception of filter) will be passed through as regular query parameters.
 *
 * If you ran the above examples you would notice that the `.list` method returns a ModelCollection.
 *
 * ## ModelCollection
 * A {@link module:model.ModelCollection|ModelCollection} is simple a collection of Model objects. The ModelCollection is
 * sometimes somewhat cumbersome to work with and often you would like to transform the ModelCollection to an array using
 * the `.toArray()` method or spreading the values of the ModelCollection.
 *
 * ```js
 * d2.models.organisationUnit
 *  .filter().on('level').equals(2)
 *  .list()
 *  .then(organisationUnitCollection => {
 *    let organisationUnits = organisationUnitCollection.toArray();
 *    // or
 *    organisationUnits = [...organisationUnitCollection.values()];
 * });
 * ```
 *
 * The ModelCollection does not only contain the Models, it also gives you access to a {@link module:model.Pager|Pager}.
 * The pager objects keeps track of which page was loaded and how many pages there are.
 *
 * The following example will load the first page of organisation units and then keep loading a new page every second
 * until we run out of pages.
 * ```js
 * function loadNextPage(pager, callback) {
 *   if (pager.hasNextPage()) {
 *     pager.getNextPage()
 *       .then(organisationUnitCollection  => {
 *         setTimeout(() => {
 *           callback(organisationUnitCollection);
 *           loadNextPage(organisationUnitCollection.pager, callback);
 *         }, 1000);
 *       });
 *   }
 * }
 *
 * const printCollection = collection => console.log(collection.toArray());
 *
 * d2.models.organisationUnit
 *   .list()
 *   .then(organisationUnitCollection => {
 *     printCollection(organisationUnitCollection);
 *     loadNextPage(organisationUnitCollection.pager, printCollection);
 *   });
 * ```
 *
 * ## Model
 * TODO: :(
 */





/* harmony default export */ __webpack_exports__["default"] = ({
  ModelBase: _ModelBase__WEBPACK_IMPORTED_MODULE_0__["default"],
  Model: _Model__WEBPACK_IMPORTED_MODULE_1__["default"],
  ModelDefinition: _ModelDefinition__WEBPACK_IMPORTED_MODULE_2__["default"],
  ModelDefinitions: _ModelDefinitions__WEBPACK_IMPORTED_MODULE_3__["default"],
  ModelValidation: _ModelValidation__WEBPACK_IMPORTED_MODULE_4__["default"]
});

/***/ }),

/***/ "./src/pager/Pager.js":
/*!****************************!*\
  !*** ./src/pager/Pager.js ***!
  \****************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../lib/check */ "./src/lib/check.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }


/**
 * @description
 * Pager object that can be used to navigate pages within a `Modelcollection`
 *
 * @memberof module:model
 */

/**
 * @memberof module:model
 */
// TODO: Move to the model map

var Pager =
/*#__PURE__*/
function () {
  /**
   * @constructor
   *
   * @param {Object} [pager={page: 1, pageCount: 1}] Paging information object.
   * @param {Object} [pagingHandler={list: () => Promise.reject('No handler available')}] Paging handler object. The requirement for this object is that it has a list method.
   *
   * @description
   * Returns a newly created pager object with methods to navigate pages.
   */
  function Pager() {
    var pager = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
      page: 1,
      pageCount: 1,
      query: {}
    };
    var pagingHandler = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
      list: function list() {
        return Promise.reject('No handler available');
      }
    };

    _classCallCheck(this, Pager);

    /**
     * @property {number} page Current page number
     */
    this.page = pager.page;
    /**
     * @property {number} pageCount The total number of pages available
     */

    this.pageCount = pager.pageCount;
    /**
     * @property {number} total The total number of items available.
     *
     * @description
     * This represents the total number of items available in the system. Note it is not the number of items
     * on the current page.
     */

    this.total = pager.total;
    /**
     * @property {string} nextPage The url to the next page.
     *
     * @description
     * If there is no next page then this will be undefined.
     */

    this.nextPage = pager.nextPage;
    /**
     * @property {string} prevPage The url to the previous page
     *
     * @description
     * If there is no previous page then this will be undefined.
     */

    this.prevPage = pager.prevPage;
    /**
     * @property {object} query Query parameters
     *
     * @description
     * Query parameters are used for things like filtering and field selection. Used to guarantee that pages are
     * from the same collection.
     */

    this.query = pager.query;
    this.pagingHandler = pagingHandler;
  }
  /**
   * @returns {Boolean} Result is true when there is a next page, false when there is not.
   *
   * @description
   * Check whether there is a next page.
   */


  _createClass(Pager, [{
    key: "hasNextPage",
    value: function hasNextPage() {
      return Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["isDefined"])(this.nextPage);
    }
    /**
     * Check whether there is a previous page.
     *
     * @returns {Boolean} Result is true when there is a previous page, false when there is not.
     */

  }, {
    key: "hasPreviousPage",
    value: function hasPreviousPage() {
      return Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["isDefined"])(this.prevPage);
    }
    /**
     * @description
     * Loads the next page in the collection if there is one. If no additional pages are available the Promise will reject.
     *
     * @returns {Promise} Promise that resolves with a new `ModelCollection` containing the next page's data. Or rejects with
     * a string when there is no next page for this collection or when the request for the next page failed.
     *
     * @example
     * d2.models.organisationUnit
     *   .list()
     *   .then(collection => {
     *     collection.pager.getNextPage()
     *       .then(secondPageCollection => {
     *         console.log(secondPageCollection.toArray());
     *       });
     *   });
     */

  }, {
    key: "getNextPage",
    value: function getNextPage() {
      if (this.hasNextPage()) {
        return this.goToPage(this.page + 1);
      }

      return Promise.reject('There is no next page for this collection');
    }
    /**
     * @description
     * Loads the previous page in the collection if there is one. If no previous pages are available the Promise will reject.
     *
     * @returns {Promise} Promise that resolves with a new `ModelCollection` containing the previous page's data. Or rejects with
     * a string when there is no previous page for this collection or when the request for the previous page failed.
     *
     * @example
     * d2.models.organisationUnit
     *   .list()
     *   .then(collection => {
     *     collection.pager.goToPage(3)
     *       .then(collection => collection.pager.getPreviousPage())
     *       .then(secondPageCollection => {
     *         console.log(secondPageCollection.toArray());
     *       });
     *   });
     */

  }, {
    key: "getPreviousPage",
    value: function getPreviousPage() {
      if (this.hasPreviousPage()) {
        return this.goToPage(this.page - 1);
      }

      return Promise.reject('There is no previous page for this collection');
    }
    /**
     * Loads a specific page for the collection. If the requested page is out of the range of available pages (e.g < 0 or > page count)
     * the Promise will reject with an error.
     *
     * @param {Number} pageNr The number of the page you wish to navigate to.
     * @returns {Promise} Promise that resolves with a new `ModelCollection` containing the data for the requested page.
     *
     * @example
     * d2.models.organisationUnit
     *   .list()
     *   .then(collection => {
     *     collection.pager.goToPage(4)
     *       .then(fourthPageCollection => {
     *         console.log(fourthPageCollection.toArray());
     *       });
     *   });
     */
    // TODO: Throwing the errors here is not really consistent with the rejection of promises for the getNextPage and getPreviousPage

  }, {
    key: "goToPage",
    value: function goToPage(pageNr) {
      if (pageNr < 1) {
        throw new Error('PageNr can not be less than 1');
      }

      if (pageNr > this.pageCount) {
        throw new Error("PageNr can not be larger than the total page count of ".concat(this.pageCount));
      }

      return this.pagingHandler.list(Object.assign({}, this.query, {
        page: pageNr
      }));
    }
  }]);

  return Pager;
}();

/* harmony default export */ __webpack_exports__["default"] = (Pager);

/***/ }),

/***/ "./src/system/System.js":
/*!******************************!*\
  !*** ./src/system/System.js ***!
  \******************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
/* harmony import */ var _SystemSettings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./SystemSettings */ "./src/system/SystemSettings.js");
/* harmony import */ var _SystemConfiguration__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./SystemConfiguration */ "./src/system/SystemConfiguration.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

/**
 * @module system
 *
 * @requires module:api/Api
 */



/**
 * @description
 * Represents the system that can be interacted with. There is a single instance of this pre-defined onto the d2
 * object after initialisation. This can be interacted with using its property objects to among other be used
 * to get and save systemSettings.
 *
 * @memberof module:system
 */

var System =
/*#__PURE__*/
function () {
  function System(settings, configuration) {
    _classCallCheck(this, System);

    /**
     * Contains a reference to a `SystemSettings` instance that can be used
     * to retrieve and save system settings.
     *
     * ```js
     * d2.system.settings.get('keyLastSuccessfulResourceTablesUpdate')
     *  .then(systemSettingsValue => {
     *    console.log('Analytics was last updated on: ' + systemSettingsValue);
     *  });
     * ```
     * @type {SystemSettings}
     *
     */
    this.settings = settings;
    /**
     * A representation of the system configuration,
     * that can be used to retrieve and change system configuration options.
     * @type {SystemConfiguration}
     */

    this.configuration = configuration;
    /**
     * An object containing system information about the DHIS2 instance
     * @type {Object}
     */

    this.systemInfo = undefined;
    /**
     * An object containing version information about the DHIS2 instance
     * @type {Object}
     */

    this.version = undefined;
    /**
     * An array of all the webapps that are installed on the current DHIS2 instance
     * @type {Array}
     */

    this.installedApps = undefined;
  }
  /**
   * Sets the systemInfo and version properties
   *
   * @param systemInfo
   */


  _createClass(System, [{
    key: "setSystemInfo",
    value: function setSystemInfo(systemInfo) {
      this.version = System.parseVersionString(systemInfo.version);
      this.systemInfo = systemInfo;
    }
    /**
     * Sets the list of currently installed webapps
     *
     * @param apps
     */

  }, {
    key: "setInstalledApps",
    value: function setInstalledApps(apps) {
      this.installedApps = apps;
    }
    /**
     * Refreshes the list of currently installed webapps
     *
     * @returns {Promise} A promise that resolves to the list of installed apps
     */

  }, {
    key: "loadInstalledApps",
    value: function loadInstalledApps() {
      var _this = this;

      var api = _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi();
      return api.get('apps').then(function (apps) {
        _this.setInstalledApps(apps);

        return apps;
      });
    }
    /**
     * Upload and install a zip file containing a new webapp
     *
     * @param zipFile Zip file data from a file input form field
     * @param onProgress An optional callback that will be called whenever file upload progress info is available
     * @returns {Promise}
     */

  }, {
    key: "uploadApp",
    value: function uploadApp(zipFile, onProgress) {
      var api = _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi();
      var data = new FormData();
      var xhr;
      data.append('file', zipFile);

      if (onProgress !== undefined) {
        xhr = new XMLHttpRequest();

        xhr.upload.onprogress = function (progress) {
          if (progress.lengthComputable) {
            onProgress(progress.loaded / progress.total);
          }
        };
      }

      return api.post('apps', data, {
        contentType: false,
        processData: false,
        xhr: xhr !== undefined ? function () {
          return xhr;
        } : undefined
      });
    }
    /**
     * Load the list of apps available in the DHIS 2 app store
     *
     * @param compatibleOnly If true, apps that are incompatible with the current system will be filtered out
     * @returns {Promise}
     */

  }, {
    key: "loadAppStore",
    value: function loadAppStore() {
      var _this2 = this;

      var compatibleOnly = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      return new Promise(function (resolve, reject) {
        var api = _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi();
        api.get('appStore').then(function (appStoreData) {
          return resolve(appStoreData.map(function (appData) {
            var app = Object.assign({}, appData);

            if (compatibleOnly) {
              app.versions = app.versions.filter(function (versionData) {
                return System.isVersionCompatible(_this2.version, versionData);
              });
            }

            return app;
          }).filter(function (appData) {
            return appData.versions.length > 0;
          }));
        }).catch(function (err) {
          return reject(err);
        });
      });
    }
    /**
     * Install the specified app version from the DHIS 2 app store
     *
     * @param uid The uid of the app version to install
     * @returns {Promise}
     */

  }, {
    key: "installAppVersion",
    value: function installAppVersion(uid) {
      var api = _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi();
      return new Promise(function (resolve, reject) {
        api.post(['appStore', uid].join('/'), '', {
          dataType: 'text'
        }).then(function () {
          resolve();
        }).catch(function (err) {
          reject(err);
        });
      });
    }
    /**
     * Remove the specified app from the system
     *
     * @param appKey The key of the app to remove
     * @returns {Promise}
     */

  }, {
    key: "uninstallApp",
    value: function uninstallApp(appKey) {
      var api = _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi();
      return api.delete(['apps', appKey].join('/')) // TODO: Stop jQuery from rejecting successful promises
      .catch(function () {
        return undefined;
      });
    }
    /**
     * Refresh the list of apps that are installed on the server
     *
     * @returns {Promise} A promise that resolves to the updated list of installed apps
     */

  }, {
    key: "reloadApps",
    value: function reloadApps() {
      var _this3 = this;

      var api = _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi();
      return api.update('apps').then(function () {
        return _this3.loadInstalledApps();
      });
    }
    /**
     * @static
     * @typedef {Object} ParsedVersion
     * @property {number} major - Major version of the parsed-string (before .)
     * @property {number} minor - Minor version of the parsed-string (after .)
     * @property {boolean} snapshot - If it's a snapshot-version
     */
    // TODO: Validate string
    // TODO: Handle valid version objects too

    /**
     * Parses a version string into an object describing the version.
     * @param {string} version Version-string to parse
     * @returns {module:system.ParsedVersion}
     */

  }], [{
    key: "parseVersionString",
    value: function parseVersionString(version) {
      return {
        major: Number.parseInt(version, 10),
        minor: Number.parseInt(version.substring(version.indexOf('.') + 1), 10),
        snapshot: version.indexOf('-SNAPSHOT') >= 0
      };
    } // Disable eslint complexity warning

    /* eslint-disable complexity */

    /**
     * Compares version a to version b.
     * @param a {string|module:system.ParsedVersion}
     * @param b {string|module:system.ParsedVersion}
     * @returns {number} 0 if same version, else a - b.
     */

  }, {
    key: "compareVersions",
    value: function compareVersions(a, b) {
      var from = typeof a === 'string' || a instanceof String ? System.parseVersionString(a) : a;
      var to = typeof b === 'string' || b instanceof String ? System.parseVersionString(b) : b;

      if (from.major !== to.major) {
        return from.major - to.major;
      }

      if (from.minor !== to.minor) {
        return from.minor - to.minor;
      }

      return (from.snapshot ? 0 : 1) - (to.snapshot ? 0 : 1);
    }
    /**
     * Checks if systemVersion is compatible with appVersion.
     * Versions are compatible if appVersion.minDhisVersion <= parsed systemVersion and
     * if appVersion.maxDhisVersion >= parsed systemVersion.
     * @param systemVersion {string|module:system.ParsedVersion} systemVersion to check
     * @param {Object} appVersion - AppVersion object to check
     * @returns {boolean} true if compatible, false otherwise.
     */

  }, {
    key: "isVersionCompatible",
    value: function isVersionCompatible(systemVersion, appVersion) {
      var minVersion = appVersion.minDhisVersion || appVersion.min_platform_version || null;
      var maxVersion = appVersion.maxDhisVersion || appVersion.max_platform_version || null;
      var isNewEnough = minVersion ? System.compareVersions(systemVersion, minVersion) >= 0 : true;
      var isNotTooOld = maxVersion ? System.compareVersions(systemVersion, maxVersion) <= 0 : true;
      return isNewEnough && isNotTooOld;
    }
    /* eslint-enable */

    /**
     * Get a new instance of the system object. This will function as a singleton, when a System object has been created
     * when requesting getSystem again the original version will be returned.
     *
     * @returns {System} Object with the system interaction properties
     */

  }, {
    key: "getSystem",
    value: function getSystem() {
      if (!System.getSystem.system) {
        System.getSystem.system = new System(new _SystemSettings__WEBPACK_IMPORTED_MODULE_1__["default"](), new _SystemConfiguration__WEBPACK_IMPORTED_MODULE_2__["default"]());
      }

      return System.getSystem.system;
    }
  }]);

  return System;
}();

/* harmony default export */ __webpack_exports__["default"] = (System);

/***/ }),

/***/ "./src/system/SystemConfiguration.js":
/*!*******************************************!*\
  !*** ./src/system/SystemConfiguration.js ***!
  \*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }


/**
 * Handles communication with the configuration endpoint. Can be used to get or set configuration options.
 *
 * @memberof module:system
 */

var SystemConfiguration =
/*#__PURE__*/
function () {
  function SystemConfiguration() {
    var api = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _api_Api__WEBPACK_IMPORTED_MODULE_0__["default"].getApi();

    _classCallCheck(this, SystemConfiguration);

    this.api = api;
    this.configuration = undefined;
    this.configPromise = null;
  }
  /**
   * Fetches all system configuration settings from the API and caches them so that future
   * calls to this function won't call the API again.
   *
   * @param {boolean} [ignoreCache=false] If set to true, calls the API regardless of cache status
   * @returns {Promise} Promise that resolves with all the individual configuration options from the api.
   */


  _createClass(SystemConfiguration, [{
    key: "all",
    value: function all(ignoreCache) {
      var _this = this;

      if (this.configPromise === null || ignoreCache === true) {
        this.configPromise = this.api.get('configuration').then(function (configuration) {
          _this.configuration = configuration;
          return _this.configuration;
        });
      }

      return this.configPromise;
    }
    /**
     * Returns the value of the specified configuration option.
     *
     * This is a convenience method that works exactly the same as calling `configuration.all()[name]`.
     *
     * @param key {String}
     * @param {boolean} [ignoreCache=false] If set to true, calls the API regardless of cache status
     * @returns {Promise}
     */

  }, {
    key: "get",
    value: function get(key, ignoreCache) {
      return this.all(ignoreCache).then(function (config) {
        if (config.hasOwnProperty(key)) {
          return Promise.resolve(config[key]);
        }

        return Promise.reject("Unknown config option: ".concat(key));
      });
    }
    /**
     * Send a query to the API to change the value of a configuration key to the specified value.
     *
     * @param key {String}
     * @param value {String|null}
     * @returns {Promise}
     */

    /* eslint-disable complexity */

  }, {
    key: "set",
    value: function set(key, value) {
      var that = this;
      var req;

      if (key === 'systemId') {
        return Promise.reject("The system ID can't be changed");
      }

      if ((key === 'feedbackRecipients' || key === 'selfRegistrationOrgUnit' || key === 'selfRegistrationRole') && (value === 'null' || value === null)) {
        // Only valid UIDs are accepted when POST'ing, so we have to use DELETE in stead of POST'ing a null value.
        req = this.api.delete(['configuration', key].join('/'));
      } else if (key === 'corsWhitelist') {
        // The corsWhitelist endpoint expects a JSON array (of URLs), while here value is expected to be a string.
        req = this.api.post(['configuration', key].join('/'), value.trim().split('\n'));
      } else {
        req = this.api.post(['configuration', key].join('/'), value, {
          dataType: 'text',
          contentType: 'text/plain'
        });
      }

      return req.then(function () {
        // Ideally we'd update the cache here, but doing so requires another trip to the server
        // For now, just bust the cache to ensure it's not incorrect
        that.configuration = undefined;
        return Promise.resolve();
      }).catch(function () {
        return Promise.reject("No configuration found for ".concat(key));
      });
    }
    /* eslint-enable complexity */

  }]);

  return SystemConfiguration;
}();

/* harmony default export */ __webpack_exports__["default"] = (SystemConfiguration);

/***/ }),

/***/ "./src/system/SystemSettings.js":
/*!**************************************!*\
  !*** ./src/system/SystemSettings.js ***!
  \**************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_check__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../lib/check */ "./src/lib/check.js");
/* harmony import */ var _api_Api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../api/Api */ "./src/api/Api.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }



/**
 * @description
 * Handles communication with the systemSettings endpoint. Can be used to get or save systemSettings.
 *
 * @memberof module:system
 * @requires lib/check
 * @requires api/Api
 */
// TODO: Return the values from the local cache if we have not updated it? We could

var SystemSettings =
/*#__PURE__*/
function () {
  function SystemSettings() {
    var api = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _api_Api__WEBPACK_IMPORTED_MODULE_1__["default"].getApi();

    _classCallCheck(this, SystemSettings);

    this.api = api;
  }
  /**
   * Loads all the system settings in the system and returns them as an object from the promise.
   *
   * @returns {Promise} Promise that resolves with the systemsettings object from the api.
   *
   * @example
   * d2.system.settings.all()
   *  .then(systemSettings => {
   *    console.log('Analytics was last updated on: ' + systemSettings.keyLastSuccessfulResourceTablesUpdate);
   *  });
   */


  _createClass(SystemSettings, [{
    key: "all",
    value: function all() {
      var _this = this;

      return this.settings ? Promise.resolve(this.settings) : this.api.get('systemSettings').then(function (settings) {
        _this.settings = settings;
        return Promise.resolve(_this.settings);
      });
    }
    /**
     * Get a single systemSetting for the given key.
     *
     * This will use the cached value of the key if it has been previously loaded.
     *
     * @param {String} systemSettingsKey The identifier of the system setting that should be retrieved.
     * @returns {Promise} A promise that resolves with the value or will fail if the value is not available.
     *
     * @example
     * d2.system.settings.get('keyLastSuccessfulResourceTablesUpdate')
     *  .then(systemSettingsValue => {
     *    console.log('Analytics was last updated on: ' + systemSettingsValue);
     *  });
     */

  }, {
    key: "get",
    value: function get(systemSettingsKey) {
      var _this2 = this;

      if (this.settings && this.settings[systemSettingsKey]) {
        return Promise.resolve(this.settings[systemSettingsKey]);
      }

      function processValue(value) {
        // Attempt to parse the response as JSON. If this fails we return the value as is.
        try {
          return JSON.parse(value);
        } catch (e) {
          return value;
        }
      }

      return new Promise(function (resolve, reject) {
        if (!Object(_lib_check__WEBPACK_IMPORTED_MODULE_0__["isString"])(systemSettingsKey)) {
          throw new TypeError('A "key" parameter should be specified when calling get() on systemSettings');
        }

        var options = {
          headers: {
            accept: 'text/plain'
          }
        };

        _this2.api.get(['systemSettings', systemSettingsKey].join('/'), undefined, options).then(function (response) {
          if (response) {
            resolve(processValue(response));
          }

          reject(new Error('The requested systemSetting has no value or does not exist.'));
        });
      });
    }
  }, {
    key: "set",
    value: function set(systemSettingsKey, value) {
      var _this3 = this;

      var settingUrl = ['systemSettings', systemSettingsKey].join('/');

      if (value === null || "".concat(value).length === 0) {
        return this.api.delete(settingUrl).then(function (response) {
          // Update cache if present
          if (_this3.settings && _this3.settings[systemSettingsKey]) {
            delete _this3.settings[systemSettingsKey];
          }

          return response;
        });
      }

      return this.api.post(settingUrl, value, {
        headers: {
          'Content-Type': 'text/plain'
        }
      }).then(function (response) {
        // update cache if present
        if (_this3.settings) {
          _this3.settings[systemSettingsKey] = value;
        }

        return response;
      });
    }
  }]);

  return SystemSettings;
}();

/* harmony default export */ __webpack_exports__["default"] = (SystemSettings);

/***/ }),

/***/ "./src/uid.js":
/*!********************!*\
  !*** ./src/uid.js ***!
  \********************/
/*! exports provided: generateUid, isValidUid */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generateUid", function() { return generateUid; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isValidUid", function() { return isValidUid; });
/**
 * @module uid
 *
 * @description
 * Client side implementation of the DHIS2 code (uid) generator.
 * ({@link https://github.com/dhis2/dhis2-core/blob/ad2d5dea959aff3146d8fe5796cf0b75eb6ee5d8/dhis-2/dhis-api/src/main/java/org/hisp/dhis/common/CodeGenerator.java|CodeGenerator.java})
 *
 * This module is used to generate and validate DHIS2 uids. A valid DHIS2 uid is a 11 character string which starts with a letter from the ISO basic Latin alphabet.
 */
var abc = 'abcdefghijklmnopqrstuvwxyz';
var letters = abc.concat(abc.toUpperCase());
var ALLOWED_CHARS = "0123456789".concat(letters);
var NUMBER_OF_CODEPOINTS = ALLOWED_CHARS.length;
var CODESIZE = 11;
var CODE_PATTERN = /^[a-zA-Z]{1}[a-zA-Z0-9]{10}$/;

function randomWithMax(max) {
  return Math.floor(Math.random() * max);
}
/**
 * Generate a valid DHIS2 uid. A valid DHIS2 uid is a 11 character string which starts with a letter from the ISO basic Latin alphabet.
 *
 * @return {string} A 11 character uid that always starts with a letter.
 *
 * @example
 * import { generateUid } from 'd2/lib/uid';
 *
 * generateUid();
 */


function generateUid() {
  // First char should be a letter
  var randomChars = letters.charAt(randomWithMax(letters.length));

  for (var i = 1; i < CODESIZE; i += 1) {
    randomChars += ALLOWED_CHARS.charAt(randomWithMax(NUMBER_OF_CODEPOINTS));
  } // return new String( randomChars );


  return randomChars;
}
/**
 * Tests whether the given code is valid.
 *
 * @param {string} code The code to validate.
 * @return {boolean} Returns true if the code is valid, false otherwise.
 *
 * @example
 * import { isValidUid } from 'd2/lib/uid';
 *
 * isValidUid('JkWynlWMjJR'); // true
 * isValidUid('0kWynlWMjJR'); // false (Uid can not start with a number)
 * isValidUid('AkWy$lWMjJR'); // false (Uid can only contain alphanumeric characters.
 */

function isValidUid(code) {
  if (code == null) {
    return false;
  }

  return CODE_PATTERN.test(code);
}

/***/ })

/******/ });
});
//# sourceMappingURL=d2-browser.js.map