UNPKG

119 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3 typeof define === 'function' && define.amd ? define(['exports'], factory) :
4 (factory((global.Daux = {})));
5}(this, (function (exports) { 'use strict';
6
7 function createCommonjsModule(fn, module) {
8 return module = { exports: {} }, fn(module, module.exports), module.exports;
9 }
10
11 var _global = createCommonjsModule(function (module) {
12 // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
13 var global = module.exports = typeof window != 'undefined' && window.Math == Math
14 ? window : typeof self != 'undefined' && self.Math == Math ? self
15 // eslint-disable-next-line no-new-func
16 : Function('return this')();
17 if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
18 });
19
20 var _core = createCommonjsModule(function (module) {
21 var core = module.exports = { version: '2.5.7' };
22 if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
23 });
24 var _core_1 = _core.version;
25
26 var _isObject = function (it) {
27 return typeof it === 'object' ? it !== null : typeof it === 'function';
28 };
29
30 var _anObject = function (it) {
31 if (!_isObject(it)) throw TypeError(it + ' is not an object!');
32 return it;
33 };
34
35 var _fails = function (exec) {
36 try {
37 return !!exec();
38 } catch (e) {
39 return true;
40 }
41 };
42
43 // Thank's IE8 for his funny defineProperty
44 var _descriptors = !_fails(function () {
45 return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
46 });
47
48 var document$1 = _global.document;
49 // typeof document.createElement is 'object' in old IE
50 var is = _isObject(document$1) && _isObject(document$1.createElement);
51 var _domCreate = function (it) {
52 return is ? document$1.createElement(it) : {};
53 };
54
55 var _ie8DomDefine = !_descriptors && !_fails(function () {
56 return Object.defineProperty(_domCreate('div'), 'a', { get: function () { return 7; } }).a != 7;
57 });
58
59 // 7.1.1 ToPrimitive(input [, PreferredType])
60
61 // instead of the ES6 spec version, we didn't implement @@toPrimitive case
62 // and the second argument - flag - preferred type is a string
63 var _toPrimitive = function (it, S) {
64 if (!_isObject(it)) return it;
65 var fn, val;
66 if (S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val;
67 if (typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it))) return val;
68 if (!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val;
69 throw TypeError("Can't convert object to primitive value");
70 };
71
72 var dP = Object.defineProperty;
73
74 var f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes) {
75 _anObject(O);
76 P = _toPrimitive(P, true);
77 _anObject(Attributes);
78 if (_ie8DomDefine) try {
79 return dP(O, P, Attributes);
80 } catch (e) { /* empty */ }
81 if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
82 if ('value' in Attributes) O[P] = Attributes.value;
83 return O;
84 };
85
86 var _objectDp = {
87 f: f
88 };
89
90 var _propertyDesc = function (bitmap, value) {
91 return {
92 enumerable: !(bitmap & 1),
93 configurable: !(bitmap & 2),
94 writable: !(bitmap & 4),
95 value: value
96 };
97 };
98
99 var _hide = _descriptors ? function (object, key, value) {
100 return _objectDp.f(object, key, _propertyDesc(1, value));
101 } : function (object, key, value) {
102 object[key] = value;
103 return object;
104 };
105
106 var hasOwnProperty = {}.hasOwnProperty;
107 var _has = function (it, key) {
108 return hasOwnProperty.call(it, key);
109 };
110
111 var id = 0;
112 var px = Math.random();
113 var _uid = function (key) {
114 return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
115 };
116
117 var _redefine = createCommonjsModule(function (module) {
118 var SRC = _uid('src');
119 var TO_STRING = 'toString';
120 var $toString = Function[TO_STRING];
121 var TPL = ('' + $toString).split(TO_STRING);
122
123 _core.inspectSource = function (it) {
124 return $toString.call(it);
125 };
126
127 (module.exports = function (O, key, val, safe) {
128 var isFunction = typeof val == 'function';
129 if (isFunction) _has(val, 'name') || _hide(val, 'name', key);
130 if (O[key] === val) return;
131 if (isFunction) _has(val, SRC) || _hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
132 if (O === _global) {
133 O[key] = val;
134 } else if (!safe) {
135 delete O[key];
136 _hide(O, key, val);
137 } else if (O[key]) {
138 O[key] = val;
139 } else {
140 _hide(O, key, val);
141 }
142 // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
143 })(Function.prototype, TO_STRING, function toString() {
144 return typeof this == 'function' && this[SRC] || $toString.call(this);
145 });
146 });
147
148 var _aFunction = function (it) {
149 if (typeof it != 'function') throw TypeError(it + ' is not a function!');
150 return it;
151 };
152
153 // optional / simple context binding
154
155 var _ctx = function (fn, that, length) {
156 _aFunction(fn);
157 if (that === undefined) return fn;
158 switch (length) {
159 case 1: return function (a) {
160 return fn.call(that, a);
161 };
162 case 2: return function (a, b) {
163 return fn.call(that, a, b);
164 };
165 case 3: return function (a, b, c) {
166 return fn.call(that, a, b, c);
167 };
168 }
169 return function (/* ...args */) {
170 return fn.apply(that, arguments);
171 };
172 };
173
174 var PROTOTYPE = 'prototype';
175
176 var $export = function (type, name, source) {
177 var IS_FORCED = type & $export.F;
178 var IS_GLOBAL = type & $export.G;
179 var IS_STATIC = type & $export.S;
180 var IS_PROTO = type & $export.P;
181 var IS_BIND = type & $export.B;
182 var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] || (_global[name] = {}) : (_global[name] || {})[PROTOTYPE];
183 var exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {});
184 var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});
185 var key, own, out, exp;
186 if (IS_GLOBAL) source = name;
187 for (key in source) {
188 // contains in native
189 own = !IS_FORCED && target && target[key] !== undefined;
190 // export native or passed
191 out = (own ? target : source)[key];
192 // bind timers to global for call from export context
193 exp = IS_BIND && own ? _ctx(out, _global) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out;
194 // extend global
195 if (target) _redefine(target, key, out, type & $export.U);
196 // export
197 if (exports[key] != out) _hide(exports, key, exp);
198 if (IS_PROTO && expProto[key] != out) expProto[key] = out;
199 }
200 };
201 _global.core = _core;
202 // type bitmap
203 $export.F = 1; // forced
204 $export.G = 2; // global
205 $export.S = 4; // static
206 $export.P = 8; // proto
207 $export.B = 16; // bind
208 $export.W = 32; // wrap
209 $export.U = 64; // safe
210 $export.R = 128; // real proto method for `library`
211 var _export = $export;
212
213 var toString = {}.toString;
214
215 var _cof = function (it) {
216 return toString.call(it).slice(8, -1);
217 };
218
219 // fallback for non-array-like ES3 and non-enumerable old V8 strings
220
221 // eslint-disable-next-line no-prototype-builtins
222 var _iobject = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
223 return _cof(it) == 'String' ? it.split('') : Object(it);
224 };
225
226 // 7.2.1 RequireObjectCoercible(argument)
227 var _defined = function (it) {
228 if (it == undefined) throw TypeError("Can't call method on " + it);
229 return it;
230 };
231
232 // to indexed object, toObject with fallback for non-array-like ES3 strings
233
234
235 var _toIobject = function (it) {
236 return _iobject(_defined(it));
237 };
238
239 // 7.1.4 ToInteger
240 var ceil = Math.ceil;
241 var floor = Math.floor;
242 var _toInteger = function (it) {
243 return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
244 };
245
246 // 7.1.15 ToLength
247
248 var min = Math.min;
249 var _toLength = function (it) {
250 return it > 0 ? min(_toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
251 };
252
253 var max = Math.max;
254 var min$1 = Math.min;
255 var _toAbsoluteIndex = function (index, length) {
256 index = _toInteger(index);
257 return index < 0 ? max(index + length, 0) : min$1(index, length);
258 };
259
260 // false -> Array#indexOf
261 // true -> Array#includes
262
263
264
265 var _arrayIncludes = function (IS_INCLUDES) {
266 return function ($this, el, fromIndex) {
267 var O = _toIobject($this);
268 var length = _toLength(O.length);
269 var index = _toAbsoluteIndex(fromIndex, length);
270 var value;
271 // Array#includes uses SameValueZero equality algorithm
272 // eslint-disable-next-line no-self-compare
273 if (IS_INCLUDES && el != el) while (length > index) {
274 value = O[index++];
275 // eslint-disable-next-line no-self-compare
276 if (value != value) return true;
277 // Array#indexOf ignores holes, Array#includes - not
278 } else for (;length > index; index++) if (IS_INCLUDES || index in O) {
279 if (O[index] === el) return IS_INCLUDES || index || 0;
280 } return !IS_INCLUDES && -1;
281 };
282 };
283
284 var _library = false;
285
286 var _shared = createCommonjsModule(function (module) {
287 var SHARED = '__core-js_shared__';
288 var store = _global[SHARED] || (_global[SHARED] = {});
289
290 (module.exports = function (key, value) {
291 return store[key] || (store[key] = value !== undefined ? value : {});
292 })('versions', []).push({
293 version: _core.version,
294 mode: 'global',
295 copyright: '© 2018 Denis Pushkarev (zloirock.ru)'
296 });
297 });
298
299 var shared = _shared('keys');
300
301 var _sharedKey = function (key) {
302 return shared[key] || (shared[key] = _uid(key));
303 };
304
305 var arrayIndexOf = _arrayIncludes(false);
306 var IE_PROTO = _sharedKey('IE_PROTO');
307
308 var _objectKeysInternal = function (object, names) {
309 var O = _toIobject(object);
310 var i = 0;
311 var result = [];
312 var key;
313 for (key in O) if (key != IE_PROTO) _has(O, key) && result.push(key);
314 // Don't enum bug & hidden keys
315 while (names.length > i) if (_has(O, key = names[i++])) {
316 ~arrayIndexOf(result, key) || result.push(key);
317 }
318 return result;
319 };
320
321 // IE 8- don't enum bug keys
322 var _enumBugKeys = (
323 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
324 ).split(',');
325
326 // 19.1.2.14 / 15.2.3.14 Object.keys(O)
327
328
329
330 var _objectKeys = Object.keys || function keys(O) {
331 return _objectKeysInternal(O, _enumBugKeys);
332 };
333
334 var f$1 = Object.getOwnPropertySymbols;
335
336 var _objectGops = {
337 f: f$1
338 };
339
340 var f$2 = {}.propertyIsEnumerable;
341
342 var _objectPie = {
343 f: f$2
344 };
345
346 // 7.1.13 ToObject(argument)
347
348 var _toObject = function (it) {
349 return Object(_defined(it));
350 };
351
352 // 19.1.2.1 Object.assign(target, source, ...)
353
354
355
356
357
358 var $assign = Object.assign;
359
360 // should work with symbols and should have deterministic property order (V8 bug)
361 var _objectAssign = !$assign || _fails(function () {
362 var A = {};
363 var B = {};
364 // eslint-disable-next-line no-undef
365 var S = Symbol();
366 var K = 'abcdefghijklmnopqrst';
367 A[S] = 7;
368 K.split('').forEach(function (k) { B[k] = k; });
369 return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
370 }) ? function assign(target, source) { // eslint-disable-line no-unused-vars
371 var T = _toObject(target);
372 var aLen = arguments.length;
373 var index = 1;
374 var getSymbols = _objectGops.f;
375 var isEnum = _objectPie.f;
376 while (aLen > index) {
377 var S = _iobject(arguments[index++]);
378 var keys = getSymbols ? _objectKeys(S).concat(getSymbols(S)) : _objectKeys(S);
379 var length = keys.length;
380 var j = 0;
381 var key;
382 while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key];
383 } return T;
384 } : $assign;
385
386 // 19.1.3.1 Object.assign(target, source)
387
388
389 _export(_export.S + _export.F, 'Object', { assign: _objectAssign });
390
391 function _typeof(obj) {
392 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
393 _typeof = function (obj) {
394 return typeof obj;
395 };
396 } else {
397 _typeof = function (obj) {
398 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
399 };
400 }
401
402 return _typeof(obj);
403 }
404
405 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
406 try {
407 var info = gen[key](arg);
408 var value = info.value;
409 } catch (error) {
410 reject(error);
411 return;
412 }
413
414 if (info.done) {
415 resolve(value);
416 } else {
417 Promise.resolve(value).then(_next, _throw);
418 }
419 }
420
421 function _asyncToGenerator(fn) {
422 return function () {
423 var self = this,
424 args = arguments;
425 return new Promise(function (resolve, reject) {
426 var gen = fn.apply(self, args);
427
428 function _next(value) {
429 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
430 }
431
432 function _throw(err) {
433 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
434 }
435
436 _next(undefined);
437 });
438 };
439 }
440
441 function _classCallCheck(instance, Constructor) {
442 if (!(instance instanceof Constructor)) {
443 throw new TypeError("Cannot call a class as a function");
444 }
445 }
446
447 function _defineProperties(target, props) {
448 for (var i = 0; i < props.length; i++) {
449 var descriptor = props[i];
450 descriptor.enumerable = descriptor.enumerable || false;
451 descriptor.configurable = true;
452 if ("value" in descriptor) descriptor.writable = true;
453 Object.defineProperty(target, descriptor.key, descriptor);
454 }
455 }
456
457 function _createClass(Constructor, protoProps, staticProps) {
458 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
459 if (staticProps) _defineProperties(Constructor, staticProps);
460 return Constructor;
461 }
462
463 function _defineProperty(obj, key, value) {
464 if (key in obj) {
465 Object.defineProperty(obj, key, {
466 value: value,
467 enumerable: true,
468 configurable: true,
469 writable: true
470 });
471 } else {
472 obj[key] = value;
473 }
474
475 return obj;
476 }
477
478 function _toConsumableArray(arr) {
479 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
480 }
481
482 function _arrayWithoutHoles(arr) {
483 if (Array.isArray(arr)) {
484 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
485
486 return arr2;
487 }
488 }
489
490 function _iterableToArray(iter) {
491 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
492 }
493
494 function _nonIterableSpread() {
495 throw new TypeError("Invalid attempt to spread non-iterable instance");
496 }
497
498 /**
499 * @class Model
500 * @namespace Daux.Core
501 */
502 var Model =
503 /*#__PURE__*/
504 function () {
505 function Model() {
506 _classCallCheck(this, Model);
507 }
508
509 _createClass(Model, null, [{
510 key: "deserialize",
511
512 /**
513 * @param {Object} record
514 * @return {Object} Deserialized record
515 * @function
516 */
517 value: function deserialize(record) {
518 return Object.assign({}, record);
519 }
520 }, {
521 key: "attributes",
522
523 /**
524 * @type {Array}
525 */
526 get: function get() {
527 return [];
528 }
529 /**
530 * @type {Object}
531 */
532
533 }, {
534 key: "relationship",
535 get: function get() {
536 return {};
537 }
538 }]);
539
540 return Model;
541 }();
542
543 var _wks = createCommonjsModule(function (module) {
544 var store = _shared('wks');
545
546 var Symbol = _global.Symbol;
547 var USE_SYMBOL = typeof Symbol == 'function';
548
549 var $exports = module.exports = function (name) {
550 return store[name] || (store[name] =
551 USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : _uid)('Symbol.' + name));
552 };
553
554 $exports.store = store;
555 });
556
557 // 22.1.3.31 Array.prototype[@@unscopables]
558 var UNSCOPABLES = _wks('unscopables');
559 var ArrayProto = Array.prototype;
560 if (ArrayProto[UNSCOPABLES] == undefined) _hide(ArrayProto, UNSCOPABLES, {});
561 var _addToUnscopables = function (key) {
562 ArrayProto[UNSCOPABLES][key] = true;
563 };
564
565 // https://github.com/tc39/Array.prototype.includes
566
567 var $includes = _arrayIncludes(true);
568
569 _export(_export.P, 'Array', {
570 includes: function includes(el /* , fromIndex = 0 */) {
571 return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
572 }
573 });
574
575 _addToUnscopables('includes');
576
577 // 7.2.8 IsRegExp(argument)
578
579
580 var MATCH = _wks('match');
581 var _isRegexp = function (it) {
582 var isRegExp;
583 return _isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : _cof(it) == 'RegExp');
584 };
585
586 // helper for String#{startsWith, endsWith, includes}
587
588
589
590 var _stringContext = function (that, searchString, NAME) {
591 if (_isRegexp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!");
592 return String(_defined(that));
593 };
594
595 var MATCH$1 = _wks('match');
596 var _failsIsRegexp = function (KEY) {
597 var re = /./;
598 try {
599 '/./'[KEY](re);
600 } catch (e) {
601 try {
602 re[MATCH$1] = false;
603 return !'/./'[KEY](re);
604 } catch (f) { /* empty */ }
605 } return true;
606 };
607
608 var INCLUDES = 'includes';
609
610 _export(_export.P + _export.F * _failsIsRegexp(INCLUDES), 'String', {
611 includes: function includes(searchString /* , position = 0 */) {
612 return !!~_stringContext(this, searchString, INCLUDES)
613 .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
614 }
615 });
616
617 var _objectDps = _descriptors ? Object.defineProperties : function defineProperties(O, Properties) {
618 _anObject(O);
619 var keys = _objectKeys(Properties);
620 var length = keys.length;
621 var i = 0;
622 var P;
623 while (length > i) _objectDp.f(O, P = keys[i++], Properties[P]);
624 return O;
625 };
626
627 var document$2 = _global.document;
628 var _html = document$2 && document$2.documentElement;
629
630 // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
631
632
633
634 var IE_PROTO$1 = _sharedKey('IE_PROTO');
635 var Empty = function () { /* empty */ };
636 var PROTOTYPE$1 = 'prototype';
637
638 // Create object with fake `null` prototype: use iframe Object with cleared prototype
639 var createDict = function () {
640 // Thrash, waste and sodomy: IE GC bug
641 var iframe = _domCreate('iframe');
642 var i = _enumBugKeys.length;
643 var lt = '<';
644 var gt = '>';
645 var iframeDocument;
646 iframe.style.display = 'none';
647 _html.appendChild(iframe);
648 iframe.src = 'javascript:'; // eslint-disable-line no-script-url
649 // createDict = iframe.contentWindow.Object;
650 // html.removeChild(iframe);
651 iframeDocument = iframe.contentWindow.document;
652 iframeDocument.open();
653 iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
654 iframeDocument.close();
655 createDict = iframeDocument.F;
656 while (i--) delete createDict[PROTOTYPE$1][_enumBugKeys[i]];
657 return createDict();
658 };
659
660 var _objectCreate = Object.create || function create(O, Properties) {
661 var result;
662 if (O !== null) {
663 Empty[PROTOTYPE$1] = _anObject(O);
664 result = new Empty();
665 Empty[PROTOTYPE$1] = null;
666 // add "__proto__" for Object.getPrototypeOf polyfill
667 result[IE_PROTO$1] = O;
668 } else result = createDict();
669 return Properties === undefined ? result : _objectDps(result, Properties);
670 };
671
672 var _redefineAll = function (target, src, safe) {
673 for (var key in src) _redefine(target, key, src[key], safe);
674 return target;
675 };
676
677 var _anInstance = function (it, Constructor, name, forbiddenField) {
678 if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) {
679 throw TypeError(name + ': incorrect invocation!');
680 } return it;
681 };
682
683 // call something on iterator step with safe closing on error
684
685 var _iterCall = function (iterator, fn, value, entries) {
686 try {
687 return entries ? fn(_anObject(value)[0], value[1]) : fn(value);
688 // 7.4.6 IteratorClose(iterator, completion)
689 } catch (e) {
690 var ret = iterator['return'];
691 if (ret !== undefined) _anObject(ret.call(iterator));
692 throw e;
693 }
694 };
695
696 var _iterators = {};
697
698 // check on default Array iterator
699
700 var ITERATOR = _wks('iterator');
701 var ArrayProto$1 = Array.prototype;
702
703 var _isArrayIter = function (it) {
704 return it !== undefined && (_iterators.Array === it || ArrayProto$1[ITERATOR] === it);
705 };
706
707 // getting tag from 19.1.3.6 Object.prototype.toString()
708
709 var TAG = _wks('toStringTag');
710 // ES3 wrong here
711 var ARG = _cof(function () { return arguments; }()) == 'Arguments';
712
713 // fallback for IE11 Script Access Denied error
714 var tryGet = function (it, key) {
715 try {
716 return it[key];
717 } catch (e) { /* empty */ }
718 };
719
720 var _classof = function (it) {
721 var O, T, B;
722 return it === undefined ? 'Undefined' : it === null ? 'Null'
723 // @@toStringTag case
724 : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
725 // builtinTag case
726 : ARG ? _cof(O)
727 // ES3 arguments fallback
728 : (B = _cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
729 };
730
731 var ITERATOR$1 = _wks('iterator');
732
733 var core_getIteratorMethod = _core.getIteratorMethod = function (it) {
734 if (it != undefined) return it[ITERATOR$1]
735 || it['@@iterator']
736 || _iterators[_classof(it)];
737 };
738
739 var _forOf = createCommonjsModule(function (module) {
740 var BREAK = {};
741 var RETURN = {};
742 var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {
743 var iterFn = ITERATOR ? function () { return iterable; } : core_getIteratorMethod(iterable);
744 var f = _ctx(fn, that, entries ? 2 : 1);
745 var index = 0;
746 var length, step, iterator, result;
747 if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');
748 // fast case for arrays with default iterator
749 if (_isArrayIter(iterFn)) for (length = _toLength(iterable.length); length > index; index++) {
750 result = entries ? f(_anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
751 if (result === BREAK || result === RETURN) return result;
752 } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {
753 result = _iterCall(iterator, f, step.value, entries);
754 if (result === BREAK || result === RETURN) return result;
755 }
756 };
757 exports.BREAK = BREAK;
758 exports.RETURN = RETURN;
759 });
760
761 var def = _objectDp.f;
762
763 var TAG$1 = _wks('toStringTag');
764
765 var _setToStringTag = function (it, tag, stat) {
766 if (it && !_has(it = stat ? it : it.prototype, TAG$1)) def(it, TAG$1, { configurable: true, value: tag });
767 };
768
769 var IteratorPrototype = {};
770
771 // 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
772 _hide(IteratorPrototype, _wks('iterator'), function () { return this; });
773
774 var _iterCreate = function (Constructor, NAME, next) {
775 Constructor.prototype = _objectCreate(IteratorPrototype, { next: _propertyDesc(1, next) });
776 _setToStringTag(Constructor, NAME + ' Iterator');
777 };
778
779 // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
780
781
782 var IE_PROTO$2 = _sharedKey('IE_PROTO');
783 var ObjectProto = Object.prototype;
784
785 var _objectGpo = Object.getPrototypeOf || function (O) {
786 O = _toObject(O);
787 if (_has(O, IE_PROTO$2)) return O[IE_PROTO$2];
788 if (typeof O.constructor == 'function' && O instanceof O.constructor) {
789 return O.constructor.prototype;
790 } return O instanceof Object ? ObjectProto : null;
791 };
792
793 var ITERATOR$2 = _wks('iterator');
794 var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
795 var FF_ITERATOR = '@@iterator';
796 var KEYS = 'keys';
797 var VALUES = 'values';
798
799 var returnThis = function () { return this; };
800
801 var _iterDefine = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
802 _iterCreate(Constructor, NAME, next);
803 var getMethod = function (kind) {
804 if (!BUGGY && kind in proto) return proto[kind];
805 switch (kind) {
806 case KEYS: return function keys() { return new Constructor(this, kind); };
807 case VALUES: return function values() { return new Constructor(this, kind); };
808 } return function entries() { return new Constructor(this, kind); };
809 };
810 var TAG = NAME + ' Iterator';
811 var DEF_VALUES = DEFAULT == VALUES;
812 var VALUES_BUG = false;
813 var proto = Base.prototype;
814 var $native = proto[ITERATOR$2] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
815 var $default = $native || getMethod(DEFAULT);
816 var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
817 var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
818 var methods, key, IteratorPrototype;
819 // Fix native
820 if ($anyNative) {
821 IteratorPrototype = _objectGpo($anyNative.call(new Base()));
822 if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
823 // Set @@toStringTag to native iterators
824 _setToStringTag(IteratorPrototype, TAG, true);
825 // fix for some old engines
826 if (typeof IteratorPrototype[ITERATOR$2] != 'function') _hide(IteratorPrototype, ITERATOR$2, returnThis);
827 }
828 }
829 // fix Array#{values, @@iterator}.name in V8 / FF
830 if (DEF_VALUES && $native && $native.name !== VALUES) {
831 VALUES_BUG = true;
832 $default = function values() { return $native.call(this); };
833 }
834 // Define iterator
835 if (BUGGY || VALUES_BUG || !proto[ITERATOR$2]) {
836 _hide(proto, ITERATOR$2, $default);
837 }
838 // Plug for library
839 _iterators[NAME] = $default;
840 _iterators[TAG] = returnThis;
841 if (DEFAULT) {
842 methods = {
843 values: DEF_VALUES ? $default : getMethod(VALUES),
844 keys: IS_SET ? $default : getMethod(KEYS),
845 entries: $entries
846 };
847 if (FORCED) for (key in methods) {
848 if (!(key in proto)) _redefine(proto, key, methods[key]);
849 } else _export(_export.P + _export.F * (BUGGY || VALUES_BUG), NAME, methods);
850 }
851 return methods;
852 };
853
854 var _iterStep = function (done, value) {
855 return { value: value, done: !!done };
856 };
857
858 var SPECIES = _wks('species');
859
860 var _setSpecies = function (KEY) {
861 var C = _global[KEY];
862 if (_descriptors && C && !C[SPECIES]) _objectDp.f(C, SPECIES, {
863 configurable: true,
864 get: function () { return this; }
865 });
866 };
867
868 var _meta = createCommonjsModule(function (module) {
869 var META = _uid('meta');
870
871
872 var setDesc = _objectDp.f;
873 var id = 0;
874 var isExtensible = Object.isExtensible || function () {
875 return true;
876 };
877 var FREEZE = !_fails(function () {
878 return isExtensible(Object.preventExtensions({}));
879 });
880 var setMeta = function (it) {
881 setDesc(it, META, { value: {
882 i: 'O' + ++id, // object ID
883 w: {} // weak collections IDs
884 } });
885 };
886 var fastKey = function (it, create) {
887 // return primitive with prefix
888 if (!_isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
889 if (!_has(it, META)) {
890 // can't set metadata to uncaught frozen object
891 if (!isExtensible(it)) return 'F';
892 // not necessary to add metadata
893 if (!create) return 'E';
894 // add missing metadata
895 setMeta(it);
896 // return object ID
897 } return it[META].i;
898 };
899 var getWeak = function (it, create) {
900 if (!_has(it, META)) {
901 // can't set metadata to uncaught frozen object
902 if (!isExtensible(it)) return true;
903 // not necessary to add metadata
904 if (!create) return false;
905 // add missing metadata
906 setMeta(it);
907 // return hash weak collections IDs
908 } return it[META].w;
909 };
910 // add metadata on freeze-family methods calling
911 var onFreeze = function (it) {
912 if (FREEZE && meta.NEED && isExtensible(it) && !_has(it, META)) setMeta(it);
913 return it;
914 };
915 var meta = module.exports = {
916 KEY: META,
917 NEED: false,
918 fastKey: fastKey,
919 getWeak: getWeak,
920 onFreeze: onFreeze
921 };
922 });
923 var _meta_1 = _meta.KEY;
924 var _meta_2 = _meta.NEED;
925 var _meta_3 = _meta.fastKey;
926 var _meta_4 = _meta.getWeak;
927 var _meta_5 = _meta.onFreeze;
928
929 var _validateCollection = function (it, TYPE) {
930 if (!_isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!');
931 return it;
932 };
933
934 var dP$1 = _objectDp.f;
935
936
937
938
939
940
941
942
943
944 var fastKey = _meta.fastKey;
945
946 var SIZE = _descriptors ? '_s' : 'size';
947
948 var getEntry = function (that, key) {
949 // fast case
950 var index = fastKey(key);
951 var entry;
952 if (index !== 'F') return that._i[index];
953 // frozen object case
954 for (entry = that._f; entry; entry = entry.n) {
955 if (entry.k == key) return entry;
956 }
957 };
958
959 var _collectionStrong = {
960 getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
961 var C = wrapper(function (that, iterable) {
962 _anInstance(that, C, NAME, '_i');
963 that._t = NAME; // collection type
964 that._i = _objectCreate(null); // index
965 that._f = undefined; // first entry
966 that._l = undefined; // last entry
967 that[SIZE] = 0; // size
968 if (iterable != undefined) _forOf(iterable, IS_MAP, that[ADDER], that);
969 });
970 _redefineAll(C.prototype, {
971 // 23.1.3.1 Map.prototype.clear()
972 // 23.2.3.2 Set.prototype.clear()
973 clear: function clear() {
974 for (var that = _validateCollection(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) {
975 entry.r = true;
976 if (entry.p) entry.p = entry.p.n = undefined;
977 delete data[entry.i];
978 }
979 that._f = that._l = undefined;
980 that[SIZE] = 0;
981 },
982 // 23.1.3.3 Map.prototype.delete(key)
983 // 23.2.3.4 Set.prototype.delete(value)
984 'delete': function (key) {
985 var that = _validateCollection(this, NAME);
986 var entry = getEntry(that, key);
987 if (entry) {
988 var next = entry.n;
989 var prev = entry.p;
990 delete that._i[entry.i];
991 entry.r = true;
992 if (prev) prev.n = next;
993 if (next) next.p = prev;
994 if (that._f == entry) that._f = next;
995 if (that._l == entry) that._l = prev;
996 that[SIZE]--;
997 } return !!entry;
998 },
999 // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
1000 // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
1001 forEach: function forEach(callbackfn /* , that = undefined */) {
1002 _validateCollection(this, NAME);
1003 var f = _ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);
1004 var entry;
1005 while (entry = entry ? entry.n : this._f) {
1006 f(entry.v, entry.k, this);
1007 // revert to the last existing entry
1008 while (entry && entry.r) entry = entry.p;
1009 }
1010 },
1011 // 23.1.3.7 Map.prototype.has(key)
1012 // 23.2.3.7 Set.prototype.has(value)
1013 has: function has(key) {
1014 return !!getEntry(_validateCollection(this, NAME), key);
1015 }
1016 });
1017 if (_descriptors) dP$1(C.prototype, 'size', {
1018 get: function () {
1019 return _validateCollection(this, NAME)[SIZE];
1020 }
1021 });
1022 return C;
1023 },
1024 def: function (that, key, value) {
1025 var entry = getEntry(that, key);
1026 var prev, index;
1027 // change existing entry
1028 if (entry) {
1029 entry.v = value;
1030 // create new entry
1031 } else {
1032 that._l = entry = {
1033 i: index = fastKey(key, true), // <- index
1034 k: key, // <- key
1035 v: value, // <- value
1036 p: prev = that._l, // <- previous entry
1037 n: undefined, // <- next entry
1038 r: false // <- removed
1039 };
1040 if (!that._f) that._f = entry;
1041 if (prev) prev.n = entry;
1042 that[SIZE]++;
1043 // add to index
1044 if (index !== 'F') that._i[index] = entry;
1045 } return that;
1046 },
1047 getEntry: getEntry,
1048 setStrong: function (C, NAME, IS_MAP) {
1049 // add .keys, .values, .entries, [@@iterator]
1050 // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
1051 _iterDefine(C, NAME, function (iterated, kind) {
1052 this._t = _validateCollection(iterated, NAME); // target
1053 this._k = kind; // kind
1054 this._l = undefined; // previous
1055 }, function () {
1056 var that = this;
1057 var kind = that._k;
1058 var entry = that._l;
1059 // revert to the last existing entry
1060 while (entry && entry.r) entry = entry.p;
1061 // get next entry
1062 if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) {
1063 // or finish the iteration
1064 that._t = undefined;
1065 return _iterStep(1);
1066 }
1067 // return step by kind
1068 if (kind == 'keys') return _iterStep(0, entry.k);
1069 if (kind == 'values') return _iterStep(0, entry.v);
1070 return _iterStep(0, [entry.k, entry.v]);
1071 }, IS_MAP ? 'entries' : 'values', !IS_MAP, true);
1072
1073 // add [@@species], 23.1.2.2, 23.2.2.2
1074 _setSpecies(NAME);
1075 }
1076 };
1077
1078 var ITERATOR$3 = _wks('iterator');
1079 var SAFE_CLOSING = false;
1080
1081 try {
1082 var riter = [7][ITERATOR$3]();
1083 riter['return'] = function () { SAFE_CLOSING = true; };
1084 } catch (e) { /* empty */ }
1085
1086 var _iterDetect = function (exec, skipClosing) {
1087 if (!skipClosing && !SAFE_CLOSING) return false;
1088 var safe = false;
1089 try {
1090 var arr = [7];
1091 var iter = arr[ITERATOR$3]();
1092 iter.next = function () { return { done: safe = true }; };
1093 arr[ITERATOR$3] = function () { return iter; };
1094 exec(arr);
1095 } catch (e) { /* empty */ }
1096 return safe;
1097 };
1098
1099 var gOPD = Object.getOwnPropertyDescriptor;
1100
1101 var f$3 = _descriptors ? gOPD : function getOwnPropertyDescriptor(O, P) {
1102 O = _toIobject(O);
1103 P = _toPrimitive(P, true);
1104 if (_ie8DomDefine) try {
1105 return gOPD(O, P);
1106 } catch (e) { /* empty */ }
1107 if (_has(O, P)) return _propertyDesc(!_objectPie.f.call(O, P), O[P]);
1108 };
1109
1110 var _objectGopd = {
1111 f: f$3
1112 };
1113
1114 // Works with __proto__ only. Old v8 can't work with null proto objects.
1115 /* eslint-disable no-proto */
1116
1117
1118 var check = function (O, proto) {
1119 _anObject(O);
1120 if (!_isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
1121 };
1122 var _setProto = {
1123 set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
1124 function (test, buggy, set) {
1125 try {
1126 set = _ctx(Function.call, _objectGopd.f(Object.prototype, '__proto__').set, 2);
1127 set(test, []);
1128 buggy = !(test instanceof Array);
1129 } catch (e) { buggy = true; }
1130 return function setPrototypeOf(O, proto) {
1131 check(O, proto);
1132 if (buggy) O.__proto__ = proto;
1133 else set(O, proto);
1134 return O;
1135 };
1136 }({}, false) : undefined),
1137 check: check
1138 };
1139
1140 var setPrototypeOf = _setProto.set;
1141 var _inheritIfRequired = function (that, target, C) {
1142 var S = target.constructor;
1143 var P;
1144 if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && _isObject(P) && setPrototypeOf) {
1145 setPrototypeOf(that, P);
1146 } return that;
1147 };
1148
1149 var _collection = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) {
1150 var Base = _global[NAME];
1151 var C = Base;
1152 var ADDER = IS_MAP ? 'set' : 'add';
1153 var proto = C && C.prototype;
1154 var O = {};
1155 var fixMethod = function (KEY) {
1156 var fn = proto[KEY];
1157 _redefine(proto, KEY,
1158 KEY == 'delete' ? function (a) {
1159 return IS_WEAK && !_isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
1160 } : KEY == 'has' ? function has(a) {
1161 return IS_WEAK && !_isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
1162 } : KEY == 'get' ? function get(a) {
1163 return IS_WEAK && !_isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
1164 } : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; }
1165 : function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; }
1166 );
1167 };
1168 if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !_fails(function () {
1169 new C().entries().next();
1170 }))) {
1171 // create collection constructor
1172 C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
1173 _redefineAll(C.prototype, methods);
1174 _meta.NEED = true;
1175 } else {
1176 var instance = new C();
1177 // early implementations not supports chaining
1178 var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;
1179 // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
1180 var THROWS_ON_PRIMITIVES = _fails(function () { instance.has(1); });
1181 // most early implementations doesn't supports iterables, most modern - not close it correctly
1182 var ACCEPT_ITERABLES = _iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new
1183 // for early implementations -0 and +0 not the same
1184 var BUGGY_ZERO = !IS_WEAK && _fails(function () {
1185 // V8 ~ Chromium 42- fails only with 5+ elements
1186 var $instance = new C();
1187 var index = 5;
1188 while (index--) $instance[ADDER](index, index);
1189 return !$instance.has(-0);
1190 });
1191 if (!ACCEPT_ITERABLES) {
1192 C = wrapper(function (target, iterable) {
1193 _anInstance(target, C, NAME);
1194 var that = _inheritIfRequired(new Base(), target, C);
1195 if (iterable != undefined) _forOf(iterable, IS_MAP, that[ADDER], that);
1196 return that;
1197 });
1198 C.prototype = proto;
1199 proto.constructor = C;
1200 }
1201 if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {
1202 fixMethod('delete');
1203 fixMethod('has');
1204 IS_MAP && fixMethod('get');
1205 }
1206 if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);
1207 // weak collections should not contains .clear method
1208 if (IS_WEAK && proto.clear) delete proto.clear;
1209 }
1210
1211 _setToStringTag(C, NAME);
1212
1213 O[NAME] = C;
1214 _export(_export.G + _export.W + _export.F * (C != Base), O);
1215
1216 if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP);
1217
1218 return C;
1219 };
1220
1221 var SET = 'Set';
1222
1223 // 23.2 Set Objects
1224 var es6_set = _collection(SET, function (get) {
1225 return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
1226 }, {
1227 // 23.2.3.1 Set.prototype.add(value)
1228 add: function add(value) {
1229 return _collectionStrong.def(_validateCollection(this, SET), value = value === 0 ? 0 : value, value);
1230 }
1231 }, _collectionStrong);
1232
1233 // 7.2.2 IsArray(argument)
1234
1235 var _isArray = Array.isArray || function isArray(arg) {
1236 return _cof(arg) == 'Array';
1237 };
1238
1239 var SPECIES$1 = _wks('species');
1240
1241 var _arraySpeciesConstructor = function (original) {
1242 var C;
1243 if (_isArray(original)) {
1244 C = original.constructor;
1245 // cross-realm fallback
1246 if (typeof C == 'function' && (C === Array || _isArray(C.prototype))) C = undefined;
1247 if (_isObject(C)) {
1248 C = C[SPECIES$1];
1249 if (C === null) C = undefined;
1250 }
1251 } return C === undefined ? Array : C;
1252 };
1253
1254 // 9.4.2.3 ArraySpeciesCreate(originalArray, length)
1255
1256
1257 var _arraySpeciesCreate = function (original, length) {
1258 return new (_arraySpeciesConstructor(original))(length);
1259 };
1260
1261 // 0 -> Array#forEach
1262 // 1 -> Array#map
1263 // 2 -> Array#filter
1264 // 3 -> Array#some
1265 // 4 -> Array#every
1266 // 5 -> Array#find
1267 // 6 -> Array#findIndex
1268
1269
1270
1271
1272
1273 var _arrayMethods = function (TYPE, $create) {
1274 var IS_MAP = TYPE == 1;
1275 var IS_FILTER = TYPE == 2;
1276 var IS_SOME = TYPE == 3;
1277 var IS_EVERY = TYPE == 4;
1278 var IS_FIND_INDEX = TYPE == 6;
1279 var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
1280 var create = $create || _arraySpeciesCreate;
1281 return function ($this, callbackfn, that) {
1282 var O = _toObject($this);
1283 var self = _iobject(O);
1284 var f = _ctx(callbackfn, that, 3);
1285 var length = _toLength(self.length);
1286 var index = 0;
1287 var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
1288 var val, res;
1289 for (;length > index; index++) if (NO_HOLES || index in self) {
1290 val = self[index];
1291 res = f(val, index, O);
1292 if (TYPE) {
1293 if (IS_MAP) result[index] = res; // map
1294 else if (res) switch (TYPE) {
1295 case 3: return true; // some
1296 case 5: return val; // find
1297 case 6: return index; // findIndex
1298 case 2: result.push(val); // filter
1299 } else if (IS_EVERY) return false; // every
1300 }
1301 }
1302 return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
1303 };
1304 };
1305
1306 // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
1307
1308 var $find = _arrayMethods(5);
1309 var KEY = 'find';
1310 var forced = true;
1311 // Shouldn't skip holes
1312 if (KEY in []) Array(1)[KEY](function () { forced = false; });
1313 _export(_export.P + _export.F * forced, 'Array', {
1314 find: function find(callbackfn /* , that = undefined */) {
1315 return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
1316 }
1317 });
1318 _addToUnscopables(KEY);
1319
1320 // 21.2.5.3 get RegExp.prototype.flags
1321
1322 var _flags = function () {
1323 var that = _anObject(this);
1324 var result = '';
1325 if (that.global) result += 'g';
1326 if (that.ignoreCase) result += 'i';
1327 if (that.multiline) result += 'm';
1328 if (that.unicode) result += 'u';
1329 if (that.sticky) result += 'y';
1330 return result;
1331 };
1332
1333 // 21.2.5.3 get RegExp.prototype.flags()
1334 if (_descriptors && /./g.flags != 'g') _objectDp.f(RegExp.prototype, 'flags', {
1335 configurable: true,
1336 get: _flags
1337 });
1338
1339 var TO_STRING = 'toString';
1340 var $toString = /./[TO_STRING];
1341
1342 var define = function (fn) {
1343 _redefine(RegExp.prototype, TO_STRING, fn, true);
1344 };
1345
1346 // 21.2.5.14 RegExp.prototype.toString()
1347 if (_fails(function () { return $toString.call({ source: 'a', flags: 'b' }) != '/a/b'; })) {
1348 define(function toString() {
1349 var R = _anObject(this);
1350 return '/'.concat(R.source, '/',
1351 'flags' in R ? R.flags : !_descriptors && R instanceof RegExp ? _flags.call(R) : undefined);
1352 });
1353 // FF44- RegExp#toString has a wrong name
1354 } else if ($toString.name != TO_STRING) {
1355 define(function toString() {
1356 return $toString.call(this);
1357 });
1358 }
1359
1360 // most Object methods by ES6 should accept primitives
1361
1362
1363
1364 var _objectSap = function (KEY, exec) {
1365 var fn = (_core.Object || {})[KEY] || Object[KEY];
1366 var exp = {};
1367 exp[KEY] = exec(fn);
1368 _export(_export.S + _export.F * _fails(function () { fn(1); }), 'Object', exp);
1369 };
1370
1371 // 19.1.2.14 Object.keys(O)
1372
1373
1374
1375 _objectSap('keys', function () {
1376 return function keys(it) {
1377 return _objectKeys(_toObject(it));
1378 };
1379 });
1380
1381 // 7.3.20 SpeciesConstructor(O, defaultConstructor)
1382
1383
1384 var SPECIES$2 = _wks('species');
1385 var _speciesConstructor = function (O, D) {
1386 var C = _anObject(O).constructor;
1387 var S;
1388 return C === undefined || (S = _anObject(C)[SPECIES$2]) == undefined ? D : _aFunction(S);
1389 };
1390
1391 // fast apply, http://jsperf.lnkit.com/fast-apply/5
1392 var _invoke = function (fn, args, that) {
1393 var un = that === undefined;
1394 switch (args.length) {
1395 case 0: return un ? fn()
1396 : fn.call(that);
1397 case 1: return un ? fn(args[0])
1398 : fn.call(that, args[0]);
1399 case 2: return un ? fn(args[0], args[1])
1400 : fn.call(that, args[0], args[1]);
1401 case 3: return un ? fn(args[0], args[1], args[2])
1402 : fn.call(that, args[0], args[1], args[2]);
1403 case 4: return un ? fn(args[0], args[1], args[2], args[3])
1404 : fn.call(that, args[0], args[1], args[2], args[3]);
1405 } return fn.apply(that, args);
1406 };
1407
1408 var process = _global.process;
1409 var setTask = _global.setImmediate;
1410 var clearTask = _global.clearImmediate;
1411 var MessageChannel = _global.MessageChannel;
1412 var Dispatch = _global.Dispatch;
1413 var counter = 0;
1414 var queue = {};
1415 var ONREADYSTATECHANGE = 'onreadystatechange';
1416 var defer, channel, port;
1417 var run = function () {
1418 var id = +this;
1419 // eslint-disable-next-line no-prototype-builtins
1420 if (queue.hasOwnProperty(id)) {
1421 var fn = queue[id];
1422 delete queue[id];
1423 fn();
1424 }
1425 };
1426 var listener = function (event) {
1427 run.call(event.data);
1428 };
1429 // Node.js 0.9+ & IE10+ has setImmediate, otherwise:
1430 if (!setTask || !clearTask) {
1431 setTask = function setImmediate(fn) {
1432 var args = [];
1433 var i = 1;
1434 while (arguments.length > i) args.push(arguments[i++]);
1435 queue[++counter] = function () {
1436 // eslint-disable-next-line no-new-func
1437 _invoke(typeof fn == 'function' ? fn : Function(fn), args);
1438 };
1439 defer(counter);
1440 return counter;
1441 };
1442 clearTask = function clearImmediate(id) {
1443 delete queue[id];
1444 };
1445 // Node.js 0.8-
1446 if (_cof(process) == 'process') {
1447 defer = function (id) {
1448 process.nextTick(_ctx(run, id, 1));
1449 };
1450 // Sphere (JS game engine) Dispatch API
1451 } else if (Dispatch && Dispatch.now) {
1452 defer = function (id) {
1453 Dispatch.now(_ctx(run, id, 1));
1454 };
1455 // Browsers with MessageChannel, includes WebWorkers
1456 } else if (MessageChannel) {
1457 channel = new MessageChannel();
1458 port = channel.port2;
1459 channel.port1.onmessage = listener;
1460 defer = _ctx(port.postMessage, port, 1);
1461 // Browsers with postMessage, skip WebWorkers
1462 // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
1463 } else if (_global.addEventListener && typeof postMessage == 'function' && !_global.importScripts) {
1464 defer = function (id) {
1465 _global.postMessage(id + '', '*');
1466 };
1467 _global.addEventListener('message', listener, false);
1468 // IE8-
1469 } else if (ONREADYSTATECHANGE in _domCreate('script')) {
1470 defer = function (id) {
1471 _html.appendChild(_domCreate('script'))[ONREADYSTATECHANGE] = function () {
1472 _html.removeChild(this);
1473 run.call(id);
1474 };
1475 };
1476 // Rest old browsers
1477 } else {
1478 defer = function (id) {
1479 setTimeout(_ctx(run, id, 1), 0);
1480 };
1481 }
1482 }
1483 var _task = {
1484 set: setTask,
1485 clear: clearTask
1486 };
1487
1488 var macrotask = _task.set;
1489 var Observer = _global.MutationObserver || _global.WebKitMutationObserver;
1490 var process$1 = _global.process;
1491 var Promise$1 = _global.Promise;
1492 var isNode = _cof(process$1) == 'process';
1493
1494 var _microtask = function () {
1495 var head, last, notify;
1496
1497 var flush = function () {
1498 var parent, fn;
1499 if (isNode && (parent = process$1.domain)) parent.exit();
1500 while (head) {
1501 fn = head.fn;
1502 head = head.next;
1503 try {
1504 fn();
1505 } catch (e) {
1506 if (head) notify();
1507 else last = undefined;
1508 throw e;
1509 }
1510 } last = undefined;
1511 if (parent) parent.enter();
1512 };
1513
1514 // Node.js
1515 if (isNode) {
1516 notify = function () {
1517 process$1.nextTick(flush);
1518 };
1519 // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339
1520 } else if (Observer && !(_global.navigator && _global.navigator.standalone)) {
1521 var toggle = true;
1522 var node = document.createTextNode('');
1523 new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new
1524 notify = function () {
1525 node.data = toggle = !toggle;
1526 };
1527 // environments with maybe non-completely correct, but existent Promise
1528 } else if (Promise$1 && Promise$1.resolve) {
1529 // Promise.resolve without an argument throws an error in LG WebOS 2
1530 var promise = Promise$1.resolve(undefined);
1531 notify = function () {
1532 promise.then(flush);
1533 };
1534 // for other environments - macrotask based on:
1535 // - setImmediate
1536 // - MessageChannel
1537 // - window.postMessag
1538 // - onreadystatechange
1539 // - setTimeout
1540 } else {
1541 notify = function () {
1542 // strange IE + webpack dev server bug - use .call(global)
1543 macrotask.call(_global, flush);
1544 };
1545 }
1546
1547 return function (fn) {
1548 var task = { fn: fn, next: undefined };
1549 if (last) last.next = task;
1550 if (!head) {
1551 head = task;
1552 notify();
1553 } last = task;
1554 };
1555 };
1556
1557 // 25.4.1.5 NewPromiseCapability(C)
1558
1559
1560 function PromiseCapability(C) {
1561 var resolve, reject;
1562 this.promise = new C(function ($$resolve, $$reject) {
1563 if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
1564 resolve = $$resolve;
1565 reject = $$reject;
1566 });
1567 this.resolve = _aFunction(resolve);
1568 this.reject = _aFunction(reject);
1569 }
1570
1571 var f$4 = function (C) {
1572 return new PromiseCapability(C);
1573 };
1574
1575 var _newPromiseCapability = {
1576 f: f$4
1577 };
1578
1579 var _perform = function (exec) {
1580 try {
1581 return { e: false, v: exec() };
1582 } catch (e) {
1583 return { e: true, v: e };
1584 }
1585 };
1586
1587 var navigator = _global.navigator;
1588
1589 var _userAgent = navigator && navigator.userAgent || '';
1590
1591 var _promiseResolve = function (C, x) {
1592 _anObject(C);
1593 if (_isObject(x) && x.constructor === C) return x;
1594 var promiseCapability = _newPromiseCapability.f(C);
1595 var resolve = promiseCapability.resolve;
1596 resolve(x);
1597 return promiseCapability.promise;
1598 };
1599
1600 var task = _task.set;
1601 var microtask = _microtask();
1602
1603
1604
1605
1606 var PROMISE = 'Promise';
1607 var TypeError$1 = _global.TypeError;
1608 var process$2 = _global.process;
1609 var versions = process$2 && process$2.versions;
1610 var v8 = versions && versions.v8 || '';
1611 var $Promise = _global[PROMISE];
1612 var isNode$1 = _classof(process$2) == 'process';
1613 var empty = function () { /* empty */ };
1614 var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
1615 var newPromiseCapability = newGenericPromiseCapability = _newPromiseCapability.f;
1616
1617 var USE_NATIVE = !!function () {
1618 try {
1619 // correct subclassing with @@species support
1620 var promise = $Promise.resolve(1);
1621 var FakePromise = (promise.constructor = {})[_wks('species')] = function (exec) {
1622 exec(empty, empty);
1623 };
1624 // unhandled rejections tracking support, NodeJS Promise without it fails @@species test
1625 return (isNode$1 || typeof PromiseRejectionEvent == 'function')
1626 && promise.then(empty) instanceof FakePromise
1627 // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
1628 // https://bugs.chromium.org/p/chromium/issues/detail?id=830565
1629 // we can't detect it synchronously, so just check versions
1630 && v8.indexOf('6.6') !== 0
1631 && _userAgent.indexOf('Chrome/66') === -1;
1632 } catch (e) { /* empty */ }
1633 }();
1634
1635 // helpers
1636 var isThenable = function (it) {
1637 var then;
1638 return _isObject(it) && typeof (then = it.then) == 'function' ? then : false;
1639 };
1640 var notify = function (promise, isReject) {
1641 if (promise._n) return;
1642 promise._n = true;
1643 var chain = promise._c;
1644 microtask(function () {
1645 var value = promise._v;
1646 var ok = promise._s == 1;
1647 var i = 0;
1648 var run = function (reaction) {
1649 var handler = ok ? reaction.ok : reaction.fail;
1650 var resolve = reaction.resolve;
1651 var reject = reaction.reject;
1652 var domain = reaction.domain;
1653 var result, then, exited;
1654 try {
1655 if (handler) {
1656 if (!ok) {
1657 if (promise._h == 2) onHandleUnhandled(promise);
1658 promise._h = 1;
1659 }
1660 if (handler === true) result = value;
1661 else {
1662 if (domain) domain.enter();
1663 result = handler(value); // may throw
1664 if (domain) {
1665 domain.exit();
1666 exited = true;
1667 }
1668 }
1669 if (result === reaction.promise) {
1670 reject(TypeError$1('Promise-chain cycle'));
1671 } else if (then = isThenable(result)) {
1672 then.call(result, resolve, reject);
1673 } else resolve(result);
1674 } else reject(value);
1675 } catch (e) {
1676 if (domain && !exited) domain.exit();
1677 reject(e);
1678 }
1679 };
1680 while (chain.length > i) run(chain[i++]); // variable length - can't use forEach
1681 promise._c = [];
1682 promise._n = false;
1683 if (isReject && !promise._h) onUnhandled(promise);
1684 });
1685 };
1686 var onUnhandled = function (promise) {
1687 task.call(_global, function () {
1688 var value = promise._v;
1689 var unhandled = isUnhandled(promise);
1690 var result, handler, console;
1691 if (unhandled) {
1692 result = _perform(function () {
1693 if (isNode$1) {
1694 process$2.emit('unhandledRejection', value, promise);
1695 } else if (handler = _global.onunhandledrejection) {
1696 handler({ promise: promise, reason: value });
1697 } else if ((console = _global.console) && console.error) {
1698 console.error('Unhandled promise rejection', value);
1699 }
1700 });
1701 // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
1702 promise._h = isNode$1 || isUnhandled(promise) ? 2 : 1;
1703 } promise._a = undefined;
1704 if (unhandled && result.e) throw result.v;
1705 });
1706 };
1707 var isUnhandled = function (promise) {
1708 return promise._h !== 1 && (promise._a || promise._c).length === 0;
1709 };
1710 var onHandleUnhandled = function (promise) {
1711 task.call(_global, function () {
1712 var handler;
1713 if (isNode$1) {
1714 process$2.emit('rejectionHandled', promise);
1715 } else if (handler = _global.onrejectionhandled) {
1716 handler({ promise: promise, reason: promise._v });
1717 }
1718 });
1719 };
1720 var $reject = function (value) {
1721 var promise = this;
1722 if (promise._d) return;
1723 promise._d = true;
1724 promise = promise._w || promise; // unwrap
1725 promise._v = value;
1726 promise._s = 2;
1727 if (!promise._a) promise._a = promise._c.slice();
1728 notify(promise, true);
1729 };
1730 var $resolve = function (value) {
1731 var promise = this;
1732 var then;
1733 if (promise._d) return;
1734 promise._d = true;
1735 promise = promise._w || promise; // unwrap
1736 try {
1737 if (promise === value) throw TypeError$1("Promise can't be resolved itself");
1738 if (then = isThenable(value)) {
1739 microtask(function () {
1740 var wrapper = { _w: promise, _d: false }; // wrap
1741 try {
1742 then.call(value, _ctx($resolve, wrapper, 1), _ctx($reject, wrapper, 1));
1743 } catch (e) {
1744 $reject.call(wrapper, e);
1745 }
1746 });
1747 } else {
1748 promise._v = value;
1749 promise._s = 1;
1750 notify(promise, false);
1751 }
1752 } catch (e) {
1753 $reject.call({ _w: promise, _d: false }, e); // wrap
1754 }
1755 };
1756
1757 // constructor polyfill
1758 if (!USE_NATIVE) {
1759 // 25.4.3.1 Promise(executor)
1760 $Promise = function Promise(executor) {
1761 _anInstance(this, $Promise, PROMISE, '_h');
1762 _aFunction(executor);
1763 Internal.call(this);
1764 try {
1765 executor(_ctx($resolve, this, 1), _ctx($reject, this, 1));
1766 } catch (err) {
1767 $reject.call(this, err);
1768 }
1769 };
1770 // eslint-disable-next-line no-unused-vars
1771 Internal = function Promise(executor) {
1772 this._c = []; // <- awaiting reactions
1773 this._a = undefined; // <- checked in isUnhandled reactions
1774 this._s = 0; // <- state
1775 this._d = false; // <- done
1776 this._v = undefined; // <- value
1777 this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
1778 this._n = false; // <- notify
1779 };
1780 Internal.prototype = _redefineAll($Promise.prototype, {
1781 // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
1782 then: function then(onFulfilled, onRejected) {
1783 var reaction = newPromiseCapability(_speciesConstructor(this, $Promise));
1784 reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
1785 reaction.fail = typeof onRejected == 'function' && onRejected;
1786 reaction.domain = isNode$1 ? process$2.domain : undefined;
1787 this._c.push(reaction);
1788 if (this._a) this._a.push(reaction);
1789 if (this._s) notify(this, false);
1790 return reaction.promise;
1791 },
1792 // 25.4.5.1 Promise.prototype.catch(onRejected)
1793 'catch': function (onRejected) {
1794 return this.then(undefined, onRejected);
1795 }
1796 });
1797 OwnPromiseCapability = function () {
1798 var promise = new Internal();
1799 this.promise = promise;
1800 this.resolve = _ctx($resolve, promise, 1);
1801 this.reject = _ctx($reject, promise, 1);
1802 };
1803 _newPromiseCapability.f = newPromiseCapability = function (C) {
1804 return C === $Promise || C === Wrapper
1805 ? new OwnPromiseCapability(C)
1806 : newGenericPromiseCapability(C);
1807 };
1808 }
1809
1810 _export(_export.G + _export.W + _export.F * !USE_NATIVE, { Promise: $Promise });
1811 _setToStringTag($Promise, PROMISE);
1812 _setSpecies(PROMISE);
1813 Wrapper = _core[PROMISE];
1814
1815 // statics
1816 _export(_export.S + _export.F * !USE_NATIVE, PROMISE, {
1817 // 25.4.4.5 Promise.reject(r)
1818 reject: function reject(r) {
1819 var capability = newPromiseCapability(this);
1820 var $$reject = capability.reject;
1821 $$reject(r);
1822 return capability.promise;
1823 }
1824 });
1825 _export(_export.S + _export.F * (_library || !USE_NATIVE), PROMISE, {
1826 // 25.4.4.6 Promise.resolve(x)
1827 resolve: function resolve(x) {
1828 return _promiseResolve(_library && this === Wrapper ? $Promise : this, x);
1829 }
1830 });
1831 _export(_export.S + _export.F * !(USE_NATIVE && _iterDetect(function (iter) {
1832 $Promise.all(iter)['catch'](empty);
1833 })), PROMISE, {
1834 // 25.4.4.1 Promise.all(iterable)
1835 all: function all(iterable) {
1836 var C = this;
1837 var capability = newPromiseCapability(C);
1838 var resolve = capability.resolve;
1839 var reject = capability.reject;
1840 var result = _perform(function () {
1841 var values = [];
1842 var index = 0;
1843 var remaining = 1;
1844 _forOf(iterable, false, function (promise) {
1845 var $index = index++;
1846 var alreadyCalled = false;
1847 values.push(undefined);
1848 remaining++;
1849 C.resolve(promise).then(function (value) {
1850 if (alreadyCalled) return;
1851 alreadyCalled = true;
1852 values[$index] = value;
1853 --remaining || resolve(values);
1854 }, reject);
1855 });
1856 --remaining || resolve(values);
1857 });
1858 if (result.e) reject(result.v);
1859 return capability.promise;
1860 },
1861 // 25.4.4.4 Promise.race(iterable)
1862 race: function race(iterable) {
1863 var C = this;
1864 var capability = newPromiseCapability(C);
1865 var reject = capability.reject;
1866 var result = _perform(function () {
1867 _forOf(iterable, false, function (promise) {
1868 C.resolve(promise).then(capability.resolve, reject);
1869 });
1870 });
1871 if (result.e) reject(result.v);
1872 return capability.promise;
1873 }
1874 });
1875
1876 // 22.1.3.4 Array.prototype.entries()
1877 // 22.1.3.13 Array.prototype.keys()
1878 // 22.1.3.29 Array.prototype.values()
1879 // 22.1.3.30 Array.prototype[@@iterator]()
1880 var es6_array_iterator = _iterDefine(Array, 'Array', function (iterated, kind) {
1881 this._t = _toIobject(iterated); // target
1882 this._i = 0; // next index
1883 this._k = kind; // kind
1884 // 22.1.5.2.1 %ArrayIteratorPrototype%.next()
1885 }, function () {
1886 var O = this._t;
1887 var kind = this._k;
1888 var index = this._i++;
1889 if (!O || index >= O.length) {
1890 this._t = undefined;
1891 return _iterStep(1);
1892 }
1893 if (kind == 'keys') return _iterStep(0, index);
1894 if (kind == 'values') return _iterStep(0, O[index]);
1895 return _iterStep(0, [index, O[index]]);
1896 }, 'values');
1897
1898 // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
1899 _iterators.Arguments = _iterators.Array;
1900
1901 _addToUnscopables('keys');
1902 _addToUnscopables('values');
1903 _addToUnscopables('entries');
1904
1905 // true -> String#at
1906 // false -> String#codePointAt
1907 var _stringAt = function (TO_STRING) {
1908 return function (that, pos) {
1909 var s = String(_defined(that));
1910 var i = _toInteger(pos);
1911 var l = s.length;
1912 var a, b;
1913 if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
1914 a = s.charCodeAt(i);
1915 return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
1916 ? TO_STRING ? s.charAt(i) : a
1917 : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
1918 };
1919 };
1920
1921 var $at = _stringAt(true);
1922
1923 // 21.1.3.27 String.prototype[@@iterator]()
1924 _iterDefine(String, 'String', function (iterated) {
1925 this._t = String(iterated); // target
1926 this._i = 0; // next index
1927 // 21.1.5.2.1 %StringIteratorPrototype%.next()
1928 }, function () {
1929 var O = this._t;
1930 var index = this._i;
1931 var point;
1932 if (index >= O.length) return { value: undefined, done: true };
1933 point = $at(O, index);
1934 this._i += point.length;
1935 return { value: point, done: false };
1936 });
1937
1938 var ITERATOR$4 = _wks('iterator');
1939 var TO_STRING_TAG = _wks('toStringTag');
1940 var ArrayValues = _iterators.Array;
1941
1942 var DOMIterables = {
1943 CSSRuleList: true, // TODO: Not spec compliant, should be false.
1944 CSSStyleDeclaration: false,
1945 CSSValueList: false,
1946 ClientRectList: false,
1947 DOMRectList: false,
1948 DOMStringList: false,
1949 DOMTokenList: true,
1950 DataTransferItemList: false,
1951 FileList: false,
1952 HTMLAllCollection: false,
1953 HTMLCollection: false,
1954 HTMLFormElement: false,
1955 HTMLSelectElement: false,
1956 MediaList: true, // TODO: Not spec compliant, should be false.
1957 MimeTypeArray: false,
1958 NamedNodeMap: false,
1959 NodeList: true,
1960 PaintRequestList: false,
1961 Plugin: false,
1962 PluginArray: false,
1963 SVGLengthList: false,
1964 SVGNumberList: false,
1965 SVGPathSegList: false,
1966 SVGPointList: false,
1967 SVGStringList: false,
1968 SVGTransformList: false,
1969 SourceBufferList: false,
1970 StyleSheetList: true, // TODO: Not spec compliant, should be false.
1971 TextTrackCueList: false,
1972 TextTrackList: false,
1973 TouchList: false
1974 };
1975
1976 for (var collections = _objectKeys(DOMIterables), i = 0; i < collections.length; i++) {
1977 var NAME = collections[i];
1978 var explicit = DOMIterables[NAME];
1979 var Collection = _global[NAME];
1980 var proto = Collection && Collection.prototype;
1981 var key;
1982 if (proto) {
1983 if (!proto[ITERATOR$4]) _hide(proto, ITERATOR$4, ArrayValues);
1984 if (!proto[TO_STRING_TAG]) _hide(proto, TO_STRING_TAG, NAME);
1985 _iterators[NAME] = ArrayValues;
1986 if (explicit) for (key in es6_array_iterator) if (!proto[key]) _redefine(proto, key, es6_array_iterator[key], true);
1987 }
1988 }
1989
1990 var runtime = createCommonjsModule(function (module) {
1991 /**
1992 * Copyright (c) 2014-present, Facebook, Inc.
1993 *
1994 * This source code is licensed under the MIT license found in the
1995 * LICENSE file in the root directory of this source tree.
1996 */
1997
1998 !(function(global) {
1999
2000 var Op = Object.prototype;
2001 var hasOwn = Op.hasOwnProperty;
2002 var undefined; // More compressible than void 0.
2003 var $Symbol = typeof Symbol === "function" ? Symbol : {};
2004 var iteratorSymbol = $Symbol.iterator || "@@iterator";
2005 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
2006 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
2007 var runtime = global.regeneratorRuntime;
2008 if (runtime) {
2009 {
2010 // If regeneratorRuntime is defined globally and we're in a module,
2011 // make the exports object identical to regeneratorRuntime.
2012 module.exports = runtime;
2013 }
2014 // Don't bother evaluating the rest of this file if the runtime was
2015 // already defined globally.
2016 return;
2017 }
2018
2019 // Define the runtime globally (as expected by generated code) as either
2020 // module.exports (if we're in a module) or a new, empty object.
2021 runtime = global.regeneratorRuntime = module.exports;
2022
2023 function wrap(innerFn, outerFn, self, tryLocsList) {
2024 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
2025 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
2026 var generator = Object.create(protoGenerator.prototype);
2027 var context = new Context(tryLocsList || []);
2028
2029 // The ._invoke method unifies the implementations of the .next,
2030 // .throw, and .return methods.
2031 generator._invoke = makeInvokeMethod(innerFn, self, context);
2032
2033 return generator;
2034 }
2035 runtime.wrap = wrap;
2036
2037 // Try/catch helper to minimize deoptimizations. Returns a completion
2038 // record like context.tryEntries[i].completion. This interface could
2039 // have been (and was previously) designed to take a closure to be
2040 // invoked without arguments, but in all the cases we care about we
2041 // already have an existing method we want to call, so there's no need
2042 // to create a new function object. We can even get away with assuming
2043 // the method takes exactly one argument, since that happens to be true
2044 // in every case, so we don't have to touch the arguments object. The
2045 // only additional allocation required is the completion record, which
2046 // has a stable shape and so hopefully should be cheap to allocate.
2047 function tryCatch(fn, obj, arg) {
2048 try {
2049 return { type: "normal", arg: fn.call(obj, arg) };
2050 } catch (err) {
2051 return { type: "throw", arg: err };
2052 }
2053 }
2054
2055 var GenStateSuspendedStart = "suspendedStart";
2056 var GenStateSuspendedYield = "suspendedYield";
2057 var GenStateExecuting = "executing";
2058 var GenStateCompleted = "completed";
2059
2060 // Returning this object from the innerFn has the same effect as
2061 // breaking out of the dispatch switch statement.
2062 var ContinueSentinel = {};
2063
2064 // Dummy constructor functions that we use as the .constructor and
2065 // .constructor.prototype properties for functions that return Generator
2066 // objects. For full spec compliance, you may wish to configure your
2067 // minifier not to mangle the names of these two functions.
2068 function Generator() {}
2069 function GeneratorFunction() {}
2070 function GeneratorFunctionPrototype() {}
2071
2072 // This is a polyfill for %IteratorPrototype% for environments that
2073 // don't natively support it.
2074 var IteratorPrototype = {};
2075 IteratorPrototype[iteratorSymbol] = function () {
2076 return this;
2077 };
2078
2079 var getProto = Object.getPrototypeOf;
2080 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
2081 if (NativeIteratorPrototype &&
2082 NativeIteratorPrototype !== Op &&
2083 hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
2084 // This environment has a native %IteratorPrototype%; use it instead
2085 // of the polyfill.
2086 IteratorPrototype = NativeIteratorPrototype;
2087 }
2088
2089 var Gp = GeneratorFunctionPrototype.prototype =
2090 Generator.prototype = Object.create(IteratorPrototype);
2091 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
2092 GeneratorFunctionPrototype.constructor = GeneratorFunction;
2093 GeneratorFunctionPrototype[toStringTagSymbol] =
2094 GeneratorFunction.displayName = "GeneratorFunction";
2095
2096 // Helper for defining the .next, .throw, and .return methods of the
2097 // Iterator interface in terms of a single ._invoke method.
2098 function defineIteratorMethods(prototype) {
2099 ["next", "throw", "return"].forEach(function(method) {
2100 prototype[method] = function(arg) {
2101 return this._invoke(method, arg);
2102 };
2103 });
2104 }
2105
2106 runtime.isGeneratorFunction = function(genFun) {
2107 var ctor = typeof genFun === "function" && genFun.constructor;
2108 return ctor
2109 ? ctor === GeneratorFunction ||
2110 // For the native GeneratorFunction constructor, the best we can
2111 // do is to check its .name property.
2112 (ctor.displayName || ctor.name) === "GeneratorFunction"
2113 : false;
2114 };
2115
2116 runtime.mark = function(genFun) {
2117 if (Object.setPrototypeOf) {
2118 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
2119 } else {
2120 genFun.__proto__ = GeneratorFunctionPrototype;
2121 if (!(toStringTagSymbol in genFun)) {
2122 genFun[toStringTagSymbol] = "GeneratorFunction";
2123 }
2124 }
2125 genFun.prototype = Object.create(Gp);
2126 return genFun;
2127 };
2128
2129 // Within the body of any async function, `await x` is transformed to
2130 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
2131 // `hasOwn.call(value, "__await")` to determine if the yielded value is
2132 // meant to be awaited.
2133 runtime.awrap = function(arg) {
2134 return { __await: arg };
2135 };
2136
2137 function AsyncIterator(generator) {
2138 function invoke(method, arg, resolve, reject) {
2139 var record = tryCatch(generator[method], generator, arg);
2140 if (record.type === "throw") {
2141 reject(record.arg);
2142 } else {
2143 var result = record.arg;
2144 var value = result.value;
2145 if (value &&
2146 typeof value === "object" &&
2147 hasOwn.call(value, "__await")) {
2148 return Promise.resolve(value.__await).then(function(value) {
2149 invoke("next", value, resolve, reject);
2150 }, function(err) {
2151 invoke("throw", err, resolve, reject);
2152 });
2153 }
2154
2155 return Promise.resolve(value).then(function(unwrapped) {
2156 // When a yielded Promise is resolved, its final value becomes
2157 // the .value of the Promise<{value,done}> result for the
2158 // current iteration. If the Promise is rejected, however, the
2159 // result for this iteration will be rejected with the same
2160 // reason. Note that rejections of yielded Promises are not
2161 // thrown back into the generator function, as is the case
2162 // when an awaited Promise is rejected. This difference in
2163 // behavior between yield and await is important, because it
2164 // allows the consumer to decide what to do with the yielded
2165 // rejection (swallow it and continue, manually .throw it back
2166 // into the generator, abandon iteration, whatever). With
2167 // await, by contrast, there is no opportunity to examine the
2168 // rejection reason outside the generator function, so the
2169 // only option is to throw it from the await expression, and
2170 // let the generator function handle the exception.
2171 result.value = unwrapped;
2172 resolve(result);
2173 }, reject);
2174 }
2175 }
2176
2177 var previousPromise;
2178
2179 function enqueue(method, arg) {
2180 function callInvokeWithMethodAndArg() {
2181 return new Promise(function(resolve, reject) {
2182 invoke(method, arg, resolve, reject);
2183 });
2184 }
2185
2186 return previousPromise =
2187 // If enqueue has been called before, then we want to wait until
2188 // all previous Promises have been resolved before calling invoke,
2189 // so that results are always delivered in the correct order. If
2190 // enqueue has not been called before, then it is important to
2191 // call invoke immediately, without waiting on a callback to fire,
2192 // so that the async generator function has the opportunity to do
2193 // any necessary setup in a predictable way. This predictability
2194 // is why the Promise constructor synchronously invokes its
2195 // executor callback, and why async functions synchronously
2196 // execute code before the first await. Since we implement simple
2197 // async functions in terms of async generators, it is especially
2198 // important to get this right, even though it requires care.
2199 previousPromise ? previousPromise.then(
2200 callInvokeWithMethodAndArg,
2201 // Avoid propagating failures to Promises returned by later
2202 // invocations of the iterator.
2203 callInvokeWithMethodAndArg
2204 ) : callInvokeWithMethodAndArg();
2205 }
2206
2207 // Define the unified helper method that is used to implement .next,
2208 // .throw, and .return (see defineIteratorMethods).
2209 this._invoke = enqueue;
2210 }
2211
2212 defineIteratorMethods(AsyncIterator.prototype);
2213 AsyncIterator.prototype[asyncIteratorSymbol] = function () {
2214 return this;
2215 };
2216 runtime.AsyncIterator = AsyncIterator;
2217
2218 // Note that simple async functions are implemented on top of
2219 // AsyncIterator objects; they just return a Promise for the value of
2220 // the final result produced by the iterator.
2221 runtime.async = function(innerFn, outerFn, self, tryLocsList) {
2222 var iter = new AsyncIterator(
2223 wrap(innerFn, outerFn, self, tryLocsList)
2224 );
2225
2226 return runtime.isGeneratorFunction(outerFn)
2227 ? iter // If outerFn is a generator, return the full iterator.
2228 : iter.next().then(function(result) {
2229 return result.done ? result.value : iter.next();
2230 });
2231 };
2232
2233 function makeInvokeMethod(innerFn, self, context) {
2234 var state = GenStateSuspendedStart;
2235
2236 return function invoke(method, arg) {
2237 if (state === GenStateExecuting) {
2238 throw new Error("Generator is already running");
2239 }
2240
2241 if (state === GenStateCompleted) {
2242 if (method === "throw") {
2243 throw arg;
2244 }
2245
2246 // Be forgiving, per 25.3.3.3.3 of the spec:
2247 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
2248 return doneResult();
2249 }
2250
2251 context.method = method;
2252 context.arg = arg;
2253
2254 while (true) {
2255 var delegate = context.delegate;
2256 if (delegate) {
2257 var delegateResult = maybeInvokeDelegate(delegate, context);
2258 if (delegateResult) {
2259 if (delegateResult === ContinueSentinel) continue;
2260 return delegateResult;
2261 }
2262 }
2263
2264 if (context.method === "next") {
2265 // Setting context._sent for legacy support of Babel's
2266 // function.sent implementation.
2267 context.sent = context._sent = context.arg;
2268
2269 } else if (context.method === "throw") {
2270 if (state === GenStateSuspendedStart) {
2271 state = GenStateCompleted;
2272 throw context.arg;
2273 }
2274
2275 context.dispatchException(context.arg);
2276
2277 } else if (context.method === "return") {
2278 context.abrupt("return", context.arg);
2279 }
2280
2281 state = GenStateExecuting;
2282
2283 var record = tryCatch(innerFn, self, context);
2284 if (record.type === "normal") {
2285 // If an exception is thrown from innerFn, we leave state ===
2286 // GenStateExecuting and loop back for another invocation.
2287 state = context.done
2288 ? GenStateCompleted
2289 : GenStateSuspendedYield;
2290
2291 if (record.arg === ContinueSentinel) {
2292 continue;
2293 }
2294
2295 return {
2296 value: record.arg,
2297 done: context.done
2298 };
2299
2300 } else if (record.type === "throw") {
2301 state = GenStateCompleted;
2302 // Dispatch the exception by looping back around to the
2303 // context.dispatchException(context.arg) call above.
2304 context.method = "throw";
2305 context.arg = record.arg;
2306 }
2307 }
2308 };
2309 }
2310
2311 // Call delegate.iterator[context.method](context.arg) and handle the
2312 // result, either by returning a { value, done } result from the
2313 // delegate iterator, or by modifying context.method and context.arg,
2314 // setting context.delegate to null, and returning the ContinueSentinel.
2315 function maybeInvokeDelegate(delegate, context) {
2316 var method = delegate.iterator[context.method];
2317 if (method === undefined) {
2318 // A .throw or .return when the delegate iterator has no .throw
2319 // method always terminates the yield* loop.
2320 context.delegate = null;
2321
2322 if (context.method === "throw") {
2323 if (delegate.iterator.return) {
2324 // If the delegate iterator has a return method, give it a
2325 // chance to clean up.
2326 context.method = "return";
2327 context.arg = undefined;
2328 maybeInvokeDelegate(delegate, context);
2329
2330 if (context.method === "throw") {
2331 // If maybeInvokeDelegate(context) changed context.method from
2332 // "return" to "throw", let that override the TypeError below.
2333 return ContinueSentinel;
2334 }
2335 }
2336
2337 context.method = "throw";
2338 context.arg = new TypeError(
2339 "The iterator does not provide a 'throw' method");
2340 }
2341
2342 return ContinueSentinel;
2343 }
2344
2345 var record = tryCatch(method, delegate.iterator, context.arg);
2346
2347 if (record.type === "throw") {
2348 context.method = "throw";
2349 context.arg = record.arg;
2350 context.delegate = null;
2351 return ContinueSentinel;
2352 }
2353
2354 var info = record.arg;
2355
2356 if (! info) {
2357 context.method = "throw";
2358 context.arg = new TypeError("iterator result is not an object");
2359 context.delegate = null;
2360 return ContinueSentinel;
2361 }
2362
2363 if (info.done) {
2364 // Assign the result of the finished delegate to the temporary
2365 // variable specified by delegate.resultName (see delegateYield).
2366 context[delegate.resultName] = info.value;
2367
2368 // Resume execution at the desired location (see delegateYield).
2369 context.next = delegate.nextLoc;
2370
2371 // If context.method was "throw" but the delegate handled the
2372 // exception, let the outer generator proceed normally. If
2373 // context.method was "next", forget context.arg since it has been
2374 // "consumed" by the delegate iterator. If context.method was
2375 // "return", allow the original .return call to continue in the
2376 // outer generator.
2377 if (context.method !== "return") {
2378 context.method = "next";
2379 context.arg = undefined;
2380 }
2381
2382 } else {
2383 // Re-yield the result returned by the delegate method.
2384 return info;
2385 }
2386
2387 // The delegate iterator is finished, so forget it and continue with
2388 // the outer generator.
2389 context.delegate = null;
2390 return ContinueSentinel;
2391 }
2392
2393 // Define Generator.prototype.{next,throw,return} in terms of the
2394 // unified ._invoke helper method.
2395 defineIteratorMethods(Gp);
2396
2397 Gp[toStringTagSymbol] = "Generator";
2398
2399 // A Generator should always return itself as the iterator object when the
2400 // @@iterator function is called on it. Some browsers' implementations of the
2401 // iterator prototype chain incorrectly implement this, causing the Generator
2402 // object to not be returned from this call. This ensures that doesn't happen.
2403 // See https://github.com/facebook/regenerator/issues/274 for more details.
2404 Gp[iteratorSymbol] = function() {
2405 return this;
2406 };
2407
2408 Gp.toString = function() {
2409 return "[object Generator]";
2410 };
2411
2412 function pushTryEntry(locs) {
2413 var entry = { tryLoc: locs[0] };
2414
2415 if (1 in locs) {
2416 entry.catchLoc = locs[1];
2417 }
2418
2419 if (2 in locs) {
2420 entry.finallyLoc = locs[2];
2421 entry.afterLoc = locs[3];
2422 }
2423
2424 this.tryEntries.push(entry);
2425 }
2426
2427 function resetTryEntry(entry) {
2428 var record = entry.completion || {};
2429 record.type = "normal";
2430 delete record.arg;
2431 entry.completion = record;
2432 }
2433
2434 function Context(tryLocsList) {
2435 // The root entry object (effectively a try statement without a catch
2436 // or a finally block) gives us a place to store values thrown from
2437 // locations where there is no enclosing try statement.
2438 this.tryEntries = [{ tryLoc: "root" }];
2439 tryLocsList.forEach(pushTryEntry, this);
2440 this.reset(true);
2441 }
2442
2443 runtime.keys = function(object) {
2444 var keys = [];
2445 for (var key in object) {
2446 keys.push(key);
2447 }
2448 keys.reverse();
2449
2450 // Rather than returning an object with a next method, we keep
2451 // things simple and return the next function itself.
2452 return function next() {
2453 while (keys.length) {
2454 var key = keys.pop();
2455 if (key in object) {
2456 next.value = key;
2457 next.done = false;
2458 return next;
2459 }
2460 }
2461
2462 // To avoid creating an additional object, we just hang the .value
2463 // and .done properties off the next function object itself. This
2464 // also ensures that the minifier will not anonymize the function.
2465 next.done = true;
2466 return next;
2467 };
2468 };
2469
2470 function values(iterable) {
2471 if (iterable) {
2472 var iteratorMethod = iterable[iteratorSymbol];
2473 if (iteratorMethod) {
2474 return iteratorMethod.call(iterable);
2475 }
2476
2477 if (typeof iterable.next === "function") {
2478 return iterable;
2479 }
2480
2481 if (!isNaN(iterable.length)) {
2482 var i = -1, next = function next() {
2483 while (++i < iterable.length) {
2484 if (hasOwn.call(iterable, i)) {
2485 next.value = iterable[i];
2486 next.done = false;
2487 return next;
2488 }
2489 }
2490
2491 next.value = undefined;
2492 next.done = true;
2493
2494 return next;
2495 };
2496
2497 return next.next = next;
2498 }
2499 }
2500
2501 // Return an iterator with no values.
2502 return { next: doneResult };
2503 }
2504 runtime.values = values;
2505
2506 function doneResult() {
2507 return { value: undefined, done: true };
2508 }
2509
2510 Context.prototype = {
2511 constructor: Context,
2512
2513 reset: function(skipTempReset) {
2514 this.prev = 0;
2515 this.next = 0;
2516 // Resetting context._sent for legacy support of Babel's
2517 // function.sent implementation.
2518 this.sent = this._sent = undefined;
2519 this.done = false;
2520 this.delegate = null;
2521
2522 this.method = "next";
2523 this.arg = undefined;
2524
2525 this.tryEntries.forEach(resetTryEntry);
2526
2527 if (!skipTempReset) {
2528 for (var name in this) {
2529 // Not sure about the optimal order of these conditions:
2530 if (name.charAt(0) === "t" &&
2531 hasOwn.call(this, name) &&
2532 !isNaN(+name.slice(1))) {
2533 this[name] = undefined;
2534 }
2535 }
2536 }
2537 },
2538
2539 stop: function() {
2540 this.done = true;
2541
2542 var rootEntry = this.tryEntries[0];
2543 var rootRecord = rootEntry.completion;
2544 if (rootRecord.type === "throw") {
2545 throw rootRecord.arg;
2546 }
2547
2548 return this.rval;
2549 },
2550
2551 dispatchException: function(exception) {
2552 if (this.done) {
2553 throw exception;
2554 }
2555
2556 var context = this;
2557 function handle(loc, caught) {
2558 record.type = "throw";
2559 record.arg = exception;
2560 context.next = loc;
2561
2562 if (caught) {
2563 // If the dispatched exception was caught by a catch block,
2564 // then let that catch block handle the exception normally.
2565 context.method = "next";
2566 context.arg = undefined;
2567 }
2568
2569 return !! caught;
2570 }
2571
2572 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
2573 var entry = this.tryEntries[i];
2574 var record = entry.completion;
2575
2576 if (entry.tryLoc === "root") {
2577 // Exception thrown outside of any try block that could handle
2578 // it, so set the completion value of the entire function to
2579 // throw the exception.
2580 return handle("end");
2581 }
2582
2583 if (entry.tryLoc <= this.prev) {
2584 var hasCatch = hasOwn.call(entry, "catchLoc");
2585 var hasFinally = hasOwn.call(entry, "finallyLoc");
2586
2587 if (hasCatch && hasFinally) {
2588 if (this.prev < entry.catchLoc) {
2589 return handle(entry.catchLoc, true);
2590 } else if (this.prev < entry.finallyLoc) {
2591 return handle(entry.finallyLoc);
2592 }
2593
2594 } else if (hasCatch) {
2595 if (this.prev < entry.catchLoc) {
2596 return handle(entry.catchLoc, true);
2597 }
2598
2599 } else if (hasFinally) {
2600 if (this.prev < entry.finallyLoc) {
2601 return handle(entry.finallyLoc);
2602 }
2603
2604 } else {
2605 throw new Error("try statement without catch or finally");
2606 }
2607 }
2608 }
2609 },
2610
2611 abrupt: function(type, arg) {
2612 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
2613 var entry = this.tryEntries[i];
2614 if (entry.tryLoc <= this.prev &&
2615 hasOwn.call(entry, "finallyLoc") &&
2616 this.prev < entry.finallyLoc) {
2617 var finallyEntry = entry;
2618 break;
2619 }
2620 }
2621
2622 if (finallyEntry &&
2623 (type === "break" ||
2624 type === "continue") &&
2625 finallyEntry.tryLoc <= arg &&
2626 arg <= finallyEntry.finallyLoc) {
2627 // Ignore the finally entry if control is not jumping to a
2628 // location outside the try/catch block.
2629 finallyEntry = null;
2630 }
2631
2632 var record = finallyEntry ? finallyEntry.completion : {};
2633 record.type = type;
2634 record.arg = arg;
2635
2636 if (finallyEntry) {
2637 this.method = "next";
2638 this.next = finallyEntry.finallyLoc;
2639 return ContinueSentinel;
2640 }
2641
2642 return this.complete(record);
2643 },
2644
2645 complete: function(record, afterLoc) {
2646 if (record.type === "throw") {
2647 throw record.arg;
2648 }
2649
2650 if (record.type === "break" ||
2651 record.type === "continue") {
2652 this.next = record.arg;
2653 } else if (record.type === "return") {
2654 this.rval = this.arg = record.arg;
2655 this.method = "return";
2656 this.next = "end";
2657 } else if (record.type === "normal" && afterLoc) {
2658 this.next = afterLoc;
2659 }
2660
2661 return ContinueSentinel;
2662 },
2663
2664 finish: function(finallyLoc) {
2665 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
2666 var entry = this.tryEntries[i];
2667 if (entry.finallyLoc === finallyLoc) {
2668 this.complete(entry.completion, entry.afterLoc);
2669 resetTryEntry(entry);
2670 return ContinueSentinel;
2671 }
2672 }
2673 },
2674
2675 "catch": function(tryLoc) {
2676 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
2677 var entry = this.tryEntries[i];
2678 if (entry.tryLoc === tryLoc) {
2679 var record = entry.completion;
2680 if (record.type === "throw") {
2681 var thrown = record.arg;
2682 resetTryEntry(entry);
2683 }
2684 return thrown;
2685 }
2686 }
2687
2688 // The context.catch method must only be called with a location
2689 // argument that corresponds to a known catch block.
2690 throw new Error("illegal catch attempt");
2691 },
2692
2693 delegateYield: function(iterable, resultName, nextLoc) {
2694 this.delegate = {
2695 iterator: values(iterable),
2696 resultName: resultName,
2697 nextLoc: nextLoc
2698 };
2699
2700 if (this.method === "next") {
2701 // Deliberately forget the last sent value so that we don't
2702 // accidentally pass it on to the delegate.
2703 this.arg = undefined;
2704 }
2705
2706 return ContinueSentinel;
2707 }
2708 };
2709 })(
2710 // In sloppy mode, unbound `this` refers to the global object, fallback to
2711 // Function constructor if we're in global strict mode. That is sadly a form
2712 // of indirect eval which violates Content Security Policy.
2713 (function() { return this })() || Function("return this")()
2714 );
2715 });
2716
2717 /**
2718 * @class Batch
2719 * @namespace Daux.Core
2720 */
2721 var Batch =
2722 /*#__PURE__*/
2723 function () {
2724 /**
2725 * @param {Service.Store} store
2726 */
2727 function Batch(store) {
2728 _classCallCheck(this, Batch);
2729
2730 this.store = store;
2731 this.queues = [];
2732 }
2733 /**
2734 * @param {string} type
2735 * @param {Array.<Object>} records
2736 * @function
2737 */
2738
2739
2740 _createClass(Batch, [{
2741 key: "set",
2742 value: function set(type, records) {
2743 this.queues.push({
2744 operation: 'set',
2745 data: {
2746 type: type,
2747 records: records
2748 }
2749 });
2750 }
2751 /**
2752 * @param {string} type
2753 * @param {string} id
2754 * @param {Object} attribute
2755 * @function
2756 */
2757
2758 }, {
2759 key: "update",
2760 value: function update(type, id, attribute) {
2761 this.queues.push({
2762 operation: 'update',
2763 data: {
2764 type: type,
2765 id: id,
2766 attribute: attribute
2767 }
2768 });
2769 }
2770 /**
2771 * @param {string} type
2772 * @param {string} id
2773 * @function
2774 */
2775
2776 }, {
2777 key: "delete",
2778 value: function _delete(type, id) {
2779 this.queues.push({
2780 operation: 'delete',
2781 data: {
2782 type: type,
2783 id: id
2784 }
2785 });
2786 }
2787 /**
2788 * @param {Object} [option]
2789 * @function
2790 */
2791
2792 }, {
2793 key: "commit",
2794 value: function commit(option) {
2795 var _this = this;
2796
2797 this.queues.forEach(function (_ref, index) {
2798 var operation = _ref.operation,
2799 data = _ref.data;
2800 var finalOption = option;
2801
2802 if (!finalOption) {
2803 var isBackgroundOperation = index !== _this.queues.length - 1;
2804 finalOption = {
2805 isBackgroundOperation: isBackgroundOperation
2806 };
2807 }
2808
2809 if (operation === 'set') {
2810 _this.store.set(data.type, data.records, finalOption);
2811 } else if (operation === 'update') {
2812 _this.store.update(data.type, data.id, data.attribute, finalOption);
2813 } else if (operation === 'delete') {
2814 _this.store.delete(data.type, data.id, finalOption);
2815 }
2816 });
2817 this.queues = [];
2818 }
2819 }]);
2820
2821 return Batch;
2822 }();
2823
2824 /**
2825 * @param {Object} model
2826 * @param {string} type
2827 * @param {string} attribute
2828 * @return {string} Cardinality
2829 * @function
2830 */
2831 function getCardinality(model, type, attribute) {
2832 var meta = model[type].relationship[attribute];
2833
2834 if (meta.kind === 'belongsTo') {
2835 if (meta.inverse) {
2836 var inverseMeta = model[meta.type].relationship[meta.inverse];
2837
2838 if (inverseMeta.kind === 'belongsTo') {
2839 return 'oneToOne';
2840 }
2841
2842 return 'oneToMany';
2843 }
2844
2845 return 'oneToNone';
2846 }
2847
2848 if (meta.inverse) {
2849 var _inverseMeta = model[meta.type].relationship[meta.inverse];
2850
2851 if (_inverseMeta.kind === 'belongsTo') {
2852 return 'oneToMany';
2853 }
2854
2855 return 'manyToMany';
2856 }
2857
2858 return 'manyToNone';
2859 }
2860
2861 /**
2862 * @param {Daux.Core.Model} model
2863 * @return {Object} Default record
2864 */
2865 function getDefaultRecord(model) {
2866 var defaultRecord = {};
2867 model.attributes.forEach(function (attribute) {
2868 defaultRecord[attribute] = null;
2869 });
2870 Object.keys(model.relationship).forEach(function (relationshipKey) {
2871 if (model.relationship[relationshipKey].kind === 'belongsTo') {
2872 defaultRecord[relationshipKey] = null;
2873 } else {
2874 defaultRecord[relationshipKey] = [];
2875 }
2876 });
2877 return defaultRecord;
2878 }
2879
2880 /**
2881 * @param {Object} record
2882 * @return {string|null} Record ID
2883 * @function
2884 */
2885 function normalizeBelongsTo(record) {
2886 if (typeof record === 'string' || record === null) {
2887 return record;
2888 }
2889
2890 if (_typeof(record) === 'object') {
2891 return record.id;
2892 }
2893
2894 return null;
2895 }
2896 /**
2897 * @param {Array.<Object>} records
2898 * @return {Array.<string>} Record IDs
2899 * @function
2900 */
2901
2902
2903 function normalizeHasMany(records) {
2904 if (Array.isArray(records)) {
2905 return records.map(function (record) {
2906 if (typeof record === 'string') {
2907 return record;
2908 }
2909
2910 return record.id;
2911 });
2912 }
2913
2914 return [];
2915 }
2916 /**
2917 * @param {Daux.Core.Model} model
2918 * @param {Object} record
2919 * @return {Object} Normalized record
2920 */
2921
2922
2923 function normalize(model, record) {
2924 var normalizedRecord = {
2925 id: record.id
2926 };
2927 model.attributes.forEach(function (attribute) {
2928 normalizedRecord[attribute] = Object.prototype.hasOwnProperty.call(record, attribute) ? record[attribute] : null;
2929 });
2930 Object.keys(model.relationship).forEach(function (relationshipKey) {
2931 if (model.relationship[relationshipKey].kind === 'belongsTo') {
2932 normalizedRecord[relationshipKey] = normalizeBelongsTo(record[relationshipKey]);
2933 } else {
2934 normalizedRecord[relationshipKey] = normalizeHasMany(record[relationshipKey]);
2935 }
2936 });
2937 return normalizedRecord;
2938 }
2939
2940 /**
2941 * @class Store
2942 * @namespace Daux.Core
2943 */
2944
2945 var Store =
2946 /*#__PURE__*/
2947 function () {
2948 /**
2949 * @callback fetch
2950 * @return {Promise} Resolves with the records
2951 */
2952
2953 /**
2954 * @param {Object} model
2955 * @function
2956 */
2957 function Store(model) {
2958 _classCallCheck(this, Store);
2959
2960 this.model = model;
2961 this.state = this.buildInitialState();
2962 this.subscription = {};
2963 }
2964 /**
2965 * @param {string} type
2966 * @param {Object} record
2967 * @param {Object} [option={}]
2968 * @function
2969 */
2970
2971
2972 _createClass(Store, [{
2973 key: "set",
2974 value: function set(type, record) {
2975 var option = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2976
2977 if (record.id) {
2978 var modelForType = this.model[type];
2979 var deserializedRecord = option.isDeserialized ? record : modelForType.deserialize(record);
2980
2981 if (deserializedRecord) {
2982 var normalizedRecord = normalize(modelForType, deserializedRecord);
2983 this.state[type].data[normalizedRecord.id] = normalizedRecord;
2984 this.syncAddedRelationships(type, deserializedRecord);
2985
2986 if (!option.isBackgroundOperation) {
2987 this.triggerSubscriptions();
2988 }
2989 }
2990 } else {
2991 throw new Error('Record to set has no ID');
2992 }
2993 }
2994 /**
2995 * @param {string} type
2996 * @param {string} id
2997 * @param {Object} attribute
2998 * @param {Object} [option={}]
2999 * @function
3000 */
3001
3002 }, {
3003 key: "update",
3004 value: function update(type, id, attribute) {
3005 var option = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
3006 var cachedRecord = this.getStateForRecord(type, id);
3007
3008 if (cachedRecord) {
3009 var modelForType = this.model[type];
3010 var updatedRecord = modelForType.deserialize(Object.assign({}, cachedRecord, attribute, {
3011 id: id
3012 }));
3013 this.set(type, updatedRecord, {
3014 isBackgroundOperation: true,
3015 isDeserialized: true
3016 });
3017 this.syncRemovedRelationships(type, updatedRecord, cachedRecord);
3018
3019 if (!option.isBackgroundOperation) {
3020 this.triggerSubscriptions();
3021 }
3022 } else {
3023 throw new Error('Record doesn\'t exist');
3024 }
3025 }
3026 /**
3027 * @param {string} type
3028 * @param {string} id
3029 * @param {Object} [option={}]
3030 * @function
3031 */
3032
3033 }, {
3034 key: "delete",
3035 value: function _delete(type, id) {
3036 var option = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
3037 var cachedRecord = this.getStateForRecord(type, id);
3038
3039 if (cachedRecord) {
3040 var modelForType = this.model[type];
3041 var defaultRecord = getDefaultRecord(modelForType, type);
3042 this.update(type, id, defaultRecord, {
3043 isBackgroundOperation: true
3044 });
3045 delete this.state[type].data[id];
3046
3047 if (!option.isBackgroundOperation) {
3048 this.triggerSubscriptions();
3049 }
3050 } else {
3051 throw new Error('Record doesn\'t exist');
3052 }
3053 }
3054 /**
3055 * @param {string} type
3056 * @param {string} id
3057 * @param {option} [option={}]
3058 * @return {Object} Record
3059 * @function
3060 */
3061
3062 }, {
3063 key: "get",
3064 value: function () {
3065 var _get$$1 = _asyncToGenerator(
3066 /*#__PURE__*/
3067 regeneratorRuntime.mark(function _callee(type, id) {
3068 var option,
3069 record,
3070 recordState,
3071 _args = arguments;
3072 return regeneratorRuntime.wrap(function _callee$(_context) {
3073 while (1) {
3074 switch (_context.prev = _context.next) {
3075 case 0:
3076 option = _args.length > 2 && _args[2] !== undefined ? _args[2] : {};
3077
3078 if (!(!this.isRecordAttributePopulated(type, id) && option.fetch)) {
3079 _context.next = 8;
3080 break;
3081 }
3082
3083 _context.next = 4;
3084 return option.fetch();
3085
3086 case 4:
3087 record = _context.sent;
3088
3089 if (record) {
3090 _context.next = 7;
3091 break;
3092 }
3093
3094 return _context.abrupt("return", null);
3095
3096 case 7:
3097 this.set(type, record, {
3098 isBackgroundOperation: true
3099 });
3100
3101 case 8:
3102 recordState = this.getStateForRecord(type, id);
3103
3104 if (!(recordState && option.include)) {
3105 _context.next = 12;
3106 break;
3107 }
3108
3109 _context.next = 12;
3110 return this.includeRelationships(type, recordState, option);
3111
3112 case 12:
3113 return _context.abrupt("return", this.getCachedRecord(type, id));
3114
3115 case 13:
3116 case "end":
3117 return _context.stop();
3118 }
3119 }
3120 }, _callee, this);
3121 }));
3122
3123 return function get(_x, _x2) {
3124 return _get$$1.apply(this, arguments);
3125 };
3126 }()
3127 /**
3128 * @param {string} type
3129 * @param {option} [option={}]
3130 * @return {Array.<Object>} Records
3131 * @function
3132 */
3133
3134 }, {
3135 key: "getAll",
3136 value: function () {
3137 var _getAll = _asyncToGenerator(
3138 /*#__PURE__*/
3139 regeneratorRuntime.mark(function _callee2(type) {
3140 var _this = this;
3141
3142 var option,
3143 records,
3144 _args2 = arguments;
3145 return regeneratorRuntime.wrap(function _callee2$(_context2) {
3146 while (1) {
3147 switch (_context2.prev = _context2.next) {
3148 case 0:
3149 option = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {};
3150
3151 if (!(option.fetch && !this.state[type].isDataComplete)) {
3152 _context2.next = 10;
3153 break;
3154 }
3155
3156 _context2.next = 4;
3157 return option.fetch();
3158
3159 case 4:
3160 _context2.t0 = _context2.sent;
3161
3162 if (_context2.t0) {
3163 _context2.next = 7;
3164 break;
3165 }
3166
3167 _context2.t0 = [];
3168
3169 case 7:
3170 records = _context2.t0;
3171 records.forEach(function (record) {
3172 return _this.set(type, record, {
3173 isBackgroundOperation: true
3174 });
3175 });
3176 this.state[type].isDataComplete = true;
3177
3178 case 10:
3179 return _context2.abrupt("return", Promise.all(Object.keys(this.state[type].data).map(function (id) {
3180 return _this.get(type, id, {
3181 include: option.include
3182 });
3183 })));
3184
3185 case 11:
3186 case "end":
3187 return _context2.stop();
3188 }
3189 }
3190 }, _callee2, this);
3191 }));
3192
3193 return function getAll(_x3) {
3194 return _getAll.apply(this, arguments);
3195 };
3196 }()
3197 /**
3198 * @param {string} type
3199 * @param {option} [option={}]
3200 * @return {Array.<Object>} Records
3201 * @function
3202 */
3203
3204 }, {
3205 key: "query",
3206 value: function () {
3207 var _query = _asyncToGenerator(
3208 /*#__PURE__*/
3209 regeneratorRuntime.mark(function _callee3(type) {
3210 var _this2 = this;
3211
3212 var option,
3213 records,
3214 _args3 = arguments;
3215 return regeneratorRuntime.wrap(function _callee3$(_context3) {
3216 while (1) {
3217 switch (_context3.prev = _context3.next) {
3218 case 0:
3219 option = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : {};
3220 _context3.next = 3;
3221 return option.fetch();
3222
3223 case 3:
3224 _context3.t0 = _context3.sent;
3225
3226 if (_context3.t0) {
3227 _context3.next = 6;
3228 break;
3229 }
3230
3231 _context3.t0 = [];
3232
3233 case 6:
3234 records = _context3.t0;
3235 records.forEach(function (record) {
3236 return _this2.set(type, record, {
3237 isBackgroundOperation: true
3238 });
3239 });
3240 return _context3.abrupt("return", Promise.all(records.map(function (record) {
3241 return _this2.get(type, record.id, {
3242 include: option.include
3243 });
3244 })));
3245
3246 case 9:
3247 case "end":
3248 return _context3.stop();
3249 }
3250 }
3251 }, _callee3, this);
3252 }));
3253
3254 return function query(_x4) {
3255 return _query.apply(this, arguments);
3256 };
3257 }()
3258 /**
3259 * @callback subscriptionCallback
3260 */
3261
3262 /**
3263 * @param {subscriptionCallback} callback
3264 * @param {string} [id=Math.random().toString(32).slice(2).substr(0, 5)]
3265 * @return {Function} Unsubscribe function
3266 * @function
3267 */
3268
3269 }, {
3270 key: "subscribe",
3271 value: function subscribe(callback) {
3272 var _this3 = this;
3273
3274 var id = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Math.random().toString(32).slice(2).substr(0, 5);
3275 this.subscription[id] = callback;
3276 return function () {
3277 return delete _this3.subscription[id];
3278 };
3279 }
3280 /**
3281 * @return {Daux.Core.Batch} Batch instance
3282 * @function
3283 */
3284
3285 }, {
3286 key: "batch",
3287 value: function batch() {
3288 return new Batch(this);
3289 }
3290 /**
3291 * @return {Object} State
3292 * @private
3293 * @function
3294 */
3295
3296 }, {
3297 key: "buildInitialState",
3298 value: function buildInitialState() {
3299 var model = this.model;
3300 var state = {};
3301 Object.keys(model).forEach(function (modelKey) {
3302 state[modelKey] = {
3303 isDataComplete: false,
3304 data: {}
3305 };
3306 });
3307 return state;
3308 }
3309 /**
3310 * @param {string} type
3311 * @param {string} id
3312 * @param {number} [nestLevel=0]
3313 * @return {Object} State for record
3314 * @private
3315 * @function
3316 */
3317
3318 }, {
3319 key: "getCachedRecord",
3320 value: function getCachedRecord(type, id) {
3321 var _this4 = this;
3322
3323 var nestLevel = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
3324
3325 if (this.state[type].data[id]) {
3326 var cachedRecord = Object.assign({}, this.state[type].data[id]);
3327 var modelForType = this.model[type];
3328 Object.keys(modelForType.relationship).forEach(function (relationshipKey) {
3329 var descriptor = modelForType.relationship[relationshipKey];
3330
3331 if (descriptor.kind === 'belongsTo' && cachedRecord[relationshipKey]) {
3332 var belongsToId = cachedRecord[relationshipKey];
3333
3334 if (nestLevel < 1) {
3335 cachedRecord[relationshipKey] = _this4.getCachedRecord(descriptor.type, belongsToId, nestLevel + 1);
3336 } else {
3337 cachedRecord[relationshipKey] = Object.assign({}, _this4.state[descriptor.type].data[belongsToId]);
3338 }
3339 } else if (descriptor.kind === 'hasMany' && cachedRecord[relationshipKey].length > 0) {
3340 cachedRecord[relationshipKey] = cachedRecord[relationshipKey].map(function (hasManyId) {
3341 if (nestLevel < 1) {
3342 return _this4.getCachedRecord(descriptor.type, hasManyId, nestLevel + 1);
3343 }
3344
3345 return Object.assign({}, _this4.state[descriptor.type].data[hasManyId]);
3346 });
3347 }
3348 });
3349 return cachedRecord;
3350 }
3351
3352 return null;
3353 }
3354 /**
3355 * @param {string} type
3356 * @param {string} id
3357 * @return {Object} State for record
3358 * @private
3359 * @function
3360 */
3361
3362 }, {
3363 key: "getStateForRecord",
3364 value: function getStateForRecord(type, id) {
3365 return this.state[type].data[id] || null;
3366 }
3367 /**
3368 * @param {string} type
3369 * @param {string} id
3370 * @return {boolean} True if populated. Otherwise, false.
3371 * @private
3372 * @function
3373 */
3374
3375 }, {
3376 key: "isRecordAttributePopulated",
3377 value: function isRecordAttributePopulated(type, id) {
3378 var currentRecordState = this.getStateForRecord(type, id);
3379
3380 if (currentRecordState) {
3381 var attributes = this.model[type].attributes;
3382 var populatedAttribute = attributes.find(function (key) {
3383 if (currentRecordState[key] === null || Array.isArray(currentRecordState[key]) && currentRecordState[key].length === 0) {
3384 return false;
3385 }
3386
3387 return true;
3388 });
3389 return populatedAttribute;
3390 }
3391
3392 return false;
3393 }
3394 /**
3395 * @param {string} type
3396 * @param {Object} record
3397 * @param {Object} option
3398 * @param {string} key
3399 * @param {string} descriptor
3400 * @private
3401 * @function
3402 */
3403
3404 }, {
3405 key: "includeRelationship",
3406 value: function () {
3407 var _includeRelationship = _asyncToGenerator(
3408 /*#__PURE__*/
3409 regeneratorRuntime.mark(function _callee4(type, record, option, key, descriptor) {
3410 var _this5 = this;
3411
3412 var includedData, _includedData, includedDataIds, uniqueHasManyIds;
3413
3414 return regeneratorRuntime.wrap(function _callee4$(_context4) {
3415 while (1) {
3416 switch (_context4.prev = _context4.next) {
3417 case 0:
3418 if (!(descriptor.kind === 'belongsTo')) {
3419 _context4.next = 9;
3420 break;
3421 }
3422
3423 if (!(record[key] === null || !this.isRecordAttributePopulated(descriptor.type, record[key]))) {
3424 _context4.next = 7;
3425 break;
3426 }
3427
3428 _context4.next = 4;
3429 return option.include[key](record);
3430
3431 case 4:
3432 includedData = _context4.sent;
3433 this.set(descriptor.type, includedData, {
3434 isBackgroundOperation: true
3435 });
3436 this.update(type, record.id, _defineProperty({}, key, includedData.id), {
3437 isBackgroundOperation: true
3438 });
3439
3440 case 7:
3441 _context4.next = 17;
3442 break;
3443
3444 case 9:
3445 if (!(descriptor.kind === 'hasMany')) {
3446 _context4.next = 17;
3447 break;
3448 }
3449
3450 _context4.next = 12;
3451 return option.include[key](record);
3452
3453 case 12:
3454 _includedData = _context4.sent;
3455
3456 _includedData.forEach(function (data) {
3457 return _this5.set(descriptor.type, data, {
3458 isBackgroundOperation: true
3459 });
3460 });
3461
3462 includedDataIds = _includedData.map(function (data) {
3463 return data.id;
3464 });
3465 uniqueHasManyIds = _toConsumableArray(new Set(_toConsumableArray(record[key]).concat(_toConsumableArray(includedDataIds))));
3466 this.update(type, record.id, _defineProperty({}, key, uniqueHasManyIds), {
3467 isBackgroundOperation: true
3468 });
3469
3470 case 17:
3471 case "end":
3472 return _context4.stop();
3473 }
3474 }
3475 }, _callee4, this);
3476 }));
3477
3478 return function includeRelationship(_x5, _x6, _x7, _x8, _x9) {
3479 return _includeRelationship.apply(this, arguments);
3480 };
3481 }()
3482 /**
3483 * @param {string} type
3484 * @param {Object} record
3485 * @param {Object} option
3486 * @private
3487 * @function
3488 */
3489
3490 }, {
3491 key: "includeRelationships",
3492 value: function () {
3493 var _includeRelationships = _asyncToGenerator(
3494 /*#__PURE__*/
3495 regeneratorRuntime.mark(function _callee5(type, record, option) {
3496 var _this6 = this;
3497
3498 var relationship, includes;
3499 return regeneratorRuntime.wrap(function _callee5$(_context5) {
3500 while (1) {
3501 switch (_context5.prev = _context5.next) {
3502 case 0:
3503 relationship = this.model[type].relationship;
3504 includes = [];
3505 Object.keys(relationship).forEach(function (key) {
3506 if (option.include[key]) {
3507 includes.push(_this6.includeRelationship(type, record, option, key, relationship[key]));
3508 }
3509 });
3510 _context5.next = 5;
3511 return Promise.all(includes);
3512
3513 case 5:
3514 case "end":
3515 return _context5.stop();
3516 }
3517 }
3518 }, _callee5, this);
3519 }));
3520
3521 return function includeRelationships(_x10, _x11, _x12) {
3522 return _includeRelationships.apply(this, arguments);
3523 };
3524 }()
3525 /**
3526 * @param {string} type
3527 * @param {Object} record
3528 * @param {string} belongsToAttribute
3529 * @private
3530 * @function
3531 */
3532
3533 }, {
3534 key: "syncAddedBelongsTo",
3535 value: function syncAddedBelongsTo(type, record, belongsToAttribute) {
3536 var cardinality = getCardinality(this.model, type, belongsToAttribute);
3537 var descriptor = this.model[type].relationship[belongsToAttribute];
3538 var recordToSync;
3539
3540 if (_typeof(record[belongsToAttribute]) === 'object' && record[belongsToAttribute] !== null) {
3541 recordToSync = this.model[descriptor.type].deserialize(record[belongsToAttribute]);
3542 } else {
3543 recordToSync = {
3544 id: record[belongsToAttribute]
3545 };
3546 }
3547
3548 if (cardinality === 'oneToOne') {
3549 var cachedRecord = this.getStateForRecord(descriptor.type, recordToSync.id);
3550
3551 if (!cachedRecord || !cachedRecord[descriptor.inverse]) {
3552 var newRecord = Object.assign(recordToSync, _defineProperty({}, descriptor.inverse, record.id));
3553 this.set(descriptor.type, newRecord, {
3554 isBackgroundOperation: true
3555 });
3556 }
3557 } else if (cardinality === 'oneToMany') {
3558 var _cachedRecord = this.getStateForRecord(descriptor.type, recordToSync.id);
3559
3560 if (!_cachedRecord) {
3561 var _newRecord = Object.assign(recordToSync, _defineProperty({}, descriptor.inverse, [record.id]));
3562
3563 this.set(descriptor.type, _newRecord, {
3564 isBackgroundOperation: true
3565 });
3566 } else if (!_cachedRecord[descriptor.inverse].find(function (id) {
3567 return id === record.id;
3568 })) {
3569 _cachedRecord[descriptor.inverse].push(record.id);
3570 }
3571 } else {
3572 var _cachedRecord2 = this.getStateForRecord(descriptor.type, recordToSync.id) || {};
3573
3574 var _newRecord2 = Object.assign(_cachedRecord2, recordToSync);
3575
3576 this.set(descriptor.type, _newRecord2, {
3577 isBackgroundOperation: true
3578 });
3579 }
3580 }
3581 /**
3582 * @param {string} type
3583 * @param {Object} record
3584 * @param {string} hasManyAttribute
3585 * @private
3586 * @function
3587 */
3588
3589 }, {
3590 key: "syncAddedHasMany",
3591 value: function syncAddedHasMany(type, record, hasManyAttribute) {
3592 var _this7 = this;
3593
3594 var recordsToSync = record[hasManyAttribute];
3595
3596 if (Array.isArray(recordsToSync)) {
3597 recordsToSync.forEach(function (item) {
3598 var cardinality = getCardinality(_this7.model, type, hasManyAttribute);
3599 var descriptor = _this7.model[type].relationship[hasManyAttribute];
3600 var recordToSync;
3601
3602 if (_typeof(item) === 'object' && item !== null) {
3603 recordToSync = _this7.model[descriptor.type].deserialize(item);
3604 } else {
3605 recordToSync = {
3606 id: item
3607 };
3608 }
3609
3610 if (cardinality === 'oneToMany') {
3611 var cachedRecord = _this7.getStateForRecord(descriptor.type, recordToSync.id);
3612
3613 if (!cachedRecord) {
3614 var newRecord = Object.assign(recordToSync, _defineProperty({}, descriptor.inverse, record.id));
3615
3616 _this7.set(descriptor.type, newRecord, {
3617 isBackgroundOperation: true
3618 });
3619 } else {
3620 cachedRecord[descriptor.inverse] = record.id;
3621 }
3622 } else if (cardinality === 'manyToMany') {
3623 var _cachedRecord3 = _this7.getStateForRecord(descriptor.type, recordToSync.id);
3624
3625 if (!_cachedRecord3) {
3626 var _newRecord3 = Object.assign(recordToSync, _defineProperty({}, descriptor.inverse, [record.id]));
3627
3628 _this7.set(descriptor.type, _newRecord3, {
3629 isBackgroundOperation: true
3630 });
3631 } else if (!_cachedRecord3[descriptor.inverse].find(function (id) {
3632 return id === record.id;
3633 })) {
3634 _cachedRecord3[descriptor.inverse].push(record.id);
3635 }
3636 } else {
3637 var _cachedRecord4 = _this7.getStateForRecord(descriptor.type, recordToSync.id) || {};
3638
3639 var _newRecord4 = Object.assign(_cachedRecord4, recordToSync);
3640
3641 _this7.set(descriptor.type, _newRecord4, {
3642 isBackgroundOperation: true
3643 });
3644 }
3645 });
3646 }
3647 }
3648 /**
3649 * @param {string} type
3650 * @param {Object} record
3651 * @param {string} hasManyAttribute
3652 * @private
3653 * @function
3654 */
3655
3656 }, {
3657 key: "syncExistingHasMany",
3658 value: function syncExistingHasMany(type, record, hasManyAttribute) {
3659 var cardinality = getCardinality(this.model, type, hasManyAttribute);
3660 var descriptor = this.model[type].relationship[hasManyAttribute];
3661 var inverseData = this.state[descriptor.type].data;
3662 var recordId = _typeof(record) === 'object' && record !== null ? record.id : record;
3663
3664 if (cardinality === 'oneToMany') {
3665 var currentHasManyState = this.state[type].data[recordId][hasManyAttribute];
3666 var inverseIds = Object.keys(this.state[descriptor.type].data).filter(function (id) {
3667 return inverseData[id][descriptor.inverse] === recordId;
3668 });
3669 inverseIds.forEach(function (id) {
3670 if (!currentHasManyState.includes(id)) {
3671 currentHasManyState.push(id);
3672 }
3673 });
3674 } else if (cardinality === 'manyToMany') {
3675 var _currentHasManyState = this.state[type].data[recordId][hasManyAttribute];
3676
3677 var _inverseIds = Object.keys(this.state[descriptor.type].data).filter(function (id) {
3678 return inverseData[id][descriptor.inverse].includes(recordId);
3679 });
3680
3681 _inverseIds.forEach(function (id) {
3682 if (!_currentHasManyState.includes(id)) {
3683 _currentHasManyState.push(id);
3684 }
3685 });
3686 }
3687 }
3688 /**
3689 * @param {string} type
3690 * @param {Object} record
3691 * @private
3692 * @function
3693 */
3694
3695 }, {
3696 key: "syncAddedRelationships",
3697 value: function syncAddedRelationships(type, record) {
3698 var _this8 = this;
3699
3700 Object.keys(this.model[type].relationship).forEach(function (relationshipKey) {
3701 var kind = _this8.model[type].relationship[relationshipKey].kind;
3702
3703 if (record[relationshipKey]) {
3704 if (kind === 'belongsTo') {
3705 _this8.syncAddedBelongsTo(type, record, relationshipKey);
3706 } else {
3707 _this8.syncAddedHasMany(type, record, relationshipKey);
3708 }
3709 } else if (kind === 'hasMany') {
3710 _this8.syncExistingHasMany(type, record, relationshipKey);
3711 }
3712 });
3713 }
3714 /**
3715 * @param {string} type
3716 * @param {Object} currentRecord
3717 * @param {Object} oldRecord
3718 * @param {string} key
3719 * @param {Object} descriptor
3720 * @private
3721 * @function
3722 */
3723
3724 }, {
3725 key: "syncRemovedBelongsToRelationship",
3726 value: function syncRemovedBelongsToRelationship(type, currentRecord, oldRecord, key, descriptor) {
3727 if (currentRecord[key] === null && currentRecord[key] !== oldRecord[key]) {
3728 var inverseRecord = this.getStateForRecord(descriptor.type, oldRecord[key]);
3729
3730 if (inverseRecord) {
3731 var cardinality = getCardinality(this.model, type, key);
3732
3733 if (cardinality === 'oneToOne') {
3734 inverseRecord[descriptor.inverse] = null;
3735 } else if (cardinality === 'oneToMany') {
3736 inverseRecord[descriptor.inverse] = inverseRecord[descriptor.inverse].filter(function (id) {
3737 return id !== oldRecord.id;
3738 });
3739 }
3740 }
3741 }
3742 }
3743 /**
3744 * @param {string} type
3745 * @param {Object} currentRecord
3746 * @param {Object} oldRecord
3747 * @param {string} key
3748 * @param {Object} descriptor
3749 * @private
3750 * @function
3751 */
3752
3753 }, {
3754 key: "syncRemovedHasManyRelationship",
3755 value: function syncRemovedHasManyRelationship(type, currentRecord, oldRecord, key, descriptor) {
3756 var _this9 = this;
3757
3758 var removedRecords = oldRecord[key].filter(function (record) {
3759 return !currentRecord[key].includes(record);
3760 });
3761 removedRecords.forEach(function (removedRecord) {
3762 var inverseRecord = _this9.getStateForRecord(descriptor.type, removedRecord);
3763
3764 if (inverseRecord) {
3765 var cardinality = getCardinality(_this9.model, type, key);
3766
3767 if (cardinality === 'oneToMany') {
3768 inverseRecord[descriptor.inverse] = null;
3769 } else if (cardinality === 'manyToMany') {
3770 inverseRecord[descriptor.inverse] = inverseRecord[descriptor.inverse].filter(function (id) {
3771 return id !== oldRecord.id;
3772 });
3773 }
3774 }
3775 });
3776 }
3777 /**
3778 * @param {string} type
3779 * @param {Object} currentRecord
3780 * @param {Object} oldRecord
3781 * @private
3782 * @function
3783 */
3784
3785 }, {
3786 key: "syncRemovedRelationships",
3787 value: function syncRemovedRelationships(type, currentRecord, oldRecord) {
3788 var _this10 = this;
3789
3790 var model = this.model[type];
3791 Object.keys(model.relationship).forEach(function (attributeKey) {
3792 var descriptor = model.relationship[attributeKey];
3793
3794 if (descriptor.kind === 'belongsTo') {
3795 _this10.syncRemovedBelongsToRelationship(type, currentRecord, oldRecord, attributeKey, descriptor);
3796 } else if (descriptor.kind === 'hasMany') {
3797 _this10.syncRemovedHasManyRelationship(type, currentRecord, oldRecord, attributeKey, descriptor);
3798 }
3799 });
3800 }
3801 /**
3802 * @private
3803 * @function
3804 */
3805
3806 }, {
3807 key: "triggerSubscriptions",
3808 value: function triggerSubscriptions() {
3809 var _this11 = this;
3810
3811 Object.keys(this.subscription).forEach(function (key) {
3812 try {
3813 _this11.subscription[key]();
3814 } catch (error) {
3815 delete _this11.subscription[key];
3816 }
3817 });
3818 }
3819 }]);
3820
3821 return Store;
3822 }();
3823
3824 exports.Model = Model;
3825 exports.Store = Store;
3826
3827 Object.defineProperty(exports, '__esModule', { value: true });
3828
3829})));