UNPKG

213 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3 typeof define === 'function' && define.amd ? define(factory) :
4 (global.bearer = factory());
5}(this, (function () { 'use strict';
6
7 /*! *****************************************************************************
8 Copyright (c) Microsoft Corporation. All rights reserved.
9 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
10 this file except in compliance with the License. You may obtain a copy of the
11 License at http://www.apache.org/licenses/LICENSE-2.0
12
13 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
15 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
16 MERCHANTABLITY OR NON-INFRINGEMENT.
17
18 See the Apache Version 2.0 License for specific language governing permissions
19 and limitations under the License.
20 ***************************************************************************** */
21
22 function __rest(s, e) {
23 var t = {};
24 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
25 t[p] = s[p];
26 if (s != null && typeof Object.getOwnPropertySymbols === "function")
27 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
28 t[p[i]] = s[p[i]];
29 return t;
30 }
31
32 function __awaiter(thisArg, _arguments, P, generator) {
33 return new (P || (P = Promise))(function (resolve, reject) {
34 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
35 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
36 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
37 step((generator = generator.apply(thisArg, _arguments || [])).next());
38 });
39 }
40
41 /**
42 * Returns a function, that, as long as it continues to be invoked, will not
43 * be triggered. The function will be called after it stops being called for
44 * N milliseconds. If `immediate` is passed, trigger the function on the
45 * leading edge, instead of the trailing. The function also has a property 'clear'
46 * that is a function which will clear the timer to prevent previously scheduled executions.
47 *
48 * @source underscore.js
49 * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
50 * @param {Function} function to wrap
51 * @param {Number} timeout in ms (`100`)
52 * @param {Boolean} whether to execute at the beginning (`false`)
53 * @api public
54 */
55 function debounce(func, wait, immediate){
56 var timeout, args, context, timestamp, result;
57 if (null == wait) wait = 100;
58
59 function later() {
60 var last = Date.now() - timestamp;
61
62 if (last < wait && last >= 0) {
63 timeout = setTimeout(later, wait - last);
64 } else {
65 timeout = null;
66 if (!immediate) {
67 result = func.apply(context, args);
68 context = args = null;
69 }
70 }
71 }
72 var debounced = function(){
73 context = this;
74 args = arguments;
75 timestamp = Date.now();
76 var callNow = immediate && !timeout;
77 if (!timeout) timeout = setTimeout(later, wait);
78 if (callNow) {
79 result = func.apply(context, args);
80 context = args = null;
81 }
82
83 return result;
84 };
85
86 debounced.clear = function() {
87 if (timeout) {
88 clearTimeout(timeout);
89 timeout = null;
90 }
91 };
92
93 debounced.flush = function() {
94 if (timeout) {
95 result = func.apply(context, args);
96 context = args = null;
97
98 clearTimeout(timeout);
99 timeout = null;
100 }
101 };
102
103 return debounced;
104 }
105 // Adds compatibility for ES modules
106 debounce.debounce = debounce;
107
108 var debounce_1 = debounce;
109
110 var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
111
112 function unwrapExports (x) {
113 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x.default : x;
114 }
115
116 function createCommonjsModule(fn, module) {
117 return module = { exports: {} }, fn(module, module.exports), module.exports;
118 }
119
120 var postRobot = createCommonjsModule(function (module, exports) {
121 !function(root, factory) {
122 module.exports = factory();
123 }("undefined" != typeof self ? self : commonjsGlobal, function() {
124 return function(modules) {
125 var installedModules = {};
126 function __webpack_require__(moduleId) {
127 if (installedModules[moduleId]) return installedModules[moduleId].exports;
128 var module = installedModules[moduleId] = {
129 i: moduleId,
130 l: !1,
131 exports: {}
132 };
133 modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
134 module.l = !0;
135 return module.exports;
136 }
137 __webpack_require__.m = modules;
138 __webpack_require__.c = installedModules;
139 __webpack_require__.d = function(exports, name, getter) {
140 __webpack_require__.o(exports, name) || Object.defineProperty(exports, name, {
141 configurable: !1,
142 enumerable: !0,
143 get: getter
144 });
145 };
146 __webpack_require__.n = function(module) {
147 var getter = module && module.__esModule ? function() {
148 return module.default;
149 } : function() {
150 return module;
151 };
152 __webpack_require__.d(getter, "a", getter);
153 return getter;
154 };
155 __webpack_require__.o = function(object, property) {
156 return Object.prototype.hasOwnProperty.call(object, property);
157 };
158 __webpack_require__.p = "";
159 return __webpack_require__(__webpack_require__.s = "./src/index.js");
160 }({
161 "./node_modules/cross-domain-utils/src/constants.js": function(module, __webpack_exports__, __webpack_require__) {
162 __webpack_require__.d(__webpack_exports__, "a", function() {
163 return PROTOCOL;
164 });
165 __webpack_require__.d(__webpack_exports__, "b", function() {
166 return WILDCARD;
167 });
168 var PROTOCOL = {
169 MOCK: "mock:",
170 FILE: "file:",
171 ABOUT: "about:"
172 }, WILDCARD = "*";
173 },
174 "./node_modules/cross-domain-utils/src/index.js": function(module, __webpack_exports__, __webpack_require__) {
175 var __WEBPACK_IMPORTED_MODULE_0__utils__ = __webpack_require__("./node_modules/cross-domain-utils/src/utils.js");
176 __webpack_require__.d(__webpack_exports__, "getActualDomain", function() {
177 return __WEBPACK_IMPORTED_MODULE_0__utils__.a;
178 });
179 __webpack_require__.d(__webpack_exports__, "getAncestor", function() {
180 return __WEBPACK_IMPORTED_MODULE_0__utils__.b;
181 });
182 __webpack_require__.d(__webpack_exports__, "getDomain", function() {
183 return __WEBPACK_IMPORTED_MODULE_0__utils__.c;
184 });
185 __webpack_require__.d(__webpack_exports__, "getUserAgent", function() {
186 return __WEBPACK_IMPORTED_MODULE_0__utils__.d;
187 });
188 __webpack_require__.d(__webpack_exports__, "isActuallySameDomain", function() {
189 return __WEBPACK_IMPORTED_MODULE_0__utils__.e;
190 });
191 __webpack_require__.d(__webpack_exports__, "isAncestor", function() {
192 return __WEBPACK_IMPORTED_MODULE_0__utils__.f;
193 });
194 __webpack_require__.d(__webpack_exports__, "isIframe", function() {
195 return __WEBPACK_IMPORTED_MODULE_0__utils__.g;
196 });
197 __webpack_require__.d(__webpack_exports__, "isPopup", function() {
198 return __WEBPACK_IMPORTED_MODULE_0__utils__.h;
199 });
200 __webpack_require__.d(__webpack_exports__, "isWindow", function() {
201 return __WEBPACK_IMPORTED_MODULE_0__utils__.i;
202 });
203 __webpack_require__.d(__webpack_exports__, "isWindowClosed", function() {
204 return __WEBPACK_IMPORTED_MODULE_0__utils__.j;
205 });
206 __webpack_require__.d(__webpack_exports__, "matchDomain", function() {
207 return __WEBPACK_IMPORTED_MODULE_0__utils__.k;
208 });
209 __webpack_require__.d(__webpack_exports__, "stringifyDomainPattern", function() {
210 return __WEBPACK_IMPORTED_MODULE_0__utils__.l;
211 });
212 var __WEBPACK_IMPORTED_MODULE_1__types__ = __webpack_require__("./node_modules/cross-domain-utils/src/types.js");
213 __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__types__), __webpack_require__("./node_modules/cross-domain-utils/src/constants.js");
214 },
215 "./node_modules/cross-domain-utils/src/types.js": function(module, exports) {},
216 "./node_modules/cross-domain-utils/src/utils.js": function(module, __webpack_exports__, __webpack_require__) {
217 function isRegex(item) {
218 return "[object RegExp]" === Object.prototype.toString.call(item);
219 }
220 var constants = __webpack_require__("./node_modules/cross-domain-utils/src/constants.js");
221 __webpack_exports__.a = getActualDomain;
222 __webpack_exports__.c = getDomain;
223 __webpack_exports__.e = isActuallySameDomain;
224 __webpack_exports__.j = function(win) {
225 var allowMock = !(arguments.length > 1 && void 0 !== arguments[1]) || arguments[1];
226 try {
227 if (win === window) return !1;
228 } catch (err) {
229 return !0;
230 }
231 try {
232 if (!win) return !0;
233 } catch (err) {
234 return !0;
235 }
236 try {
237 if (win.closed) return !0;
238 } catch (err) {
239 return !err || err.message !== IE_WIN_ACCESS_ERROR;
240 }
241 if (allowMock && function(win) {
242 if (!isActuallySameDomain(win)) return !1;
243 try {
244 if (win === window) return !0;
245 if (isAboutProtocol(win) && canReadFromWindow(win)) return !0;
246 if (getDomain(window) === getDomain(win)) return !0;
247 } catch (err) {}
248 return !1;
249 }(win)) try {
250 if (win.mockclosed) return !0;
251 } catch (err) {}
252 try {
253 if (!win.parent || !win.top) return !0;
254 } catch (err) {}
255 var iframeIndex = function(collection, item) {
256 for (var i = 0; i < collection.length; i++) try {
257 if (collection[i] === item) return i;
258 } catch (err) {}
259 return -1;
260 }(iframeWindows, win);
261 if (-1 !== iframeIndex) {
262 var frame = iframeFrames[iframeIndex];
263 if (frame && function(frame) {
264 if (!frame.contentWindow) return !0;
265 if (!frame.parentNode) return !0;
266 var doc = frame.ownerDocument;
267 return !(!doc || !doc.documentElement || doc.documentElement.contains(frame));
268 }(frame)) return !0;
269 }
270 return !1;
271 };
272 __webpack_exports__.d = function(win) {
273 return (win = win || window).navigator.mockUserAgent || win.navigator.userAgent;
274 };
275 __webpack_exports__.b = getAncestor;
276 __webpack_exports__.f = function(parent, child) {
277 var actualParent = getAncestor(child);
278 if (actualParent) return actualParent === parent;
279 if (child === parent) return !1;
280 if (function(win) {
281 if (win) {
282 try {
283 if (win.top) return win.top;
284 } catch (err) {}
285 if (getParent(win) === win) return win;
286 try {
287 if (isAncestorParent(window, win) && window.top) return window.top;
288 } catch (err) {}
289 try {
290 if (isAncestorParent(win, window) && window.top) return window.top;
291 } catch (err) {}
292 for (var _i7 = 0, _getAllChildFrames4 = function getAllChildFrames(win) {
293 for (var result = [], _i3 = 0, _getFrames2 = getFrames(win), _length2 = null == _getFrames2 ? 0 : _getFrames2.length; _i3 < _length2; _i3++) {
294 var frame = _getFrames2[_i3];
295 result.push(frame);
296 for (var _i5 = 0, _getAllChildFrames2 = getAllChildFrames(frame), _length4 = null == _getAllChildFrames2 ? 0 : _getAllChildFrames2.length; _i5 < _length4; _i5++) {
297 var childFrame = _getAllChildFrames2[_i5];
298 result.push(childFrame);
299 }
300 }
301 return result;
302 }(win), _length6 = null == _getAllChildFrames4 ? 0 : _getAllChildFrames4.length; _i7 < _length6; _i7++) {
303 var frame = _getAllChildFrames4[_i7];
304 try {
305 if (frame.top) return frame.top;
306 } catch (err) {}
307 if (getParent(frame) === frame) return frame;
308 }
309 }
310 }(child) === child) return !1;
311 for (var _i15 = 0, _getFrames8 = getFrames(parent), _length14 = null == _getFrames8 ? 0 : _getFrames8.length; _i15 < _length14; _i15++) if (_getFrames8[_i15] === child) return !0;
312 return !1;
313 };
314 __webpack_exports__.h = function() {
315 return Boolean(getOpener(window));
316 };
317 __webpack_exports__.g = function() {
318 return Boolean(getParent(window));
319 };
320 __webpack_exports__.k = function matchDomain(pattern, origin) {
321 if ("string" == typeof pattern) {
322 if ("string" == typeof origin) return pattern === constants.b || origin === pattern;
323 if (isRegex(origin)) return !1;
324 if (Array.isArray(origin)) return !1;
325 }
326 return isRegex(pattern) ? isRegex(origin) ? pattern.toString() === origin.toString() : !Array.isArray(origin) && Boolean(origin.match(pattern)) : !!Array.isArray(pattern) && (Array.isArray(origin) ? JSON.stringify(pattern) === JSON.stringify(origin) : !isRegex(origin) && pattern.some(function(subpattern) {
327 return matchDomain(subpattern, origin);
328 }));
329 };
330 __webpack_exports__.l = function(pattern) {
331 return Array.isArray(pattern) ? "(" + pattern.join(" | ") + ")" : isRegex(pattern) ? "RegExp(" + pattern.toString() : pattern.toString();
332 };
333 __webpack_exports__.i = function(obj) {
334 try {
335 if (obj === window) return !0;
336 } catch (err) {
337 if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;
338 }
339 try {
340 if ("[object Window]" === Object.prototype.toString.call(obj)) return !0;
341 } catch (err) {
342 if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;
343 }
344 try {
345 if (window.Window && obj instanceof window.Window) return !0;
346 } catch (err) {
347 if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;
348 }
349 try {
350 if (obj && obj.self === obj) return !0;
351 } catch (err) {
352 if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;
353 }
354 try {
355 if (obj && obj.parent === obj) return !0;
356 } catch (err) {
357 if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;
358 }
359 try {
360 if (obj && obj.top === obj) return !0;
361 } catch (err) {
362 if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;
363 }
364 try {
365 obj && obj.__cross_domain_utils_window_check__;
366 } catch (err) {
367 return !0;
368 }
369 return !1;
370 };
371 var IE_WIN_ACCESS_ERROR = "Call was rejected by callee.\r\n";
372 function isAboutProtocol() {
373 return (arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : window).location.protocol === constants.a.ABOUT;
374 }
375 function getParent(win) {
376 if (win) try {
377 if (win.parent && win.parent !== win) return win.parent;
378 } catch (err) {}
379 }
380 function getOpener(win) {
381 if (win && !getParent(win)) try {
382 return win.opener;
383 } catch (err) {}
384 }
385 function canReadFromWindow(win) {
386 try {
387 win && win.location && win.location.href;
388 return !0;
389 } catch (err) {}
390 return !1;
391 }
392 function getActualDomain(win) {
393 var location = (win = win || window).location;
394 if (!location) throw new Error("Can not read window location");
395 var protocol = location.protocol;
396 if (!protocol) throw new Error("Can not read window protocol");
397 if (protocol === constants.a.FILE) return constants.a.FILE + "//";
398 if (protocol === constants.a.ABOUT) {
399 var parent = getParent(win);
400 return parent && canReadFromWindow(parent) ? getActualDomain(parent) : constants.a.ABOUT + "//";
401 }
402 var host = location.host;
403 if (!host) throw new Error("Can not read window host");
404 return protocol + "//" + host;
405 }
406 function getDomain(win) {
407 var domain = getActualDomain(win = win || window);
408 return domain && win.mockDomain && 0 === win.mockDomain.indexOf(constants.a.MOCK) ? win.mockDomain : domain;
409 }
410 function isActuallySameDomain(win) {
411 try {
412 if (win === window) return !0;
413 } catch (err) {}
414 try {
415 var desc = Object.getOwnPropertyDescriptor(win, "location");
416 if (desc && !1 === desc.enumerable) return !1;
417 } catch (err) {}
418 try {
419 if (isAboutProtocol(win) && canReadFromWindow(win)) return !0;
420 } catch (err) {}
421 try {
422 if (getActualDomain(win) === getActualDomain(window)) return !0;
423 } catch (err) {}
424 return !1;
425 }
426 function isAncestorParent(parent, child) {
427 if (!parent || !child) return !1;
428 var childParent = getParent(child);
429 return childParent ? childParent === parent : -1 !== function(win) {
430 var result = [];
431 try {
432 for (;win.parent !== win; ) {
433 result.push(win.parent);
434 win = win.parent;
435 }
436 } catch (err) {}
437 return result;
438 }(child).indexOf(parent);
439 }
440 function getFrames(win) {
441 var result = [], frames = void 0;
442 try {
443 frames = win.frames;
444 } catch (err) {
445 frames = win;
446 }
447 var len = void 0;
448 try {
449 len = frames.length;
450 } catch (err) {}
451 if (0 === len) return result;
452 if (len) {
453 for (var i = 0; i < len; i++) {
454 var frame = void 0;
455 try {
456 frame = frames[i];
457 } catch (err) {
458 continue;
459 }
460 result.push(frame);
461 }
462 return result;
463 }
464 for (var _i = 0; _i < 100; _i++) {
465 var _frame = void 0;
466 try {
467 _frame = frames[_i];
468 } catch (err) {
469 return result;
470 }
471 if (!_frame) return result;
472 result.push(_frame);
473 }
474 return result;
475 }
476 var iframeWindows = [], iframeFrames = [];
477 function getAncestor(win) {
478 return getOpener(win = win || window) || getParent(win) || void 0;
479 }
480 },
481 "./src/index.js": function(module, __webpack_exports__, __webpack_require__) {
482 Object.defineProperty(__webpack_exports__, "__esModule", {
483 value: !0
484 });
485 __webpack_require__.d({}, "WeakMap", function() {
486 return weakmap_CrossDomainSafeWeakMap;
487 });
488 var src_interface_namespaceObject = {};
489 __webpack_require__.d(src_interface_namespaceObject, "cleanUpWindow", function() {
490 return cleanUpWindow;
491 });
492 __webpack_require__.d(src_interface_namespaceObject, "Promise", function() {
493 return promise_ZalgoPromise;
494 });
495 __webpack_require__.d(src_interface_namespaceObject, "bridge", function() {
496 return bridge;
497 });
498 __webpack_require__.d(src_interface_namespaceObject, "init", function() {
499 return init;
500 });
501 __webpack_require__.d(src_interface_namespaceObject, "parent", function() {
502 return public_parent;
503 });
504 __webpack_require__.d(src_interface_namespaceObject, "send", function() {
505 return _send;
506 });
507 __webpack_require__.d(src_interface_namespaceObject, "request", function() {
508 return request;
509 });
510 __webpack_require__.d(src_interface_namespaceObject, "sendToParent", function() {
511 return sendToParent;
512 });
513 __webpack_require__.d(src_interface_namespaceObject, "client", function() {
514 return client;
515 });
516 __webpack_require__.d(src_interface_namespaceObject, "on", function() {
517 return _on;
518 });
519 __webpack_require__.d(src_interface_namespaceObject, "listen", function() {
520 return listen;
521 });
522 __webpack_require__.d(src_interface_namespaceObject, "once", function() {
523 return server_once;
524 });
525 __webpack_require__.d(src_interface_namespaceObject, "listener", function() {
526 return server_listener;
527 });
528 __webpack_require__.d(src_interface_namespaceObject, "CONFIG", function() {
529 return CONFIG;
530 });
531 __webpack_require__.d(src_interface_namespaceObject, "CONSTANTS", function() {
532 return constants_CONSTANTS;
533 });
534 __webpack_require__.d(src_interface_namespaceObject, "disable", function() {
535 return disable;
536 });
537 var src = __webpack_require__("./node_modules/cross-domain-utils/src/index.js");
538 function safeIndexOf(collection, item) {
539 for (var i = 0; i < collection.length; i++) try {
540 if (collection[i] === item) return i;
541 } catch (err) {}
542 return -1;
543 }
544 var _ALLOWED_POST_MESSAGE, defineProperty = Object.defineProperty, counter = Date.now() % 1e9, weakmap_CrossDomainSafeWeakMap = function() {
545 function CrossDomainSafeWeakMap() {
546 !function(instance, Constructor) {
547 if (!(instance instanceof CrossDomainSafeWeakMap)) throw new TypeError("Cannot call a class as a function");
548 }(this);
549 counter += 1;
550 this.name = "__weakmap_" + (1e9 * Math.random() >>> 0) + "__" + counter;
551 if (function() {
552 if ("undefined" == typeof WeakMap) return !1;
553 if (void 0 === Object.freeze) return !1;
554 try {
555 var testWeakMap = new WeakMap(), testKey = {};
556 Object.freeze(testKey);
557 testWeakMap.set(testKey, "__testvalue__");
558 return "__testvalue__" === testWeakMap.get(testKey);
559 } catch (err) {
560 return !1;
561 }
562 }()) try {
563 this.weakmap = new WeakMap();
564 } catch (err) {}
565 this.keys = [];
566 this.values = [];
567 }
568 CrossDomainSafeWeakMap.prototype._cleanupClosedWindows = function() {
569 for (var weakmap = this.weakmap, keys = this.keys, i = 0; i < keys.length; i++) {
570 var value = keys[i];
571 if (Object(src.isWindow)(value) && Object(src.isWindowClosed)(value)) {
572 if (weakmap) try {
573 weakmap.delete(value);
574 } catch (err) {}
575 keys.splice(i, 1);
576 this.values.splice(i, 1);
577 i -= 1;
578 }
579 }
580 };
581 CrossDomainSafeWeakMap.prototype.isSafeToReadWrite = function(key) {
582 if (Object(src.isWindow)(key)) return !1;
583 try {
584 key && key.self;
585 key && key[this.name];
586 } catch (err) {
587 return !1;
588 }
589 return !0;
590 };
591 CrossDomainSafeWeakMap.prototype.set = function(key, value) {
592 if (!key) throw new Error("WeakMap expected key");
593 var weakmap = this.weakmap;
594 if (weakmap) try {
595 weakmap.set(key, value);
596 } catch (err) {
597 delete this.weakmap;
598 }
599 if (this.isSafeToReadWrite(key)) {
600 var name = this.name, entry = key[name];
601 entry && entry[0] === key ? entry[1] = value : defineProperty(key, name, {
602 value: [ key, value ],
603 writable: !0
604 });
605 } else {
606 this._cleanupClosedWindows();
607 var keys = this.keys, values = this.values, index = safeIndexOf(keys, key);
608 if (-1 === index) {
609 keys.push(key);
610 values.push(value);
611 } else values[index] = value;
612 }
613 };
614 CrossDomainSafeWeakMap.prototype.get = function(key) {
615 if (!key) throw new Error("WeakMap expected key");
616 var weakmap = this.weakmap;
617 if (weakmap) try {
618 if (weakmap.has(key)) return weakmap.get(key);
619 } catch (err) {
620 delete this.weakmap;
621 }
622 if (!this.isSafeToReadWrite(key)) {
623 this._cleanupClosedWindows();
624 var index = safeIndexOf(this.keys, key);
625 if (-1 === index) return;
626 return this.values[index];
627 }
628 var entry = key[this.name];
629 if (entry && entry[0] === key) return entry[1];
630 };
631 CrossDomainSafeWeakMap.prototype.delete = function(key) {
632 if (!key) throw new Error("WeakMap expected key");
633 var weakmap = this.weakmap;
634 if (weakmap) try {
635 weakmap.delete(key);
636 } catch (err) {
637 delete this.weakmap;
638 }
639 if (this.isSafeToReadWrite(key)) {
640 var entry = key[this.name];
641 entry && entry[0] === key && (entry[0] = entry[1] = void 0);
642 } else {
643 this._cleanupClosedWindows();
644 var keys = this.keys, index = safeIndexOf(keys, key);
645 if (-1 !== index) {
646 keys.splice(index, 1);
647 this.values.splice(index, 1);
648 }
649 }
650 };
651 CrossDomainSafeWeakMap.prototype.has = function(key) {
652 if (!key) throw new Error("WeakMap expected key");
653 var weakmap = this.weakmap;
654 if (weakmap) try {
655 if (weakmap.has(key)) return !0;
656 } catch (err) {
657 delete this.weakmap;
658 }
659 if (this.isSafeToReadWrite(key)) {
660 var entry = key[this.name];
661 return !(!entry || entry[0] !== key);
662 }
663 this._cleanupClosedWindows();
664 return -1 !== safeIndexOf(this.keys, key);
665 };
666 CrossDomainSafeWeakMap.prototype.getOrSet = function(key, getter) {
667 if (this.has(key)) return this.get(key);
668 var value = getter();
669 this.set(key, value);
670 return value;
671 };
672 return CrossDomainSafeWeakMap;
673 }(), constants_CONSTANTS = {
674 POST_MESSAGE_TYPE: {
675 REQUEST: "postrobot_message_request",
676 RESPONSE: "postrobot_message_response",
677 ACK: "postrobot_message_ack"
678 },
679 POST_MESSAGE_ACK: {
680 SUCCESS: "success",
681 ERROR: "error"
682 },
683 POST_MESSAGE_NAMES: {
684 METHOD: "postrobot_method",
685 HELLO: "postrobot_ready",
686 OPEN_TUNNEL: "postrobot_open_tunnel"
687 },
688 WINDOW_TYPES: {
689 FULLPAGE: "fullpage",
690 POPUP: "popup",
691 IFRAME: "iframe"
692 },
693 WINDOW_PROPS: {
694 POSTROBOT: "__postRobot__"
695 },
696 SERIALIZATION_TYPES: {
697 METHOD: "postrobot_method",
698 ERROR: "postrobot_error",
699 PROMISE: "postrobot_promise",
700 ZALGO_PROMISE: "postrobot_zalgo_promise",
701 REGEX: "regex"
702 },
703 SEND_STRATEGIES: {
704 POST_MESSAGE: "postrobot_post_message",
705 BRIDGE: "postrobot_bridge",
706 GLOBAL: "postrobot_global"
707 },
708 MOCK_PROTOCOL: "mock:",
709 FILE_PROTOCOL: "file:",
710 BRIDGE_NAME_PREFIX: "__postrobot_bridge__",
711 POSTROBOT_PROXY: "__postrobot_proxy__",
712 WILDCARD: "*"
713 }, POST_MESSAGE_NAMES = {
714 METHOD: "postrobot_method",
715 HELLO: "postrobot_hello",
716 OPEN_TUNNEL: "postrobot_open_tunnel"
717 }, CONFIG = (Object.keys(POST_MESSAGE_NAMES).map(function(key) {
718 return POST_MESSAGE_NAMES[key];
719 }), {
720 ALLOW_POSTMESSAGE_POPUP: !("__ALLOW_POSTMESSAGE_POPUP__" in window) || window.__ALLOW_POSTMESSAGE_POPUP__,
721 BRIDGE_TIMEOUT: 5e3,
722 CHILD_WINDOW_TIMEOUT: 5e3,
723 ACK_TIMEOUT: -1 !== window.navigator.userAgent.match(/MSIE/i) ? 1e4 : 2e3,
724 RES_TIMEOUT: -1,
725 ALLOWED_POST_MESSAGE_METHODS: (_ALLOWED_POST_MESSAGE = {}, _ALLOWED_POST_MESSAGE[constants_CONSTANTS.SEND_STRATEGIES.POST_MESSAGE] = !0,
726 _ALLOWED_POST_MESSAGE[constants_CONSTANTS.SEND_STRATEGIES.BRIDGE] = !0, _ALLOWED_POST_MESSAGE[constants_CONSTANTS.SEND_STRATEGIES.GLOBAL] = !0,
727 _ALLOWED_POST_MESSAGE),
728 ALLOW_SAME_ORIGIN: !1
729 });
730 0 === window.location.href.indexOf(constants_CONSTANTS.FILE_PROTOCOL) && (CONFIG.ALLOW_POSTMESSAGE_POPUP = !0);
731 var _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
732 return typeof obj;
733 } : function(obj) {
734 return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
735 };
736 function stringifyError(err) {
737 var level = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 1;
738 if (level >= 3) return "stringifyError stack overflow";
739 try {
740 if (!err) return "<unknown error: " + Object.prototype.toString.call(err) + ">";
741 if ("string" == typeof err) return err;
742 if (err instanceof Error) {
743 var stack = err && err.stack, message = err && err.message;
744 if (stack && message) return -1 !== stack.indexOf(message) ? stack : message + "\n" + stack;
745 if (stack) return stack;
746 if (message) return message;
747 }
748 return "function" == typeof err.toString ? err.toString() : Object.prototype.toString.call(err);
749 } catch (newErr) {
750 return "Error while stringifying error: " + stringifyError(newErr, level + 1);
751 }
752 }
753 var once = function(method) {
754 if (!method) return method;
755 var called = !1;
756 return function() {
757 if (!called) {
758 called = !0;
759 return method.apply(this, arguments);
760 }
761 };
762 };
763 function util_noop() {}
764 function uniqueID() {
765 var chars = "0123456789abcdef";
766 return "xxxxxxxxxx".replace(/./g, function() {
767 return chars.charAt(Math.floor(Math.random() * chars.length));
768 });
769 }
770 function replaceObject(item, callback) {
771 var depth = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 1;
772 if (depth >= 100) throw new Error("Self-referential object passed, or object contained too many layers");
773 var newobj = void 0;
774 if ("object" !== (void 0 === item ? "undefined" : _typeof(item)) || null === item || Array.isArray(item)) {
775 if (!Array.isArray(item)) throw new TypeError("Invalid type: " + (void 0 === item ? "undefined" : _typeof(item)));
776 newobj = [];
777 } else newobj = {};
778 !function(item, callback) {
779 Array.isArray(item) ? function(item, callback) {
780 for (var i = 0; i < item.length; i++) callback(item[i], i);
781 }(item, callback) : "object" === (void 0 === item ? "undefined" : _typeof(item)) && null !== item && function(item, callback) {
782 for (var _key in item) item.hasOwnProperty(_key) && callback(item[_key], _key);
783 }(item, callback);
784 }(item, function(childItem, key) {
785 var result = callback(childItem, key);
786 void 0 !== result ? newobj[key] = result : "object" === (void 0 === childItem ? "undefined" : _typeof(childItem)) && null !== childItem ? newobj[key] = replaceObject(childItem, callback, depth + 1) : newobj[key] = childItem;
787 });
788 return newobj;
789 }
790 function isRegex(item) {
791 return "[object RegExp]" === Object.prototype.toString.call(item);
792 }
793 function utils_isPromise(item) {
794 try {
795 if (!item) return !1;
796 if ("undefined" != typeof Promise && item instanceof Promise) return !0;
797 if ("undefined" != typeof window && window.Window && item instanceof window.Window) return !1;
798 if ("undefined" != typeof window && window.constructor && item instanceof window.constructor) return !1;
799 if ("function" == typeof item.then) return !0;
800 } catch (err) {
801 return !1;
802 }
803 return !1;
804 }
805 function getGlobal() {
806 var glob = void 0;
807 if ("undefined" != typeof window) glob = window; else {
808 if ("undefined" == typeof window) throw new TypeError("Can not find global");
809 glob = window;
810 }
811 var zalgoGlobal = glob.__zalgopromise__ = glob.__zalgopromise__ || {};
812 zalgoGlobal.flushPromises = zalgoGlobal.flushPromises || [];
813 zalgoGlobal.activeCount = zalgoGlobal.activeCount || 0;
814 zalgoGlobal.possiblyUnhandledPromiseHandlers = zalgoGlobal.possiblyUnhandledPromiseHandlers || [];
815 zalgoGlobal.dispatchedErrors = zalgoGlobal.dispatchedErrors || [];
816 return zalgoGlobal;
817 }
818 var promise_ZalgoPromise = function() {
819 function ZalgoPromise(handler) {
820 var _this = this;
821 !function(instance, Constructor) {
822 if (!(instance instanceof ZalgoPromise)) throw new TypeError("Cannot call a class as a function");
823 }(this);
824 this.resolved = !1;
825 this.rejected = !1;
826 this.errorHandled = !1;
827 this.handlers = [];
828 if (handler) {
829 var _result = void 0, _error = void 0, resolved = !1, rejected = !1, isAsync = !1;
830 try {
831 handler(function(res) {
832 if (isAsync) _this.resolve(res); else {
833 resolved = !0;
834 _result = res;
835 }
836 }, function(err) {
837 if (isAsync) _this.reject(err); else {
838 rejected = !0;
839 _error = err;
840 }
841 });
842 } catch (err) {
843 this.reject(err);
844 return;
845 }
846 isAsync = !0;
847 resolved ? this.resolve(_result) : rejected && this.reject(_error);
848 }
849 }
850 ZalgoPromise.prototype.resolve = function(result) {
851 if (this.resolved || this.rejected) return this;
852 if (utils_isPromise(result)) throw new Error("Can not resolve promise with another promise");
853 this.resolved = !0;
854 this.value = result;
855 this.dispatch();
856 return this;
857 };
858 ZalgoPromise.prototype.reject = function(error) {
859 var _this2 = this;
860 if (this.resolved || this.rejected) return this;
861 if (utils_isPromise(error)) throw new Error("Can not reject promise with another promise");
862 if (!error) {
863 var _err = error && "function" == typeof error.toString ? error.toString() : Object.prototype.toString.call(error);
864 error = new Error("Expected reject to be called with Error, got " + _err);
865 }
866 this.rejected = !0;
867 this.error = error;
868 this.errorHandled || setTimeout(function() {
869 _this2.errorHandled || function(err, promise) {
870 if (-1 === getGlobal().dispatchedErrors.indexOf(err)) {
871 getGlobal().dispatchedErrors.push(err);
872 setTimeout(function() {
873 throw err;
874 }, 1);
875 for (var j = 0; j < getGlobal().possiblyUnhandledPromiseHandlers.length; j++) getGlobal().possiblyUnhandledPromiseHandlers[j](err, promise);
876 }
877 }(error, _this2);
878 }, 1);
879 this.dispatch();
880 return this;
881 };
882 ZalgoPromise.prototype.asyncReject = function(error) {
883 this.errorHandled = !0;
884 this.reject(error);
885 return this;
886 };
887 ZalgoPromise.prototype.dispatch = function() {
888 var _this3 = this, dispatching = this.dispatching, resolved = this.resolved, rejected = this.rejected, handlers = this.handlers;
889 if (!dispatching && (resolved || rejected)) {
890 this.dispatching = !0;
891 getGlobal().activeCount += 1;
892 for (var _loop = function(i) {
893 var _handlers$i = handlers[i], onSuccess = _handlers$i.onSuccess, onError = _handlers$i.onError, promise = _handlers$i.promise, result = void 0;
894 if (resolved) try {
895 result = onSuccess ? onSuccess(_this3.value) : _this3.value;
896 } catch (err) {
897 promise.reject(err);
898 return "continue";
899 } else if (rejected) {
900 if (!onError) {
901 promise.reject(_this3.error);
902 return "continue";
903 }
904 try {
905 result = onError(_this3.error);
906 } catch (err) {
907 promise.reject(err);
908 return "continue";
909 }
910 }
911 if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {
912 result.resolved ? promise.resolve(result.value) : promise.reject(result.error);
913 result.errorHandled = !0;
914 } else utils_isPromise(result) ? result instanceof ZalgoPromise && (result.resolved || result.rejected) ? result.resolved ? promise.resolve(result.value) : promise.reject(result.error) : result.then(function(res) {
915 promise.resolve(res);
916 }, function(err) {
917 promise.reject(err);
918 }) : promise.resolve(result);
919 }, i = 0; i < handlers.length; i++) _loop(i);
920 handlers.length = 0;
921 this.dispatching = !1;
922 getGlobal().activeCount -= 1;
923 0 === getGlobal().activeCount && ZalgoPromise.flushQueue();
924 }
925 };
926 ZalgoPromise.prototype.then = function(onSuccess, onError) {
927 if (onSuccess && "function" != typeof onSuccess && !onSuccess.call) throw new Error("Promise.then expected a function for success handler");
928 if (onError && "function" != typeof onError && !onError.call) throw new Error("Promise.then expected a function for error handler");
929 var promise = new ZalgoPromise();
930 this.handlers.push({
931 promise: promise,
932 onSuccess: onSuccess,
933 onError: onError
934 });
935 this.errorHandled = !0;
936 this.dispatch();
937 return promise;
938 };
939 ZalgoPromise.prototype.catch = function(onError) {
940 return this.then(void 0, onError);
941 };
942 ZalgoPromise.prototype.finally = function(onFinally) {
943 if (onFinally && "function" != typeof onFinally && !onFinally.call) throw new Error("Promise.finally expected a function");
944 return this.then(function(result) {
945 return ZalgoPromise.try(onFinally).then(function() {
946 return result;
947 });
948 }, function(err) {
949 return ZalgoPromise.try(onFinally).then(function() {
950 throw err;
951 });
952 });
953 };
954 ZalgoPromise.prototype.timeout = function(time, err) {
955 var _this4 = this;
956 if (this.resolved || this.rejected) return this;
957 var timeout = setTimeout(function() {
958 _this4.resolved || _this4.rejected || _this4.reject(err || new Error("Promise timed out after " + time + "ms"));
959 }, time);
960 return this.then(function(result) {
961 clearTimeout(timeout);
962 return result;
963 });
964 };
965 ZalgoPromise.prototype.toPromise = function() {
966 if ("undefined" == typeof Promise) throw new TypeError("Could not find Promise");
967 return Promise.resolve(this);
968 };
969 ZalgoPromise.resolve = function(value) {
970 return value instanceof ZalgoPromise ? value : utils_isPromise(value) ? new ZalgoPromise(function(resolve, reject) {
971 return value.then(resolve, reject);
972 }) : new ZalgoPromise().resolve(value);
973 };
974 ZalgoPromise.reject = function(error) {
975 return new ZalgoPromise().reject(error);
976 };
977 ZalgoPromise.asyncReject = function(error) {
978 return new ZalgoPromise().asyncReject(error);
979 };
980 ZalgoPromise.all = function(promises) {
981 var promise = new ZalgoPromise(), count = promises.length, results = [];
982 if (!count) {
983 promise.resolve(results);
984 return promise;
985 }
986 for (var _loop2 = function(i) {
987 var prom = promises[i];
988 if (prom instanceof ZalgoPromise) {
989 if (prom.resolved) {
990 results[i] = prom.value;
991 count -= 1;
992 return "continue";
993 }
994 } else if (!utils_isPromise(prom)) {
995 results[i] = prom;
996 count -= 1;
997 return "continue";
998 }
999 ZalgoPromise.resolve(prom).then(function(result) {
1000 results[i] = result;
1001 0 == (count -= 1) && promise.resolve(results);
1002 }, function(err) {
1003 promise.reject(err);
1004 });
1005 }, i = 0; i < promises.length; i++) _loop2(i);
1006 0 === count && promise.resolve(results);
1007 return promise;
1008 };
1009 ZalgoPromise.hash = function(promises) {
1010 var result = {};
1011 return ZalgoPromise.all(Object.keys(promises).map(function(key) {
1012 return ZalgoPromise.resolve(promises[key]).then(function(value) {
1013 result[key] = value;
1014 });
1015 })).then(function() {
1016 return result;
1017 });
1018 };
1019 ZalgoPromise.map = function(items, method) {
1020 return ZalgoPromise.all(items.map(method));
1021 };
1022 ZalgoPromise.onPossiblyUnhandledException = function(handler) {
1023 return function(handler) {
1024 getGlobal().possiblyUnhandledPromiseHandlers.push(handler);
1025 return {
1026 cancel: function() {
1027 getGlobal().possiblyUnhandledPromiseHandlers.splice(getGlobal().possiblyUnhandledPromiseHandlers.indexOf(handler), 1);
1028 }
1029 };
1030 }(handler);
1031 };
1032 ZalgoPromise.try = function(method, context, args) {
1033 if (method && "function" != typeof method && !method.call) throw new Error("Promise.try expected a function");
1034 var result = void 0;
1035 try {
1036 result = method.apply(context, args || []);
1037 } catch (err) {
1038 return ZalgoPromise.reject(err);
1039 }
1040 return ZalgoPromise.resolve(result);
1041 };
1042 ZalgoPromise.delay = function(_delay) {
1043 return new ZalgoPromise(function(resolve) {
1044 setTimeout(resolve, _delay);
1045 });
1046 };
1047 ZalgoPromise.isPromise = function(value) {
1048 return !!(value && value instanceof ZalgoPromise) || utils_isPromise(value);
1049 };
1050 ZalgoPromise.flush = function() {
1051 var promise = new ZalgoPromise();
1052 getGlobal().flushPromises.push(promise);
1053 0 === getGlobal().activeCount && ZalgoPromise.flushQueue();
1054 return promise;
1055 };
1056 ZalgoPromise.flushQueue = function() {
1057 var promisesToFlush = getGlobal().flushPromises;
1058 getGlobal().flushPromises = [];
1059 for (var _i2 = 0, _length2 = null == promisesToFlush ? 0 : promisesToFlush.length; _i2 < _length2; _i2++) promisesToFlush[_i2].resolve();
1060 };
1061 return ZalgoPromise;
1062 }(), global = window[constants_CONSTANTS.WINDOW_PROPS.POSTROBOT] = window[constants_CONSTANTS.WINDOW_PROPS.POSTROBOT] || {};
1063 global.registerSelf = function() {};
1064 var serialize__typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
1065 return typeof obj;
1066 } : function(obj) {
1067 return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
1068 };
1069 global.methods = global.methods || new weakmap_CrossDomainSafeWeakMap();
1070 var listenForMethods = once(function() {
1071 global.on(constants_CONSTANTS.POST_MESSAGE_NAMES.METHOD, {
1072 origin: constants_CONSTANTS.WILDCARD
1073 }, function(_ref) {
1074 var source = _ref.source, origin = _ref.origin, data = _ref.data, methods = global.methods.get(source);
1075 if (!methods) throw new Error("Could not find any methods this window has privileges to call");
1076 var meth = methods[data.id];
1077 if (!meth) throw new Error("Could not find method with id: " + data.id);
1078 if (!Object(src.matchDomain)(meth.domain, origin)) throw new Error("Method domain " + meth.domain + " does not match origin " + origin);
1079 return promise_ZalgoPromise.try(function() {
1080 return meth.method.apply({
1081 source: source,
1082 origin: origin,
1083 data: data
1084 }, data.args);
1085 }).then(function(result) {
1086 return {
1087 result: result,
1088 id: data.id,
1089 name: data.name
1090 };
1091 });
1092 });
1093 });
1094 function isSerialized(item, type) {
1095 return "object" === (void 0 === item ? "undefined" : serialize__typeof(item)) && null !== item && item.__type__ === type;
1096 }
1097 function serializeMethod(destination, domain, method, name) {
1098 var id = uniqueID(), methods = global.methods.get(destination);
1099 if (!methods) {
1100 methods = {};
1101 global.methods.set(destination, methods);
1102 }
1103 methods[id] = {
1104 domain: domain,
1105 method: method
1106 };
1107 return {
1108 __type__: constants_CONSTANTS.SERIALIZATION_TYPES.METHOD,
1109 __id__: id,
1110 __name__: name
1111 };
1112 }
1113 function deserializeMethod(source, origin, obj) {
1114 function wrapper() {
1115 var args = Array.prototype.slice.call(arguments);
1116 return global.send(source, constants_CONSTANTS.POST_MESSAGE_NAMES.METHOD, {
1117 id: obj.__id__,
1118 name: obj.__name__,
1119 args: args
1120 }, {
1121 domain: origin,
1122 timeout: -1
1123 }).then(function(_ref2) {
1124 return _ref2.data.result;
1125 }, function(err) {
1126 throw err;
1127 });
1128 }
1129 wrapper.__name__ = obj.__name__;
1130 wrapper.__xdomain__ = !0;
1131 wrapper.source = source;
1132 wrapper.origin = origin;
1133 return wrapper;
1134 }
1135 function deserializeZalgoPromise(source, origin, prom) {
1136 return new promise_ZalgoPromise(function(resolve, reject) {
1137 return deserializeMethod(source, origin, prom.__then__)(resolve, reject);
1138 });
1139 }
1140 global.readyPromises = global.readyPromises || new weakmap_CrossDomainSafeWeakMap();
1141 function sayHello(win) {
1142 return global.send(win, constants_CONSTANTS.POST_MESSAGE_NAMES.HELLO, {}, {
1143 domain: constants_CONSTANTS.WILDCARD,
1144 timeout: -1
1145 }).then(function(_ref2) {
1146 return {
1147 origin: _ref2.origin
1148 };
1149 });
1150 }
1151 var SEND_MESSAGE_STRATEGIES = {};
1152 SEND_MESSAGE_STRATEGIES[constants_CONSTANTS.SEND_STRATEGIES.POST_MESSAGE] = function(win, serializedMessage, domain) {
1153 (Array.isArray(domain) ? domain : "string" == typeof domain ? [ domain ] : [ constants_CONSTANTS.WILDCARD ]).map(function(dom) {
1154 if (0 === dom.indexOf(constants_CONSTANTS.MOCK_PROTOCOL)) {
1155 if (window.location.protocol === constants_CONSTANTS.FILE_PROTOCOL) return constants_CONSTANTS.WILDCARD;
1156 if (!Object(src.isActuallySameDomain)(win)) throw new Error("Attempting to send messsage to mock domain " + dom + ", but window is actually cross-domain");
1157 return Object(src.getActualDomain)(win);
1158 }
1159 return 0 === dom.indexOf(constants_CONSTANTS.FILE_PROTOCOL) ? constants_CONSTANTS.WILDCARD : dom;
1160 }).forEach(function(dom) {
1161 return win.postMessage(serializedMessage, dom);
1162 });
1163 };
1164 var _extends = Object.assign || function(target) {
1165 for (var i = 1; i < arguments.length; i++) {
1166 var source = arguments[i];
1167 for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
1168 }
1169 return target;
1170 };
1171 function sendMessage(win, message, domain) {
1172 return promise_ZalgoPromise.try(function() {
1173 var _jsonStringify;
1174 message = function(win, message) {
1175 var options = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, id = uniqueID(), type = Object(src.isPopup)() ? constants_CONSTANTS.WINDOW_TYPES.POPUP : Object(src.isIframe)() ? constants_CONSTANTS.WINDOW_TYPES.IFRAME : constants_CONSTANTS.WINDOW_TYPES.FULLPAGE, sourceDomain = Object(src.getDomain)(window);
1176 return _extends({}, message, options, {
1177 sourceDomain: sourceDomain,
1178 id: message.id || id,
1179 windowType: type
1180 });
1181 }(win, message, {
1182 data: function(destination, domain, obj) {
1183 return replaceObject({
1184 obj: message.data
1185 }, function(item, key) {
1186 return "function" == typeof item ? serializeMethod(destination, domain, item, key.toString()) : item instanceof Error ? (err = item,
1187 {
1188 __type__: constants_CONSTANTS.SERIALIZATION_TYPES.ERROR,
1189 __message__: stringifyError(err),
1190 __code__: err.code
1191 }) : window.Promise && item instanceof window.Promise ? function(destination, domain, promise, name) {
1192 return {
1193 __type__: constants_CONSTANTS.SERIALIZATION_TYPES.PROMISE,
1194 __then__: serializeMethod(destination, domain, function(resolve, reject) {
1195 return promise.then(resolve, reject);
1196 }, name + ".then")
1197 };
1198 }(destination, domain, item, key.toString()) : promise_ZalgoPromise.isPromise(item) ? function(destination, domain, promise, name) {
1199 return {
1200 __type__: constants_CONSTANTS.SERIALIZATION_TYPES.ZALGO_PROMISE,
1201 __then__: serializeMethod(destination, domain, function(resolve, reject) {
1202 return promise.then(resolve, reject);
1203 }, name + ".then")
1204 };
1205 }(destination, domain, item, key.toString()) : isRegex(item) ? (regex = item, {
1206 __type__: constants_CONSTANTS.SERIALIZATION_TYPES.REGEX,
1207 __source__: regex.source
1208 }) : void 0;
1209 var err, regex;
1210 }).obj;
1211 }(win, domain),
1212 domain: domain
1213 });
1214 if (win === window && !CONFIG.ALLOW_SAME_ORIGIN) throw new Error("Attemping to send message to self");
1215 if (Object(src.isWindowClosed)(win)) throw new Error("Window is closed");
1216 var messages = [], serializedMessage = function(obj, replacer, indent) {
1217 var objectToJSON = void 0, arrayToJSON = void 0;
1218 try {
1219 if ("{}" !== JSON.stringify({})) {
1220 objectToJSON = Object.prototype.toJSON;
1221 delete Object.prototype.toJSON;
1222 }
1223 if ("{}" !== JSON.stringify({})) throw new Error("Can not correctly serialize JSON objects");
1224 if ("[]" !== JSON.stringify([])) {
1225 arrayToJSON = Array.prototype.toJSON;
1226 delete Array.prototype.toJSON;
1227 }
1228 if ("[]" !== JSON.stringify([])) throw new Error("Can not correctly serialize JSON objects");
1229 } catch (err) {
1230 throw new Error("Can not repair JSON.stringify: " + err.message);
1231 }
1232 var result = JSON.stringify.call(this, obj, null, 2);
1233 try {
1234 objectToJSON && (Object.prototype.toJSON = objectToJSON);
1235 arrayToJSON && (Array.prototype.toJSON = arrayToJSON);
1236 } catch (err) {
1237 throw new Error("Can not repair JSON.stringify: " + err.message);
1238 }
1239 return result;
1240 }(((_jsonStringify = {})[constants_CONSTANTS.WINDOW_PROPS.POSTROBOT] = message,
1241 _jsonStringify));
1242 return promise_ZalgoPromise.map(Object.keys(SEND_MESSAGE_STRATEGIES), function(strategyName) {
1243 return promise_ZalgoPromise.try(function() {
1244 if (!CONFIG.ALLOWED_POST_MESSAGE_METHODS[strategyName]) throw new Error("Strategy disallowed: " + strategyName);
1245 return SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain);
1246 }).then(function() {
1247 messages.push(strategyName + ": success");
1248 return !0;
1249 }, function(err) {
1250 messages.push(strategyName + ": " + stringifyError(err) + "\n");
1251 return !1;
1252 });
1253 }).then(function(results) {
1254 var success = results.some(Boolean), status = message.type + " " + message.name + " " + (success ? "success" : "error") + ":\n - " + messages.join("\n - ") + "\n";
1255 if (!success) throw new Error(status);
1256 });
1257 });
1258 }
1259 global.responseListeners = global.responseListeners || {};
1260 global.requestListeners = global.requestListeners || {};
1261 global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new function() {}();
1262 global.erroredResponseListeners = global.erroredResponseListeners || {};
1263 var _RECEIVE_MESSAGE_TYPE, __DOMAIN_REGEX__ = "__domain_regex__";
1264 function getResponseListener(hash) {
1265 return global.responseListeners[hash];
1266 }
1267 function deleteResponseListener(hash) {
1268 delete global.responseListeners[hash];
1269 }
1270 function isResponseListenerErrored(hash) {
1271 return Boolean(global.erroredResponseListeners[hash]);
1272 }
1273 function getRequestListener(_ref) {
1274 var name = _ref.name, win = _ref.win, domain = _ref.domain;
1275 win === constants_CONSTANTS.WILDCARD && (win = null);
1276 domain === constants_CONSTANTS.WILDCARD && (domain = null);
1277 if (!name) throw new Error("Name required to get request listener");
1278 var nameListeners = global.requestListeners[name];
1279 if (nameListeners) for (var _i2 = 0, _ref3 = [ win, global.WINDOW_WILDCARD ], _length2 = null == _ref3 ? 0 : _ref3.length; _i2 < _length2; _i2++) {
1280 var winQualifier = _ref3[_i2], winListeners = winQualifier && nameListeners.get(winQualifier);
1281 if (winListeners) {
1282 if (domain && "string" == typeof domain) {
1283 if (winListeners[domain]) return winListeners[domain];
1284 if (winListeners[__DOMAIN_REGEX__]) for (var _i4 = 0, _winListeners$__DOMAI2 = winListeners[__DOMAIN_REGEX__], _length4 = null == _winListeners$__DOMAI2 ? 0 : _winListeners$__DOMAI2.length; _i4 < _length4; _i4++) {
1285 var _ref5 = _winListeners$__DOMAI2[_i4], regex = _ref5.regex, listener = _ref5.listener;
1286 if (Object(src.matchDomain)(regex, domain)) return listener;
1287 }
1288 }
1289 if (winListeners[constants_CONSTANTS.WILDCARD]) return winListeners[constants_CONSTANTS.WILDCARD];
1290 }
1291 }
1292 }
1293 var types__extends = Object.assign || function(target) {
1294 for (var i = 1; i < arguments.length; i++) {
1295 var source = arguments[i];
1296 for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
1297 }
1298 return target;
1299 }, RECEIVE_MESSAGE_TYPES = ((_RECEIVE_MESSAGE_TYPE = {})[constants_CONSTANTS.POST_MESSAGE_TYPE.ACK] = function(source, origin, message) {
1300 if (!isResponseListenerErrored(message.hash)) {
1301 var options = getResponseListener(message.hash);
1302 if (!options) throw new Error("No handler found for post message ack for message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname);
1303 if (!Object(src.matchDomain)(options.domain, origin)) throw new Error("Ack origin " + origin + " does not match domain " + options.domain.toString());
1304 options.ack = !0;
1305 }
1306 }, _RECEIVE_MESSAGE_TYPE[constants_CONSTANTS.POST_MESSAGE_TYPE.REQUEST] = function(source, origin, message) {
1307 var options = getRequestListener({
1308 name: message.name,
1309 win: source,
1310 domain: origin
1311 });
1312 function respond(data) {
1313 return message.fireAndForget || Object(src.isWindowClosed)(source) ? promise_ZalgoPromise.resolve() : sendMessage(source, types__extends({
1314 target: message.originalSource,
1315 hash: message.hash,
1316 name: message.name
1317 }, data), origin);
1318 }
1319 return promise_ZalgoPromise.all([ respond({
1320 type: constants_CONSTANTS.POST_MESSAGE_TYPE.ACK
1321 }), promise_ZalgoPromise.try(function() {
1322 if (!options) throw new Error("No handler found for post message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname);
1323 if (!Object(src.matchDomain)(options.domain, origin)) throw new Error("Request origin " + origin + " does not match domain " + options.domain.toString());
1324 var data = message.data;
1325 return options.handler({
1326 source: source,
1327 origin: origin,
1328 data: data
1329 });
1330 }).then(function(data) {
1331 return respond({
1332 type: constants_CONSTANTS.POST_MESSAGE_TYPE.RESPONSE,
1333 ack: constants_CONSTANTS.POST_MESSAGE_ACK.SUCCESS,
1334 data: data
1335 });
1336 }, function(err) {
1337 var error = stringifyError(err).replace(/^Error: /, ""), code = err.code;
1338 return respond({
1339 type: constants_CONSTANTS.POST_MESSAGE_TYPE.RESPONSE,
1340 ack: constants_CONSTANTS.POST_MESSAGE_ACK.ERROR,
1341 error: error,
1342 code: code
1343 });
1344 }) ]).then(util_noop).catch(function(err) {
1345 if (options && options.handleError) return options.handleError(err);
1346 throw err;
1347 });
1348 }, _RECEIVE_MESSAGE_TYPE[constants_CONSTANTS.POST_MESSAGE_TYPE.RESPONSE] = function(source, origin, message) {
1349 if (!isResponseListenerErrored(message.hash)) {
1350 var options = getResponseListener(message.hash);
1351 if (!options) throw new Error("No handler found for post message response for message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname);
1352 if (!Object(src.matchDomain)(options.domain, origin)) throw new Error("Response origin " + origin + " does not match domain " + Object(src.stringifyDomainPattern)(options.domain));
1353 deleteResponseListener(message.hash);
1354 if (message.ack === constants_CONSTANTS.POST_MESSAGE_ACK.ERROR) {
1355 var err = new Error(message.error);
1356 message.code && (err.code = message.code);
1357 return options.respond(err, null);
1358 }
1359 if (message.ack === constants_CONSTANTS.POST_MESSAGE_ACK.SUCCESS) {
1360 var data = message.data || message.response;
1361 return options.respond(null, {
1362 source: source,
1363 origin: origin,
1364 data: data
1365 });
1366 }
1367 }
1368 }, _RECEIVE_MESSAGE_TYPE), receive__typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
1369 return typeof obj;
1370 } : function(obj) {
1371 return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
1372 };
1373 global.receivedMessages = global.receivedMessages || [];
1374 function receiveMessage(event) {
1375 if (!window || window.closed) throw new Error("Message recieved in closed window");
1376 try {
1377 if (!event.source) return;
1378 } catch (err) {
1379 return;
1380 }
1381 var source = event.source, origin = event.origin, message = function(message) {
1382 var item, parsedMessage = void 0;
1383 try {
1384 parsedMessage = (item = message, JSON.parse(item));
1385 } catch (err) {
1386 return;
1387 }
1388 if (parsedMessage && "object" === (void 0 === parsedMessage ? "undefined" : receive__typeof(parsedMessage)) && null !== parsedMessage && (parsedMessage = parsedMessage[constants_CONSTANTS.WINDOW_PROPS.POSTROBOT]) && "object" === (void 0 === parsedMessage ? "undefined" : receive__typeof(parsedMessage)) && null !== parsedMessage && parsedMessage.type && "string" == typeof parsedMessage.type && RECEIVE_MESSAGE_TYPES[parsedMessage.type]) return parsedMessage;
1389 }(event.data);
1390 if (message) {
1391 if (!message.sourceDomain || "string" != typeof message.sourceDomain) throw new Error("Expected message to have sourceDomain");
1392 0 !== message.sourceDomain.indexOf(constants_CONSTANTS.MOCK_PROTOCOL) && 0 !== message.sourceDomain.indexOf(constants_CONSTANTS.FILE_PROTOCOL) || (origin = message.sourceDomain);
1393 if (-1 === global.receivedMessages.indexOf(message.id)) {
1394 global.receivedMessages.push(message.id);
1395 if (!Object(src.isWindowClosed)(source) || message.fireAndForget) {
1396 message.data && (message.data = function(source, origin, obj) {
1397 return replaceObject({
1398 obj: message.data
1399 }, function(item) {
1400 if ("object" === (void 0 === item ? "undefined" : serialize__typeof(item)) && null !== item) return isSerialized(item, constants_CONSTANTS.SERIALIZATION_TYPES.METHOD) ? deserializeMethod(source, origin, item) : isSerialized(item, constants_CONSTANTS.SERIALIZATION_TYPES.ERROR) ? function(source, origin, obj) {
1401 var err = new Error(obj.__message__);
1402 obj.__code__ && (err.code = obj.__code__);
1403 return err;
1404 }(0, 0, item) : isSerialized(item, constants_CONSTANTS.SERIALIZATION_TYPES.PROMISE) ? function(source, origin, prom) {
1405 return window.Promise ? new window.Promise(function(resolve, reject) {
1406 return deserializeMethod(source, origin, prom.__then__)(resolve, reject);
1407 }) : deserializeZalgoPromise(source, origin, prom);
1408 }(source, origin, item) : isSerialized(item, constants_CONSTANTS.SERIALIZATION_TYPES.ZALGO_PROMISE) ? deserializeZalgoPromise(source, origin, item) : isSerialized(item, constants_CONSTANTS.SERIALIZATION_TYPES.REGEX) ? function(source, origin, item) {
1409 return new RegExp(item.__source__);
1410 }(0, 0, item) : void 0;
1411 }).obj;
1412 }(source, origin));
1413 RECEIVE_MESSAGE_TYPES[message.type](source, origin, message);
1414 }
1415 }
1416 }
1417 }
1418 function messageListener(event) {
1419 try {
1420 event.source;
1421 } catch (err) {
1422 return;
1423 }
1424 receiveMessage({
1425 source: event.source || event.sourceElement,
1426 origin: event.origin || event.originalEvent && event.originalEvent.origin,
1427 data: event.data
1428 });
1429 }
1430 global.receiveMessage = receiveMessage;
1431 global.requestPromises = global.requestPromises || new weakmap_CrossDomainSafeWeakMap();
1432 function request(options) {
1433 return promise_ZalgoPromise.try(function() {
1434 if (!options.name) throw new Error("Expected options.name");
1435 var name = options.name, targetWindow = void 0, domain = void 0;
1436 if ("string" == typeof options.window) {
1437 var el = document.getElementById(options.window);
1438 if (!el) throw new Error("Expected options.window " + Object.prototype.toString.call(options.window) + " to be a valid element id");
1439 if ("iframe" !== el.tagName.toLowerCase()) throw new Error("Expected options.window " + Object.prototype.toString.call(options.window) + " to be an iframe");
1440 if (!el.contentWindow) throw new Error("Iframe must have contentWindow. Make sure it has a src attribute and is in the DOM.");
1441 targetWindow = el.contentWindow;
1442 } else if (options.window instanceof HTMLIFrameElement) {
1443 if ("iframe" !== options.window.tagName.toLowerCase()) throw new Error("Expected options.window " + Object.prototype.toString.call(options.window) + " to be an iframe");
1444 if (options.window && !options.window.contentWindow) throw new Error("Iframe must have contentWindow. Make sure it has a src attribute and is in the DOM.");
1445 options.window && options.window.contentWindow && (targetWindow = options.window.contentWindow);
1446 } else targetWindow = options.window;
1447 if (!targetWindow) throw new Error("Expected options.window to be a window object, iframe, or iframe element id.");
1448 var win = targetWindow;
1449 domain = options.domain || constants_CONSTANTS.WILDCARD;
1450 var hash = options.name + "_" + uniqueID();
1451 if (Object(src.isWindowClosed)(win)) throw new Error("Target window is closed");
1452 var hasResult = !1, requestPromises = global.requestPromises.get(win);
1453 if (!requestPromises) {
1454 requestPromises = [];
1455 global.requestPromises.set(win, requestPromises);
1456 }
1457 var requestPromise = promise_ZalgoPromise.try(function() {
1458 if (Object(src.isAncestor)(window, win)) return function(win) {
1459 var timeout = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 5e3, name = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : "Window", promise = global.readyPromises.get(win);
1460 if (promise) return promise;
1461 promise = new promise_ZalgoPromise();
1462 global.readyPromises.set(win, promise);
1463 -1 !== timeout && setTimeout(function() {
1464 return promise.reject(new Error(name + " did not load after " + timeout + "ms"));
1465 }, timeout);
1466 return promise;
1467 }(win, options.timeout || CONFIG.CHILD_WINDOW_TIMEOUT);
1468 }).then(function() {
1469 var origin = (arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}).origin;
1470 if (isRegex(domain) && !origin) return sayHello(win);
1471 }).then(function() {
1472 var origin = (arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}).origin;
1473 if (isRegex(domain)) {
1474 if (!Object(src.matchDomain)(domain, origin)) throw new Error("Remote window domain " + origin + " does not match regex: " + domain.toString());
1475 domain = origin;
1476 }
1477 if ("string" != typeof domain && !Array.isArray(domain)) throw new TypeError("Expected domain to be a string or array");
1478 var actualDomain = domain;
1479 return new promise_ZalgoPromise(function(resolve, reject) {
1480 var responseListener = void 0;
1481 options.fireAndForget || function(hash, listener) {
1482 global.responseListeners[hash] = listener;
1483 }(hash, responseListener = {
1484 name: name,
1485 window: win,
1486 domain: actualDomain,
1487 respond: function(err, result) {
1488 if (!err) {
1489 hasResult = !0;
1490 requestPromises.splice(requestPromises.indexOf(requestPromise, 1));
1491 }
1492 err ? reject(err) : resolve(result);
1493 }
1494 });
1495 sendMessage(win, {
1496 type: constants_CONSTANTS.POST_MESSAGE_TYPE.REQUEST,
1497 hash: hash,
1498 name: name,
1499 data: options.data,
1500 fireAndForget: options.fireAndForget
1501 }, actualDomain).catch(reject);
1502 if (options.fireAndForget) return resolve();
1503 var ackTimeout = CONFIG.ACK_TIMEOUT, resTimeout = options.timeout || CONFIG.RES_TIMEOUT, cycleTime = 100;
1504 setTimeout(function cycle() {
1505 if (!hasResult) {
1506 if (Object(src.isWindowClosed)(win)) return responseListener.ack ? reject(new Error("Window closed for " + name + " before response")) : reject(new Error("Window closed for " + name + " before ack"));
1507 ackTimeout = Math.max(ackTimeout - cycleTime, 0);
1508 -1 !== resTimeout && (resTimeout = Math.max(resTimeout - cycleTime, 0));
1509 if (responseListener.ack) {
1510 if (-1 === resTimeout) return;
1511 cycleTime = Math.min(resTimeout, 2e3);
1512 } else {
1513 if (0 === ackTimeout) return reject(new Error("No ack for postMessage " + name + " in " + Object(src.getDomain)() + " in " + CONFIG.ACK_TIMEOUT + "ms"));
1514 if (0 === resTimeout) return reject(new Error("No response for postMessage " + name + " in " + Object(src.getDomain)() + " in " + (options.timeout || CONFIG.RES_TIMEOUT) + "ms"));
1515 }
1516 setTimeout(cycle, cycleTime);
1517 }
1518 }, cycleTime);
1519 });
1520 });
1521 requestPromise.catch(function() {
1522 !function(hash) {
1523 global.erroredResponseListeners[hash] = !0;
1524 }(hash);
1525 deleteResponseListener(hash);
1526 });
1527 requestPromises.push(requestPromise);
1528 return requestPromise;
1529 });
1530 }
1531 function _send(window, name, data, options) {
1532 (options = options || {}).window = window;
1533 options.name = name;
1534 options.data = data;
1535 return request(options);
1536 }
1537 function sendToParent(name, data, options) {
1538 var win = Object(src.getAncestor)();
1539 return win ? _send(win, name, data, options) : new promise_ZalgoPromise(function(resolve, reject) {
1540 return reject(new Error("Window does not have a parent"));
1541 });
1542 }
1543 function client() {
1544 var options = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
1545 if (!options.window) throw new Error("Expected options.window");
1546 var win = options.window;
1547 return {
1548 send: function(name, data) {
1549 return _send(win, name, data, options);
1550 }
1551 };
1552 }
1553 global.send = _send;
1554 var server__typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
1555 return typeof obj;
1556 } : function(obj) {
1557 return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
1558 };
1559 function listen(options) {
1560 if (!options.name) throw new Error("Expected options.name");
1561 if (!options.handler) throw new Error("Expected options.handler");
1562 var name = options.name, win = options.window, domain = options.domain, listenerOptions = {
1563 handler: options.handler,
1564 handleError: options.errorHandler || function(err) {
1565 throw err;
1566 },
1567 window: win,
1568 domain: domain || constants_CONSTANTS.WILDCARD,
1569 name: name
1570 }, requestListener = function addRequestListener(_ref6, listener) {
1571 var name = _ref6.name, win = _ref6.win, domain = _ref6.domain;
1572 if (!name || "string" != typeof name) throw new Error("Name required to add request listener");
1573 if (Array.isArray(win)) {
1574 for (var listenersCollection = [], _i6 = 0, _win2 = win, _length6 = null == _win2 ? 0 : _win2.length; _i6 < _length6; _i6++) {
1575 var item = _win2[_i6];
1576 listenersCollection.push(addRequestListener({
1577 name: name,
1578 domain: domain,
1579 win: item
1580 }, listener));
1581 }
1582 return {
1583 cancel: function() {
1584 for (var _i8 = 0, _length8 = null == listenersCollection ? 0 : listenersCollection.length; _i8 < _length8; _i8++) listenersCollection[_i8].cancel();
1585 }
1586 };
1587 }
1588 if (Array.isArray(domain)) {
1589 for (var _listenersCollection = [], _i10 = 0, _domain2 = domain, _length10 = null == _domain2 ? 0 : _domain2.length; _i10 < _length10; _i10++) {
1590 var _item = _domain2[_i10];
1591 _listenersCollection.push(addRequestListener({
1592 name: name,
1593 win: win,
1594 domain: _item
1595 }, listener));
1596 }
1597 return {
1598 cancel: function() {
1599 for (var _i12 = 0, _length12 = null == _listenersCollection ? 0 : _listenersCollection.length; _i12 < _length12; _i12++) _listenersCollection[_i12].cancel();
1600 }
1601 };
1602 }
1603 var existingListener = getRequestListener({
1604 name: name,
1605 win: win,
1606 domain: domain
1607 });
1608 win && win !== constants_CONSTANTS.WILDCARD || (win = global.WINDOW_WILDCARD);
1609 domain = domain || constants_CONSTANTS.WILDCARD;
1610 if (existingListener) throw win && domain ? new Error("Request listener already exists for " + name + " on domain " + domain.toString() + " for " + (win === global.WINDOW_WILDCARD ? "wildcard" : "specified") + " window") : win ? new Error("Request listener already exists for " + name + " for " + (win === global.WINDOW_WILDCARD ? "wildcard" : "specified") + " window") : domain ? new Error("Request listener already exists for " + name + " on domain " + domain.toString()) : new Error("Request listener already exists for " + name);
1611 var requestListeners = global.requestListeners, nameListeners = requestListeners[name];
1612 if (!nameListeners) {
1613 nameListeners = new weakmap_CrossDomainSafeWeakMap();
1614 requestListeners[name] = nameListeners;
1615 }
1616 var winListeners = nameListeners.get(win);
1617 if (!winListeners) {
1618 winListeners = {};
1619 nameListeners.set(win, winListeners);
1620 }
1621 var strDomain = domain.toString(), regexListeners = winListeners[__DOMAIN_REGEX__], regexListener = void 0;
1622 if (isRegex(domain)) {
1623 if (!regexListeners) {
1624 regexListeners = [];
1625 winListeners[__DOMAIN_REGEX__] = regexListeners;
1626 }
1627 regexListener = {
1628 regex: domain,
1629 listener: listener
1630 };
1631 regexListeners.push(regexListener);
1632 } else winListeners[strDomain] = listener;
1633 return {
1634 cancel: function() {
1635 if (winListeners) {
1636 delete winListeners[strDomain];
1637 win && 0 === Object.keys(winListeners).length && nameListeners.delete(win);
1638 regexListener && regexListeners.splice(regexListeners.indexOf(regexListener, 1));
1639 }
1640 }
1641 };
1642 }({
1643 name: name,
1644 win: win,
1645 domain: domain
1646 }, listenerOptions);
1647 if (options.once) {
1648 var _handler = listenerOptions.handler;
1649 listenerOptions.handler = once(function() {
1650 requestListener.cancel();
1651 return _handler.apply(this, arguments);
1652 });
1653 }
1654 if (listenerOptions.window && options.errorOnClose) var interval = function(method, time) {
1655 var timeout = void 0;
1656 timeout = setTimeout(function runInterval() {
1657 timeout = setTimeout(runInterval, 50);
1658 (function() {
1659 if (win && "object" === (void 0 === win ? "undefined" : server__typeof(win)) && Object(src.isWindowClosed)(win)) {
1660 interval.cancel();
1661 listenerOptions.handleError(new Error("Post message target window is closed"));
1662 }
1663 }).call();
1664 }, 50);
1665 return {
1666 cancel: function() {
1667 clearTimeout(timeout);
1668 }
1669 };
1670 }();
1671 return {
1672 cancel: function() {
1673 requestListener.cancel();
1674 }
1675 };
1676 }
1677 function _on(name, options, handler) {
1678 if ("function" == typeof options) {
1679 handler = options;
1680 options = {};
1681 }
1682 (options = options || {}).name = name;
1683 options.handler = handler || options.handler;
1684 return listen(options);
1685 }
1686 function server_once(name) {
1687 var options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, handler = arguments[2];
1688 if ("function" == typeof options) {
1689 handler = options;
1690 options = {};
1691 }
1692 options = options || {};
1693 handler = handler || options.handler;
1694 var errorHandler = options.errorHandler, promise = new promise_ZalgoPromise(function(resolve, reject) {
1695 (options = options || {}).name = name;
1696 options.once = !0;
1697 options.handler = function(event) {
1698 resolve(event);
1699 if (handler) return handler(event);
1700 };
1701 options.errorHandler = function(err) {
1702 reject(err);
1703 if (errorHandler) return errorHandler(err);
1704 };
1705 }), onceListener = listen(options);
1706 promise.cancel = onceListener.cancel;
1707 return promise;
1708 }
1709 function server_listener() {
1710 var options = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
1711 return {
1712 on: function(name, handler) {
1713 return _on(name, options, handler);
1714 }
1715 };
1716 }
1717 global.on = _on;
1718 function disable() {
1719 delete window[constants_CONSTANTS.WINDOW_PROPS.POSTROBOT];
1720 window.removeEventListener("message", messageListener);
1721 }
1722 var public_parent = Object(src.getAncestor)();
1723 function cleanUpWindow(win) {
1724 var requestPromises = global.requestPromises.get(win);
1725 if (requestPromises) for (var _i2 = 0, _length2 = null == requestPromises ? 0 : requestPromises.length; _i2 < _length2; _i2++) requestPromises[_i2].reject(new Error("No response from window - cleaned up"));
1726 global.popupWindowsByWin && global.popupWindowsByWin.delete(win);
1727 global.remoteWindows && global.remoteWindows.delete(win);
1728 global.requestPromises.delete(win);
1729 global.methods.delete(win);
1730 global.readyPromises.delete(win);
1731 }
1732 var bridge = null;
1733 function init() {
1734 if (!global.initialized) {
1735 handler = messageListener, (obj = window).addEventListener ? obj.addEventListener("message", handler) : obj.attachEvent("onmessage", handler);
1736 !function() {
1737 handler = function(_ref3) {
1738 var source = _ref3.source, origin = _ref3.origin, promise = global.readyPromises.get(source) || new promise_ZalgoPromise();
1739 promise.resolve({
1740 origin: origin
1741 });
1742 global.readyPromises.set(source, promise);
1743 }, global.on(constants_CONSTANTS.POST_MESSAGE_NAMES.HELLO, {
1744 domain: constants_CONSTANTS.WILDCARD
1745 }, function(_ref) {
1746 var source = _ref.source, origin = _ref.origin;
1747 return handler({
1748 source: source,
1749 origin: origin
1750 });
1751 });
1752 var handler, parent = Object(src.getAncestor)();
1753 parent && sayHello(parent).catch(util_noop);
1754 }();
1755 listenForMethods({
1756 on: _on,
1757 send: _send
1758 });
1759 }
1760 var obj, handler;
1761 global.initialized = !0;
1762 }
1763 init();
1764 __webpack_require__.d(__webpack_exports__, "cleanUpWindow", function() {
1765 return cleanUpWindow;
1766 });
1767 __webpack_require__.d(__webpack_exports__, "Promise", function() {
1768 return promise_ZalgoPromise;
1769 });
1770 __webpack_require__.d(__webpack_exports__, "bridge", function() {
1771 return bridge;
1772 });
1773 __webpack_require__.d(__webpack_exports__, "init", function() {
1774 return init;
1775 });
1776 __webpack_require__.d(__webpack_exports__, "parent", function() {
1777 return public_parent;
1778 });
1779 __webpack_require__.d(__webpack_exports__, "send", function() {
1780 return _send;
1781 });
1782 __webpack_require__.d(__webpack_exports__, "request", function() {
1783 return request;
1784 });
1785 __webpack_require__.d(__webpack_exports__, "sendToParent", function() {
1786 return sendToParent;
1787 });
1788 __webpack_require__.d(__webpack_exports__, "client", function() {
1789 return client;
1790 });
1791 __webpack_require__.d(__webpack_exports__, "on", function() {
1792 return _on;
1793 });
1794 __webpack_require__.d(__webpack_exports__, "listen", function() {
1795 return listen;
1796 });
1797 __webpack_require__.d(__webpack_exports__, "once", function() {
1798 return server_once;
1799 });
1800 __webpack_require__.d(__webpack_exports__, "listener", function() {
1801 return server_listener;
1802 });
1803 __webpack_require__.d(__webpack_exports__, "CONFIG", function() {
1804 return CONFIG;
1805 });
1806 __webpack_require__.d(__webpack_exports__, "CONSTANTS", function() {
1807 return constants_CONSTANTS;
1808 });
1809 __webpack_require__.d(__webpack_exports__, "disable", function() {
1810 return disable;
1811 });
1812 __webpack_exports__.default = src_interface_namespaceObject;
1813 }
1814 });
1815 });
1816
1817 });
1818
1819 unwrapExports(postRobot);
1820 var postRobot_1 = postRobot.postRobot;
1821
1822 var postRobot$2 = createCommonjsModule(function (module) {
1823 /* @flow */
1824
1825 // eslint-disable-next-line import/no-commonjs
1826 module.exports = postRobot;
1827
1828 // eslint-disable-next-line import/no-commonjs
1829 module.exports.default = module.exports;
1830 });
1831
1832 var logger_browser = createCommonjsModule(function (module, exports) {
1833 !function(e,n){module.exports=n();}(commonjsGlobal,function(){var e=1e3,n=60*e,t=60*n,r=24*t,s=7*r,o=365.25*r,a=function(a,i){i=i||{};var u=typeof a;if("string"===u&&a.length>0)return function(a){if((a=String(a)).length>100)return;var c=/^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!c)return;var i=parseFloat(c[1]);switch((c[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*o;case"weeks":case"week":case"w":return i*s;case"days":case"day":case"d":return i*r;case"hours":case"hour":case"hrs":case"hr":case"h":return i*t;case"minutes":case"minute":case"mins":case"min":case"m":return i*n;case"seconds":case"second":case"secs":case"sec":case"s":return i*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:return}}(a);if("number"===u&&!1===isNaN(a))return i.long?function(s){var o=Math.abs(s);if(o>=r)return c(s,o,r,"day");if(o>=t)return c(s,o,t,"hour");if(o>=n)return c(s,o,n,"minute");if(o>=e)return c(s,o,e,"second");return s+" ms"}(a):function(s){var o=Math.abs(s);if(o>=r)return Math.round(s/r)+"d";if(o>=t)return Math.round(s/t)+"h";if(o>=n)return Math.round(s/n)+"m";if(o>=e)return Math.round(s/e)+"s";return s+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))};function c(e,n,t,r){var s=n>=1.5*t;return Math.round(e/t)+" "+r+(s?"s":"")}var i,u=function(e){function n(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]}function t(e){let o;function a(...e){if(!a.enabled)return;const n=a,r=Number(new Date),s=r-(o||r);n.diff=s,n.prev=o,n.curr=r,o=r,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let c=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,s)=>{if("%%"===r)return r;c++;const o=t.formatters[s];if("function"==typeof o){const t=e[c];r=o.call(n,t),e.splice(c,1),c--;}return r}),t.formatArgs.call(n,e),(n.log||t.log).apply(n,e);}return a.namespace=e,a.enabled=t.enabled(e),a.useColors=t.useColors(),a.color=n(e),a.destroy=r,a.extend=s,"function"==typeof t.init&&t.init(a),t.instances.push(a),a}function r(){const e=t.instances.indexOf(this);return -1!==e&&(t.instances.splice(e,1),!0)}function s(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(o),...t.skips.map(o).map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),s=r.length;for(n=0;n<s;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")));for(n=0;n<t.instances.length;n++){const e=t.instances[n];e.enabled=t.enabled(e.namespace);}},t.enabled=function(e){if("*"===e[e.length-1])return !0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return !1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return !0;return !1},t.humanize=a,Object.keys(e).forEach(n=>{t[n]=e[n];}),t.instances=[],t.names=[],t.skips=[],t.formatters={},t.selectColor=n,t.enable(t.load()),t},C=(function(e,n){n.log=function(...e){return "object"==typeof console&&console.log&&console.log(...e)},n.formatArgs=function(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const t="color: "+this.color;n.splice(1,0,t,"color: inherit");let r=0,s=0;n[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(r++,"%c"===e&&(s=r));}),n.splice(s,0,t);},n.save=function(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug");}catch(e){}},n.load=function(){let e;try{e=n.storage.getItem("debug");}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},n.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return !0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return !1;return "undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},n.storage=function(){try{return localStorage}catch(e){}}(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.exports=u(n);const{formatters:t}=e.exports;t.j=function(e){try{return JSON.stringify(e)}catch(e){return "[UnexpectedJSONParseError]: "+e.message}};}(i={exports:{}},i.exports),i.exports);C.log,C.formatArgs,C.save,C.load,C.useColors,C.storage,C.colors;return e=>C(`bearer:${e}`)});
1834 });
1835
1836 var logger = logger_browser('js');
1837
1838 function cleanQuery(params) {
1839 return Object.keys(params).reduce((acc, key) => {
1840 if (params[key]) {
1841 acc[key] = params[key];
1842 }
1843 return acc;
1844 }, {});
1845 }
1846 function formatQuery(params) {
1847 return Object.keys(cleanQuery(params))
1848 .reduce((acc, key) => {
1849 return [...acc, [key, params[key]].join('=')];
1850 }, [])
1851 .join('&');
1852 }
1853
1854 const logger$1 = logger.extend('Bearer');
1855 const prefix = 'bearer';
1856 const DEFAULT_OPTIONS = {
1857 secured: undefined,
1858 integrationHost: 'https://int.bearer.sh',
1859 domObserver: true,
1860 refreshDebounceDelay: 200
1861 };
1862 class Bearer {
1863 constructor(clientId, options = {}) {
1864 this.clientId = clientId;
1865 this.config = DEFAULT_OPTIONS;
1866 this.registeredIntegrations = {};
1867 // TODO: move to a dedicated file
1868 /**
1869 * `connect` lets you easily retrieve `auth-id` for an integration using OAuth authentication. Before using it, you'll need to generate a `setup-id` with the setup component of your integration
1870 * @argument {string} integration the identifier of the Integration you want to connect to ex: 12345-attach-github-pull-request
1871 * @argument {string} setupId Setup's identifier you received earlier, a Bearer reference containing all required information about auth mechanism
1872 * @argument {Object} options Optional parameters like authId if you already have one
1873 */
1874 this.connect = (integration, setupId, { authId } = {}) => {
1875 const query = formatQuery({
1876 setupId,
1877 authId,
1878 secured: this.config.secured,
1879 clientId: this.clientId
1880 });
1881 const AUTHORIZED_URL = `${this.config.integrationHost}/v2/auth/${integration}?${query}`;
1882 // TODO: get rid of post robot, too heqvy for our needs
1883 const promise = new Promise((resolve, reject) => {
1884 // TODO: use constants
1885 if (this.authorizedListener) {
1886 logger('canceling previous listener');
1887 this.authorizedListener.cancel();
1888 this.rejectedListener.cancel();
1889 }
1890 logger('add authorization listeners');
1891 this.authorizedListener = postRobot$2.on('BEARER_AUTHORIZED', ({ data }) => {
1892 logger('Authorized: %s => %j', integration, data);
1893 resolve(Object.assign({}, data, { integration }));
1894 });
1895 this.rejectedListener = postRobot$2.on('BEARER_REJECTED', ({ data }) => {
1896 logger('Rejected: %s => %j', integration, data);
1897 reject(Object.assign({}, data, { integration }));
1898 });
1899 }).then();
1900 window.open(AUTHORIZED_URL, '', 'resizable,scrollbars,status,centerscreen=yes,width=500,height=600');
1901 return promise;
1902 };
1903 this._jsonRequest = (path, { query = {}, params = {} } = {}) => __awaiter(this, void 0, void 0, function* () {
1904 const url = [this.config.integrationHost, path].join('');
1905 const queryParams = Object.assign({}, query, { clientId: this.clientId, secured: this.config.secured });
1906 const queryString = buildQuery(cleanOptions(queryParams));
1907 logger$1('json request: path %s', path);
1908 return fetch(`${url}?${queryString}`, {
1909 method: 'POST',
1910 body: JSON.stringify(params || {}),
1911 headers: {
1912 'content-type': 'application/json'
1913 },
1914 credentials: 'include'
1915 }).then((response) => __awaiter(this, void 0, void 0, function* () {
1916 if (response.status > 399) {
1917 logger$1('failing request %j', yield response.clone().json());
1918 }
1919 return response;
1920 }));
1921 });
1922 this.invoke = (integrationId, functionName, _a = {}) => __awaiter(this, void 0, void 0, function* () {
1923 var { query = {} } = _a, params = __rest(_a, ["query"]);
1924 const path = `/api/v4/functions/${integrationId}/${functionName}`;
1925 try {
1926 const response = yield this._jsonRequest(path, { query, params });
1927 const payload = yield response.json();
1928 logger$1('successful request %j', payload);
1929 if (!payload.error) {
1930 return payload;
1931 }
1932 else {
1933 throw { error: payload.error };
1934 }
1935 }
1936 catch (error) {
1937 logger$1('invoke failed %j', error, error.message);
1938 throw { error };
1939 }
1940 });
1941 /**
1942 * Retrieve all dom elements starting by bearer- and ask for assets urls if
1943 */
1944 this.loadMissingIntegrations = () => {
1945 const elements = findElements(document.getElementsByTagName('*'));
1946 const requestedElements = elements.filter(t => !this.registeredIntegration(t));
1947 logger$1(this.registeredIntegrations, elements, requestedElements);
1948 this.sendTags(requestedElements);
1949 };
1950 /**
1951 * check wether if an integration is resgistered
1952 */
1953 this.registeredIntegration = (tagName) => {
1954 // NOTE:
1955 // .constructor !== HTMLElement looks weird but it does not work the other way ¯\_(ツ)_/¯
1956 // constructor is supposed to be class extends HTMLElement{}
1957 this.registeredIntegrations[tagName] =
1958 this.registeredIntegrations[tagName] || document.createElement(tagName).constructor !== HTMLElement;
1959 return this.registeredIntegrations[tagName];
1960 };
1961 /**
1962 * load integration asset or wait until dom is loaded
1963 */
1964 this.initialIntegrationLoading = () => {
1965 if (document.readyState === 'complete' || document.readyState === 'interactive') {
1966 this.debounceRefresh();
1967 }
1968 else {
1969 document.addEventListener('DOMContentLoaded', this.debounceRefresh);
1970 }
1971 };
1972 /**
1973 * Register a DOM observer so that we can load integration assets only when we need them
1974 */
1975 this.registerDomObserver = () => {
1976 if ('MutationObserver' in window) {
1977 this.disconnectObserver();
1978 const container = document.documentElement || document.body;
1979 const config = { childList: true, subtree: true };
1980 this.observer = new MutationObserver(this.observerCallback);
1981 this.observer.observe(container, config);
1982 }
1983 };
1984 this.observerCallback = (mutations) => {
1985 for (const mutation of mutations) {
1986 if (mutation.type == 'childList') {
1987 if (mutation.addedNodes.length) {
1988 this.debounceRefresh();
1989 }
1990 }
1991 }
1992 };
1993 /**
1994 * remove dom observer
1995 */
1996 this.disconnectObserver = () => {
1997 if (this.observer) {
1998 this.observer.disconnect();
1999 delete this.observer;
2000 }
2001 };
2002 /**
2003 * retrieve corresponding integration asset url
2004 */
2005 this.sendTags = (tags) => __awaiter(this, void 0, void 0, function* () {
2006 if (!tags.length) {
2007 return Promise.resolve(true);
2008 }
2009 try {
2010 const response = yield fetch(`${this.config.integrationHost}/v1/parse-tags`, {
2011 headers: { 'content-type': 'application/json' },
2012 body: JSON.stringify({ tags, clientId: this.clientId }),
2013 method: 'POST'
2014 });
2015 if (response.status > 299) {
2016 throw new Error(`Error while fetching integration tag names: ${tags}`);
2017 }
2018 const integrations = yield response.json();
2019 integrations.map(integration => {
2020 if (!document.querySelector(`#${getScriptId(integration.uuid)}`)) {
2021 document.body.appendChild(getScriptDOM(this.clientId || '', integration));
2022 }
2023 });
2024 return true;
2025 }
2026 catch (e) {
2027 return false;
2028 }
2029 });
2030 this.config = Object.assign({}, DEFAULT_OPTIONS, cleanOptions(options));
2031 this.secured = this.config.secured;
2032 logger$1('init bearer instance clientId: %s with config: %j', clientId, this.config);
2033 this.debounceRefresh = debounce_1(this.loadMissingIntegrations, this.config.refreshDebounceDelay);
2034 {
2035 this.initialIntegrationLoading();
2036 if (this.config.domObserver) {
2037 this.registerDomObserver();
2038 }
2039 }
2040 }
2041 }
2042 /**
2043 * Extract/format element tag names given a regexp
2044 * @param elements
2045 * @param filter
2046 */
2047 function findElements(elements, filter = /^bearer-/i) {
2048 return Array.from(elements)
2049 .filter(el => filter.test(el.tagName))
2050 .map(el => el.tagName.toLowerCase());
2051 }
2052 /**
2053 * Return the bearer script id
2054 * @param uuid
2055 */
2056 function getScriptId(uuid) {
2057 return `${prefix}-${uuid}`; // id must start with a letter
2058 }
2059 /**
2060 * create a script tag for a given integration
2061 * @param clientId
2062 * @param integration
2063 */
2064 function getScriptDOM(clientId, integration) {
2065 const s = document.createElement('script');
2066 s.type = 'text/javascript';
2067 s.async = true;
2068 const separator = integration.asset.indexOf('?') > -1 ? '&' : '?';
2069 s.src = [integration.asset, [`clientId=${clientId}`].join('&')].join(separator);
2070 s.id = getScriptId(integration.uuid);
2071 return s;
2072 }
2073 function buildQuery(params) {
2074 function encode(k) {
2075 return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
2076 }
2077 return Object.keys(params)
2078 .map(encode)
2079 .join('&');
2080 }
2081 function cleanOptions(obj) {
2082 return Object.keys(obj).reduce((acc, key) => {
2083 if (obj[key] !== undefined) {
2084 acc[key] = obj[key];
2085 }
2086 return acc;
2087 }, {});
2088 }
2089
2090 var lodash_merge = createCommonjsModule(function (module, exports) {
2091 /**
2092 * Lodash (Custom Build) <https://lodash.com/>
2093 * Build: `lodash modularize exports="npm" -o ./`
2094 * Copyright JS Foundation and other contributors <https://js.foundation/>
2095 * Released under MIT license <https://lodash.com/license>
2096 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
2097 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
2098 */
2099
2100 /** Used as the size to enable large array optimizations. */
2101 var LARGE_ARRAY_SIZE = 200;
2102
2103 /** Used to stand-in for `undefined` hash values. */
2104 var HASH_UNDEFINED = '__lodash_hash_undefined__';
2105
2106 /** Used to detect hot functions by number of calls within a span of milliseconds. */
2107 var HOT_COUNT = 800,
2108 HOT_SPAN = 16;
2109
2110 /** Used as references for various `Number` constants. */
2111 var MAX_SAFE_INTEGER = 9007199254740991;
2112
2113 /** `Object#toString` result references. */
2114 var argsTag = '[object Arguments]',
2115 arrayTag = '[object Array]',
2116 asyncTag = '[object AsyncFunction]',
2117 boolTag = '[object Boolean]',
2118 dateTag = '[object Date]',
2119 errorTag = '[object Error]',
2120 funcTag = '[object Function]',
2121 genTag = '[object GeneratorFunction]',
2122 mapTag = '[object Map]',
2123 numberTag = '[object Number]',
2124 nullTag = '[object Null]',
2125 objectTag = '[object Object]',
2126 proxyTag = '[object Proxy]',
2127 regexpTag = '[object RegExp]',
2128 setTag = '[object Set]',
2129 stringTag = '[object String]',
2130 undefinedTag = '[object Undefined]',
2131 weakMapTag = '[object WeakMap]';
2132
2133 var arrayBufferTag = '[object ArrayBuffer]',
2134 dataViewTag = '[object DataView]',
2135 float32Tag = '[object Float32Array]',
2136 float64Tag = '[object Float64Array]',
2137 int8Tag = '[object Int8Array]',
2138 int16Tag = '[object Int16Array]',
2139 int32Tag = '[object Int32Array]',
2140 uint8Tag = '[object Uint8Array]',
2141 uint8ClampedTag = '[object Uint8ClampedArray]',
2142 uint16Tag = '[object Uint16Array]',
2143 uint32Tag = '[object Uint32Array]';
2144
2145 /**
2146 * Used to match `RegExp`
2147 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
2148 */
2149 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
2150
2151 /** Used to detect host constructors (Safari). */
2152 var reIsHostCtor = /^\[object .+?Constructor\]$/;
2153
2154 /** Used to detect unsigned integer values. */
2155 var reIsUint = /^(?:0|[1-9]\d*)$/;
2156
2157 /** Used to identify `toStringTag` values of typed arrays. */
2158 var typedArrayTags = {};
2159 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
2160 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
2161 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
2162 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
2163 typedArrayTags[uint32Tag] = true;
2164 typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
2165 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
2166 typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
2167 typedArrayTags[errorTag] = typedArrayTags[funcTag] =
2168 typedArrayTags[mapTag] = typedArrayTags[numberTag] =
2169 typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
2170 typedArrayTags[setTag] = typedArrayTags[stringTag] =
2171 typedArrayTags[weakMapTag] = false;
2172
2173 /** Detect free variable `global` from Node.js. */
2174 var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
2175
2176 /** Detect free variable `self`. */
2177 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
2178
2179 /** Used as a reference to the global object. */
2180 var root = freeGlobal || freeSelf || Function('return this')();
2181
2182 /** Detect free variable `exports`. */
2183 var freeExports = exports && !exports.nodeType && exports;
2184
2185 /** Detect free variable `module`. */
2186 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
2187
2188 /** Detect the popular CommonJS extension `module.exports`. */
2189 var moduleExports = freeModule && freeModule.exports === freeExports;
2190
2191 /** Detect free variable `process` from Node.js. */
2192 var freeProcess = moduleExports && freeGlobal.process;
2193
2194 /** Used to access faster Node.js helpers. */
2195 var nodeUtil = (function() {
2196 try {
2197 return freeProcess && freeProcess.binding && freeProcess.binding('util');
2198 } catch (e) {}
2199 }());
2200
2201 /* Node.js helper references. */
2202 var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
2203
2204 /**
2205 * A faster alternative to `Function#apply`, this function invokes `func`
2206 * with the `this` binding of `thisArg` and the arguments of `args`.
2207 *
2208 * @private
2209 * @param {Function} func The function to invoke.
2210 * @param {*} thisArg The `this` binding of `func`.
2211 * @param {Array} args The arguments to invoke `func` with.
2212 * @returns {*} Returns the result of `func`.
2213 */
2214 function apply(func, thisArg, args) {
2215 switch (args.length) {
2216 case 0: return func.call(thisArg);
2217 case 1: return func.call(thisArg, args[0]);
2218 case 2: return func.call(thisArg, args[0], args[1]);
2219 case 3: return func.call(thisArg, args[0], args[1], args[2]);
2220 }
2221 return func.apply(thisArg, args);
2222 }
2223
2224 /**
2225 * The base implementation of `_.times` without support for iteratee shorthands
2226 * or max array length checks.
2227 *
2228 * @private
2229 * @param {number} n The number of times to invoke `iteratee`.
2230 * @param {Function} iteratee The function invoked per iteration.
2231 * @returns {Array} Returns the array of results.
2232 */
2233 function baseTimes(n, iteratee) {
2234 var index = -1,
2235 result = Array(n);
2236
2237 while (++index < n) {
2238 result[index] = iteratee(index);
2239 }
2240 return result;
2241 }
2242
2243 /**
2244 * The base implementation of `_.unary` without support for storing metadata.
2245 *
2246 * @private
2247 * @param {Function} func The function to cap arguments for.
2248 * @returns {Function} Returns the new capped function.
2249 */
2250 function baseUnary(func) {
2251 return function(value) {
2252 return func(value);
2253 };
2254 }
2255
2256 /**
2257 * Gets the value at `key` of `object`.
2258 *
2259 * @private
2260 * @param {Object} [object] The object to query.
2261 * @param {string} key The key of the property to get.
2262 * @returns {*} Returns the property value.
2263 */
2264 function getValue(object, key) {
2265 return object == null ? undefined : object[key];
2266 }
2267
2268 /**
2269 * Creates a unary function that invokes `func` with its argument transformed.
2270 *
2271 * @private
2272 * @param {Function} func The function to wrap.
2273 * @param {Function} transform The argument transform.
2274 * @returns {Function} Returns the new function.
2275 */
2276 function overArg(func, transform) {
2277 return function(arg) {
2278 return func(transform(arg));
2279 };
2280 }
2281
2282 /**
2283 * Gets the value at `key`, unless `key` is "__proto__".
2284 *
2285 * @private
2286 * @param {Object} object The object to query.
2287 * @param {string} key The key of the property to get.
2288 * @returns {*} Returns the property value.
2289 */
2290 function safeGet(object, key) {
2291 return key == '__proto__'
2292 ? undefined
2293 : object[key];
2294 }
2295
2296 /** Used for built-in method references. */
2297 var arrayProto = Array.prototype,
2298 funcProto = Function.prototype,
2299 objectProto = Object.prototype;
2300
2301 /** Used to detect overreaching core-js shims. */
2302 var coreJsData = root['__core-js_shared__'];
2303
2304 /** Used to resolve the decompiled source of functions. */
2305 var funcToString = funcProto.toString;
2306
2307 /** Used to check objects for own properties. */
2308 var hasOwnProperty = objectProto.hasOwnProperty;
2309
2310 /** Used to detect methods masquerading as native. */
2311 var maskSrcKey = (function() {
2312 var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
2313 return uid ? ('Symbol(src)_1.' + uid) : '';
2314 }());
2315
2316 /**
2317 * Used to resolve the
2318 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
2319 * of values.
2320 */
2321 var nativeObjectToString = objectProto.toString;
2322
2323 /** Used to infer the `Object` constructor. */
2324 var objectCtorString = funcToString.call(Object);
2325
2326 /** Used to detect if a method is native. */
2327 var reIsNative = RegExp('^' +
2328 funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
2329 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
2330 );
2331
2332 /** Built-in value references. */
2333 var Buffer = moduleExports ? root.Buffer : undefined,
2334 Symbol = root.Symbol,
2335 Uint8Array = root.Uint8Array,
2336 allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,
2337 getPrototype = overArg(Object.getPrototypeOf, Object),
2338 objectCreate = Object.create,
2339 propertyIsEnumerable = objectProto.propertyIsEnumerable,
2340 splice = arrayProto.splice,
2341 symToStringTag = Symbol ? Symbol.toStringTag : undefined;
2342
2343 var defineProperty = (function() {
2344 try {
2345 var func = getNative(Object, 'defineProperty');
2346 func({}, '', {});
2347 return func;
2348 } catch (e) {}
2349 }());
2350
2351 /* Built-in method references for those with the same name as other `lodash` methods. */
2352 var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
2353 nativeMax = Math.max,
2354 nativeNow = Date.now;
2355
2356 /* Built-in method references that are verified to be native. */
2357 var Map = getNative(root, 'Map'),
2358 nativeCreate = getNative(Object, 'create');
2359
2360 /**
2361 * The base implementation of `_.create` without support for assigning
2362 * properties to the created object.
2363 *
2364 * @private
2365 * @param {Object} proto The object to inherit from.
2366 * @returns {Object} Returns the new object.
2367 */
2368 var baseCreate = (function() {
2369 function object() {}
2370 return function(proto) {
2371 if (!isObject(proto)) {
2372 return {};
2373 }
2374 if (objectCreate) {
2375 return objectCreate(proto);
2376 }
2377 object.prototype = proto;
2378 var result = new object;
2379 object.prototype = undefined;
2380 return result;
2381 };
2382 }());
2383
2384 /**
2385 * Creates a hash object.
2386 *
2387 * @private
2388 * @constructor
2389 * @param {Array} [entries] The key-value pairs to cache.
2390 */
2391 function Hash(entries) {
2392 var index = -1,
2393 length = entries == null ? 0 : entries.length;
2394
2395 this.clear();
2396 while (++index < length) {
2397 var entry = entries[index];
2398 this.set(entry[0], entry[1]);
2399 }
2400 }
2401
2402 /**
2403 * Removes all key-value entries from the hash.
2404 *
2405 * @private
2406 * @name clear
2407 * @memberOf Hash
2408 */
2409 function hashClear() {
2410 this.__data__ = nativeCreate ? nativeCreate(null) : {};
2411 this.size = 0;
2412 }
2413
2414 /**
2415 * Removes `key` and its value from the hash.
2416 *
2417 * @private
2418 * @name delete
2419 * @memberOf Hash
2420 * @param {Object} hash The hash to modify.
2421 * @param {string} key The key of the value to remove.
2422 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
2423 */
2424 function hashDelete(key) {
2425 var result = this.has(key) && delete this.__data__[key];
2426 this.size -= result ? 1 : 0;
2427 return result;
2428 }
2429
2430 /**
2431 * Gets the hash value for `key`.
2432 *
2433 * @private
2434 * @name get
2435 * @memberOf Hash
2436 * @param {string} key The key of the value to get.
2437 * @returns {*} Returns the entry value.
2438 */
2439 function hashGet(key) {
2440 var data = this.__data__;
2441 if (nativeCreate) {
2442 var result = data[key];
2443 return result === HASH_UNDEFINED ? undefined : result;
2444 }
2445 return hasOwnProperty.call(data, key) ? data[key] : undefined;
2446 }
2447
2448 /**
2449 * Checks if a hash value for `key` exists.
2450 *
2451 * @private
2452 * @name has
2453 * @memberOf Hash
2454 * @param {string} key The key of the entry to check.
2455 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
2456 */
2457 function hashHas(key) {
2458 var data = this.__data__;
2459 return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
2460 }
2461
2462 /**
2463 * Sets the hash `key` to `value`.
2464 *
2465 * @private
2466 * @name set
2467 * @memberOf Hash
2468 * @param {string} key The key of the value to set.
2469 * @param {*} value The value to set.
2470 * @returns {Object} Returns the hash instance.
2471 */
2472 function hashSet(key, value) {
2473 var data = this.__data__;
2474 this.size += this.has(key) ? 0 : 1;
2475 data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
2476 return this;
2477 }
2478
2479 // Add methods to `Hash`.
2480 Hash.prototype.clear = hashClear;
2481 Hash.prototype['delete'] = hashDelete;
2482 Hash.prototype.get = hashGet;
2483 Hash.prototype.has = hashHas;
2484 Hash.prototype.set = hashSet;
2485
2486 /**
2487 * Creates an list cache object.
2488 *
2489 * @private
2490 * @constructor
2491 * @param {Array} [entries] The key-value pairs to cache.
2492 */
2493 function ListCache(entries) {
2494 var index = -1,
2495 length = entries == null ? 0 : entries.length;
2496
2497 this.clear();
2498 while (++index < length) {
2499 var entry = entries[index];
2500 this.set(entry[0], entry[1]);
2501 }
2502 }
2503
2504 /**
2505 * Removes all key-value entries from the list cache.
2506 *
2507 * @private
2508 * @name clear
2509 * @memberOf ListCache
2510 */
2511 function listCacheClear() {
2512 this.__data__ = [];
2513 this.size = 0;
2514 }
2515
2516 /**
2517 * Removes `key` and its value from the list cache.
2518 *
2519 * @private
2520 * @name delete
2521 * @memberOf ListCache
2522 * @param {string} key The key of the value to remove.
2523 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
2524 */
2525 function listCacheDelete(key) {
2526 var data = this.__data__,
2527 index = assocIndexOf(data, key);
2528
2529 if (index < 0) {
2530 return false;
2531 }
2532 var lastIndex = data.length - 1;
2533 if (index == lastIndex) {
2534 data.pop();
2535 } else {
2536 splice.call(data, index, 1);
2537 }
2538 --this.size;
2539 return true;
2540 }
2541
2542 /**
2543 * Gets the list cache value for `key`.
2544 *
2545 * @private
2546 * @name get
2547 * @memberOf ListCache
2548 * @param {string} key The key of the value to get.
2549 * @returns {*} Returns the entry value.
2550 */
2551 function listCacheGet(key) {
2552 var data = this.__data__,
2553 index = assocIndexOf(data, key);
2554
2555 return index < 0 ? undefined : data[index][1];
2556 }
2557
2558 /**
2559 * Checks if a list cache value for `key` exists.
2560 *
2561 * @private
2562 * @name has
2563 * @memberOf ListCache
2564 * @param {string} key The key of the entry to check.
2565 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
2566 */
2567 function listCacheHas(key) {
2568 return assocIndexOf(this.__data__, key) > -1;
2569 }
2570
2571 /**
2572 * Sets the list cache `key` to `value`.
2573 *
2574 * @private
2575 * @name set
2576 * @memberOf ListCache
2577 * @param {string} key The key of the value to set.
2578 * @param {*} value The value to set.
2579 * @returns {Object} Returns the list cache instance.
2580 */
2581 function listCacheSet(key, value) {
2582 var data = this.__data__,
2583 index = assocIndexOf(data, key);
2584
2585 if (index < 0) {
2586 ++this.size;
2587 data.push([key, value]);
2588 } else {
2589 data[index][1] = value;
2590 }
2591 return this;
2592 }
2593
2594 // Add methods to `ListCache`.
2595 ListCache.prototype.clear = listCacheClear;
2596 ListCache.prototype['delete'] = listCacheDelete;
2597 ListCache.prototype.get = listCacheGet;
2598 ListCache.prototype.has = listCacheHas;
2599 ListCache.prototype.set = listCacheSet;
2600
2601 /**
2602 * Creates a map cache object to store key-value pairs.
2603 *
2604 * @private
2605 * @constructor
2606 * @param {Array} [entries] The key-value pairs to cache.
2607 */
2608 function MapCache(entries) {
2609 var index = -1,
2610 length = entries == null ? 0 : entries.length;
2611
2612 this.clear();
2613 while (++index < length) {
2614 var entry = entries[index];
2615 this.set(entry[0], entry[1]);
2616 }
2617 }
2618
2619 /**
2620 * Removes all key-value entries from the map.
2621 *
2622 * @private
2623 * @name clear
2624 * @memberOf MapCache
2625 */
2626 function mapCacheClear() {
2627 this.size = 0;
2628 this.__data__ = {
2629 'hash': new Hash,
2630 'map': new (Map || ListCache),
2631 'string': new Hash
2632 };
2633 }
2634
2635 /**
2636 * Removes `key` and its value from the map.
2637 *
2638 * @private
2639 * @name delete
2640 * @memberOf MapCache
2641 * @param {string} key The key of the value to remove.
2642 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
2643 */
2644 function mapCacheDelete(key) {
2645 var result = getMapData(this, key)['delete'](key);
2646 this.size -= result ? 1 : 0;
2647 return result;
2648 }
2649
2650 /**
2651 * Gets the map value for `key`.
2652 *
2653 * @private
2654 * @name get
2655 * @memberOf MapCache
2656 * @param {string} key The key of the value to get.
2657 * @returns {*} Returns the entry value.
2658 */
2659 function mapCacheGet(key) {
2660 return getMapData(this, key).get(key);
2661 }
2662
2663 /**
2664 * Checks if a map value for `key` exists.
2665 *
2666 * @private
2667 * @name has
2668 * @memberOf MapCache
2669 * @param {string} key The key of the entry to check.
2670 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
2671 */
2672 function mapCacheHas(key) {
2673 return getMapData(this, key).has(key);
2674 }
2675
2676 /**
2677 * Sets the map `key` to `value`.
2678 *
2679 * @private
2680 * @name set
2681 * @memberOf MapCache
2682 * @param {string} key The key of the value to set.
2683 * @param {*} value The value to set.
2684 * @returns {Object} Returns the map cache instance.
2685 */
2686 function mapCacheSet(key, value) {
2687 var data = getMapData(this, key),
2688 size = data.size;
2689
2690 data.set(key, value);
2691 this.size += data.size == size ? 0 : 1;
2692 return this;
2693 }
2694
2695 // Add methods to `MapCache`.
2696 MapCache.prototype.clear = mapCacheClear;
2697 MapCache.prototype['delete'] = mapCacheDelete;
2698 MapCache.prototype.get = mapCacheGet;
2699 MapCache.prototype.has = mapCacheHas;
2700 MapCache.prototype.set = mapCacheSet;
2701
2702 /**
2703 * Creates a stack cache object to store key-value pairs.
2704 *
2705 * @private
2706 * @constructor
2707 * @param {Array} [entries] The key-value pairs to cache.
2708 */
2709 function Stack(entries) {
2710 var data = this.__data__ = new ListCache(entries);
2711 this.size = data.size;
2712 }
2713
2714 /**
2715 * Removes all key-value entries from the stack.
2716 *
2717 * @private
2718 * @name clear
2719 * @memberOf Stack
2720 */
2721 function stackClear() {
2722 this.__data__ = new ListCache;
2723 this.size = 0;
2724 }
2725
2726 /**
2727 * Removes `key` and its value from the stack.
2728 *
2729 * @private
2730 * @name delete
2731 * @memberOf Stack
2732 * @param {string} key The key of the value to remove.
2733 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
2734 */
2735 function stackDelete(key) {
2736 var data = this.__data__,
2737 result = data['delete'](key);
2738
2739 this.size = data.size;
2740 return result;
2741 }
2742
2743 /**
2744 * Gets the stack value for `key`.
2745 *
2746 * @private
2747 * @name get
2748 * @memberOf Stack
2749 * @param {string} key The key of the value to get.
2750 * @returns {*} Returns the entry value.
2751 */
2752 function stackGet(key) {
2753 return this.__data__.get(key);
2754 }
2755
2756 /**
2757 * Checks if a stack value for `key` exists.
2758 *
2759 * @private
2760 * @name has
2761 * @memberOf Stack
2762 * @param {string} key The key of the entry to check.
2763 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
2764 */
2765 function stackHas(key) {
2766 return this.__data__.has(key);
2767 }
2768
2769 /**
2770 * Sets the stack `key` to `value`.
2771 *
2772 * @private
2773 * @name set
2774 * @memberOf Stack
2775 * @param {string} key The key of the value to set.
2776 * @param {*} value The value to set.
2777 * @returns {Object} Returns the stack cache instance.
2778 */
2779 function stackSet(key, value) {
2780 var data = this.__data__;
2781 if (data instanceof ListCache) {
2782 var pairs = data.__data__;
2783 if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
2784 pairs.push([key, value]);
2785 this.size = ++data.size;
2786 return this;
2787 }
2788 data = this.__data__ = new MapCache(pairs);
2789 }
2790 data.set(key, value);
2791 this.size = data.size;
2792 return this;
2793 }
2794
2795 // Add methods to `Stack`.
2796 Stack.prototype.clear = stackClear;
2797 Stack.prototype['delete'] = stackDelete;
2798 Stack.prototype.get = stackGet;
2799 Stack.prototype.has = stackHas;
2800 Stack.prototype.set = stackSet;
2801
2802 /**
2803 * Creates an array of the enumerable property names of the array-like `value`.
2804 *
2805 * @private
2806 * @param {*} value The value to query.
2807 * @param {boolean} inherited Specify returning inherited property names.
2808 * @returns {Array} Returns the array of property names.
2809 */
2810 function arrayLikeKeys(value, inherited) {
2811 var isArr = isArray(value),
2812 isArg = !isArr && isArguments(value),
2813 isBuff = !isArr && !isArg && isBuffer(value),
2814 isType = !isArr && !isArg && !isBuff && isTypedArray(value),
2815 skipIndexes = isArr || isArg || isBuff || isType,
2816 result = skipIndexes ? baseTimes(value.length, String) : [],
2817 length = result.length;
2818
2819 for (var key in value) {
2820 if ((inherited || hasOwnProperty.call(value, key)) &&
2821 !(skipIndexes && (
2822 // Safari 9 has enumerable `arguments.length` in strict mode.
2823 key == 'length' ||
2824 // Node.js 0.10 has enumerable non-index properties on buffers.
2825 (isBuff && (key == 'offset' || key == 'parent')) ||
2826 // PhantomJS 2 has enumerable non-index properties on typed arrays.
2827 (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
2828 // Skip index properties.
2829 isIndex(key, length)
2830 ))) {
2831 result.push(key);
2832 }
2833 }
2834 return result;
2835 }
2836
2837 /**
2838 * This function is like `assignValue` except that it doesn't assign
2839 * `undefined` values.
2840 *
2841 * @private
2842 * @param {Object} object The object to modify.
2843 * @param {string} key The key of the property to assign.
2844 * @param {*} value The value to assign.
2845 */
2846 function assignMergeValue(object, key, value) {
2847 if ((value !== undefined && !eq(object[key], value)) ||
2848 (value === undefined && !(key in object))) {
2849 baseAssignValue(object, key, value);
2850 }
2851 }
2852
2853 /**
2854 * Assigns `value` to `key` of `object` if the existing value is not equivalent
2855 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
2856 * for equality comparisons.
2857 *
2858 * @private
2859 * @param {Object} object The object to modify.
2860 * @param {string} key The key of the property to assign.
2861 * @param {*} value The value to assign.
2862 */
2863 function assignValue(object, key, value) {
2864 var objValue = object[key];
2865 if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
2866 (value === undefined && !(key in object))) {
2867 baseAssignValue(object, key, value);
2868 }
2869 }
2870
2871 /**
2872 * Gets the index at which the `key` is found in `array` of key-value pairs.
2873 *
2874 * @private
2875 * @param {Array} array The array to inspect.
2876 * @param {*} key The key to search for.
2877 * @returns {number} Returns the index of the matched value, else `-1`.
2878 */
2879 function assocIndexOf(array, key) {
2880 var length = array.length;
2881 while (length--) {
2882 if (eq(array[length][0], key)) {
2883 return length;
2884 }
2885 }
2886 return -1;
2887 }
2888
2889 /**
2890 * The base implementation of `assignValue` and `assignMergeValue` without
2891 * value checks.
2892 *
2893 * @private
2894 * @param {Object} object The object to modify.
2895 * @param {string} key The key of the property to assign.
2896 * @param {*} value The value to assign.
2897 */
2898 function baseAssignValue(object, key, value) {
2899 if (key == '__proto__' && defineProperty) {
2900 defineProperty(object, key, {
2901 'configurable': true,
2902 'enumerable': true,
2903 'value': value,
2904 'writable': true
2905 });
2906 } else {
2907 object[key] = value;
2908 }
2909 }
2910
2911 /**
2912 * The base implementation of `baseForOwn` which iterates over `object`
2913 * properties returned by `keysFunc` and invokes `iteratee` for each property.
2914 * Iteratee functions may exit iteration early by explicitly returning `false`.
2915 *
2916 * @private
2917 * @param {Object} object The object to iterate over.
2918 * @param {Function} iteratee The function invoked per iteration.
2919 * @param {Function} keysFunc The function to get the keys of `object`.
2920 * @returns {Object} Returns `object`.
2921 */
2922 var baseFor = createBaseFor();
2923
2924 /**
2925 * The base implementation of `getTag` without fallbacks for buggy environments.
2926 *
2927 * @private
2928 * @param {*} value The value to query.
2929 * @returns {string} Returns the `toStringTag`.
2930 */
2931 function baseGetTag(value) {
2932 if (value == null) {
2933 return value === undefined ? undefinedTag : nullTag;
2934 }
2935 return (symToStringTag && symToStringTag in Object(value))
2936 ? getRawTag(value)
2937 : objectToString(value);
2938 }
2939
2940 /**
2941 * The base implementation of `_.isArguments`.
2942 *
2943 * @private
2944 * @param {*} value The value to check.
2945 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
2946 */
2947 function baseIsArguments(value) {
2948 return isObjectLike(value) && baseGetTag(value) == argsTag;
2949 }
2950
2951 /**
2952 * The base implementation of `_.isNative` without bad shim checks.
2953 *
2954 * @private
2955 * @param {*} value The value to check.
2956 * @returns {boolean} Returns `true` if `value` is a native function,
2957 * else `false`.
2958 */
2959 function baseIsNative(value) {
2960 if (!isObject(value) || isMasked(value)) {
2961 return false;
2962 }
2963 var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
2964 return pattern.test(toSource(value));
2965 }
2966
2967 /**
2968 * The base implementation of `_.isTypedArray` without Node.js optimizations.
2969 *
2970 * @private
2971 * @param {*} value The value to check.
2972 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
2973 */
2974 function baseIsTypedArray(value) {
2975 return isObjectLike(value) &&
2976 isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
2977 }
2978
2979 /**
2980 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
2981 *
2982 * @private
2983 * @param {Object} object The object to query.
2984 * @returns {Array} Returns the array of property names.
2985 */
2986 function baseKeysIn(object) {
2987 if (!isObject(object)) {
2988 return nativeKeysIn(object);
2989 }
2990 var isProto = isPrototype(object),
2991 result = [];
2992
2993 for (var key in object) {
2994 if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
2995 result.push(key);
2996 }
2997 }
2998 return result;
2999 }
3000
3001 /**
3002 * The base implementation of `_.merge` without support for multiple sources.
3003 *
3004 * @private
3005 * @param {Object} object The destination object.
3006 * @param {Object} source The source object.
3007 * @param {number} srcIndex The index of `source`.
3008 * @param {Function} [customizer] The function to customize merged values.
3009 * @param {Object} [stack] Tracks traversed source values and their merged
3010 * counterparts.
3011 */
3012 function baseMerge(object, source, srcIndex, customizer, stack) {
3013 if (object === source) {
3014 return;
3015 }
3016 baseFor(source, function(srcValue, key) {
3017 if (isObject(srcValue)) {
3018 stack || (stack = new Stack);
3019 baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
3020 }
3021 else {
3022 var newValue = customizer
3023 ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
3024 : undefined;
3025
3026 if (newValue === undefined) {
3027 newValue = srcValue;
3028 }
3029 assignMergeValue(object, key, newValue);
3030 }
3031 }, keysIn);
3032 }
3033
3034 /**
3035 * A specialized version of `baseMerge` for arrays and objects which performs
3036 * deep merges and tracks traversed objects enabling objects with circular
3037 * references to be merged.
3038 *
3039 * @private
3040 * @param {Object} object The destination object.
3041 * @param {Object} source The source object.
3042 * @param {string} key The key of the value to merge.
3043 * @param {number} srcIndex The index of `source`.
3044 * @param {Function} mergeFunc The function to merge values.
3045 * @param {Function} [customizer] The function to customize assigned values.
3046 * @param {Object} [stack] Tracks traversed source values and their merged
3047 * counterparts.
3048 */
3049 function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
3050 var objValue = safeGet(object, key),
3051 srcValue = safeGet(source, key),
3052 stacked = stack.get(srcValue);
3053
3054 if (stacked) {
3055 assignMergeValue(object, key, stacked);
3056 return;
3057 }
3058 var newValue = customizer
3059 ? customizer(objValue, srcValue, (key + ''), object, source, stack)
3060 : undefined;
3061
3062 var isCommon = newValue === undefined;
3063
3064 if (isCommon) {
3065 var isArr = isArray(srcValue),
3066 isBuff = !isArr && isBuffer(srcValue),
3067 isTyped = !isArr && !isBuff && isTypedArray(srcValue);
3068
3069 newValue = srcValue;
3070 if (isArr || isBuff || isTyped) {
3071 if (isArray(objValue)) {
3072 newValue = objValue;
3073 }
3074 else if (isArrayLikeObject(objValue)) {
3075 newValue = copyArray(objValue);
3076 }
3077 else if (isBuff) {
3078 isCommon = false;
3079 newValue = cloneBuffer(srcValue, true);
3080 }
3081 else if (isTyped) {
3082 isCommon = false;
3083 newValue = cloneTypedArray(srcValue, true);
3084 }
3085 else {
3086 newValue = [];
3087 }
3088 }
3089 else if (isPlainObject(srcValue) || isArguments(srcValue)) {
3090 newValue = objValue;
3091 if (isArguments(objValue)) {
3092 newValue = toPlainObject(objValue);
3093 }
3094 else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
3095 newValue = initCloneObject(srcValue);
3096 }
3097 }
3098 else {
3099 isCommon = false;
3100 }
3101 }
3102 if (isCommon) {
3103 // Recursively merge objects and arrays (susceptible to call stack limits).
3104 stack.set(srcValue, newValue);
3105 mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
3106 stack['delete'](srcValue);
3107 }
3108 assignMergeValue(object, key, newValue);
3109 }
3110
3111 /**
3112 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
3113 *
3114 * @private
3115 * @param {Function} func The function to apply a rest parameter to.
3116 * @param {number} [start=func.length-1] The start position of the rest parameter.
3117 * @returns {Function} Returns the new function.
3118 */
3119 function baseRest(func, start) {
3120 return setToString(overRest(func, start, identity), func + '');
3121 }
3122
3123 /**
3124 * The base implementation of `setToString` without support for hot loop shorting.
3125 *
3126 * @private
3127 * @param {Function} func The function to modify.
3128 * @param {Function} string The `toString` result.
3129 * @returns {Function} Returns `func`.
3130 */
3131 var baseSetToString = !defineProperty ? identity : function(func, string) {
3132 return defineProperty(func, 'toString', {
3133 'configurable': true,
3134 'enumerable': false,
3135 'value': constant(string),
3136 'writable': true
3137 });
3138 };
3139
3140 /**
3141 * Creates a clone of `buffer`.
3142 *
3143 * @private
3144 * @param {Buffer} buffer The buffer to clone.
3145 * @param {boolean} [isDeep] Specify a deep clone.
3146 * @returns {Buffer} Returns the cloned buffer.
3147 */
3148 function cloneBuffer(buffer, isDeep) {
3149 if (isDeep) {
3150 return buffer.slice();
3151 }
3152 var length = buffer.length,
3153 result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
3154
3155 buffer.copy(result);
3156 return result;
3157 }
3158
3159 /**
3160 * Creates a clone of `arrayBuffer`.
3161 *
3162 * @private
3163 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
3164 * @returns {ArrayBuffer} Returns the cloned array buffer.
3165 */
3166 function cloneArrayBuffer(arrayBuffer) {
3167 var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
3168 new Uint8Array(result).set(new Uint8Array(arrayBuffer));
3169 return result;
3170 }
3171
3172 /**
3173 * Creates a clone of `typedArray`.
3174 *
3175 * @private
3176 * @param {Object} typedArray The typed array to clone.
3177 * @param {boolean} [isDeep] Specify a deep clone.
3178 * @returns {Object} Returns the cloned typed array.
3179 */
3180 function cloneTypedArray(typedArray, isDeep) {
3181 var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
3182 return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
3183 }
3184
3185 /**
3186 * Copies the values of `source` to `array`.
3187 *
3188 * @private
3189 * @param {Array} source The array to copy values from.
3190 * @param {Array} [array=[]] The array to copy values to.
3191 * @returns {Array} Returns `array`.
3192 */
3193 function copyArray(source, array) {
3194 var index = -1,
3195 length = source.length;
3196
3197 array || (array = Array(length));
3198 while (++index < length) {
3199 array[index] = source[index];
3200 }
3201 return array;
3202 }
3203
3204 /**
3205 * Copies properties of `source` to `object`.
3206 *
3207 * @private
3208 * @param {Object} source The object to copy properties from.
3209 * @param {Array} props The property identifiers to copy.
3210 * @param {Object} [object={}] The object to copy properties to.
3211 * @param {Function} [customizer] The function to customize copied values.
3212 * @returns {Object} Returns `object`.
3213 */
3214 function copyObject(source, props, object, customizer) {
3215 var isNew = !object;
3216 object || (object = {});
3217
3218 var index = -1,
3219 length = props.length;
3220
3221 while (++index < length) {
3222 var key = props[index];
3223
3224 var newValue = customizer
3225 ? customizer(object[key], source[key], key, object, source)
3226 : undefined;
3227
3228 if (newValue === undefined) {
3229 newValue = source[key];
3230 }
3231 if (isNew) {
3232 baseAssignValue(object, key, newValue);
3233 } else {
3234 assignValue(object, key, newValue);
3235 }
3236 }
3237 return object;
3238 }
3239
3240 /**
3241 * Creates a function like `_.assign`.
3242 *
3243 * @private
3244 * @param {Function} assigner The function to assign values.
3245 * @returns {Function} Returns the new assigner function.
3246 */
3247 function createAssigner(assigner) {
3248 return baseRest(function(object, sources) {
3249 var index = -1,
3250 length = sources.length,
3251 customizer = length > 1 ? sources[length - 1] : undefined,
3252 guard = length > 2 ? sources[2] : undefined;
3253
3254 customizer = (assigner.length > 3 && typeof customizer == 'function')
3255 ? (length--, customizer)
3256 : undefined;
3257
3258 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
3259 customizer = length < 3 ? undefined : customizer;
3260 length = 1;
3261 }
3262 object = Object(object);
3263 while (++index < length) {
3264 var source = sources[index];
3265 if (source) {
3266 assigner(object, source, index, customizer);
3267 }
3268 }
3269 return object;
3270 });
3271 }
3272
3273 /**
3274 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
3275 *
3276 * @private
3277 * @param {boolean} [fromRight] Specify iterating from right to left.
3278 * @returns {Function} Returns the new base function.
3279 */
3280 function createBaseFor(fromRight) {
3281 return function(object, iteratee, keysFunc) {
3282 var index = -1,
3283 iterable = Object(object),
3284 props = keysFunc(object),
3285 length = props.length;
3286
3287 while (length--) {
3288 var key = props[fromRight ? length : ++index];
3289 if (iteratee(iterable[key], key, iterable) === false) {
3290 break;
3291 }
3292 }
3293 return object;
3294 };
3295 }
3296
3297 /**
3298 * Gets the data for `map`.
3299 *
3300 * @private
3301 * @param {Object} map The map to query.
3302 * @param {string} key The reference key.
3303 * @returns {*} Returns the map data.
3304 */
3305 function getMapData(map, key) {
3306 var data = map.__data__;
3307 return isKeyable(key)
3308 ? data[typeof key == 'string' ? 'string' : 'hash']
3309 : data.map;
3310 }
3311
3312 /**
3313 * Gets the native function at `key` of `object`.
3314 *
3315 * @private
3316 * @param {Object} object The object to query.
3317 * @param {string} key The key of the method to get.
3318 * @returns {*} Returns the function if it's native, else `undefined`.
3319 */
3320 function getNative(object, key) {
3321 var value = getValue(object, key);
3322 return baseIsNative(value) ? value : undefined;
3323 }
3324
3325 /**
3326 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
3327 *
3328 * @private
3329 * @param {*} value The value to query.
3330 * @returns {string} Returns the raw `toStringTag`.
3331 */
3332 function getRawTag(value) {
3333 var isOwn = hasOwnProperty.call(value, symToStringTag),
3334 tag = value[symToStringTag];
3335
3336 try {
3337 value[symToStringTag] = undefined;
3338 } catch (e) {}
3339
3340 var result = nativeObjectToString.call(value);
3341 {
3342 if (isOwn) {
3343 value[symToStringTag] = tag;
3344 } else {
3345 delete value[symToStringTag];
3346 }
3347 }
3348 return result;
3349 }
3350
3351 /**
3352 * Initializes an object clone.
3353 *
3354 * @private
3355 * @param {Object} object The object to clone.
3356 * @returns {Object} Returns the initialized clone.
3357 */
3358 function initCloneObject(object) {
3359 return (typeof object.constructor == 'function' && !isPrototype(object))
3360 ? baseCreate(getPrototype(object))
3361 : {};
3362 }
3363
3364 /**
3365 * Checks if `value` is a valid array-like index.
3366 *
3367 * @private
3368 * @param {*} value The value to check.
3369 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
3370 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
3371 */
3372 function isIndex(value, length) {
3373 var type = typeof value;
3374 length = length == null ? MAX_SAFE_INTEGER : length;
3375
3376 return !!length &&
3377 (type == 'number' ||
3378 (type != 'symbol' && reIsUint.test(value))) &&
3379 (value > -1 && value % 1 == 0 && value < length);
3380 }
3381
3382 /**
3383 * Checks if the given arguments are from an iteratee call.
3384 *
3385 * @private
3386 * @param {*} value The potential iteratee value argument.
3387 * @param {*} index The potential iteratee index or key argument.
3388 * @param {*} object The potential iteratee object argument.
3389 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
3390 * else `false`.
3391 */
3392 function isIterateeCall(value, index, object) {
3393 if (!isObject(object)) {
3394 return false;
3395 }
3396 var type = typeof index;
3397 if (type == 'number'
3398 ? (isArrayLike(object) && isIndex(index, object.length))
3399 : (type == 'string' && index in object)
3400 ) {
3401 return eq(object[index], value);
3402 }
3403 return false;
3404 }
3405
3406 /**
3407 * Checks if `value` is suitable for use as unique object key.
3408 *
3409 * @private
3410 * @param {*} value The value to check.
3411 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
3412 */
3413 function isKeyable(value) {
3414 var type = typeof value;
3415 return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
3416 ? (value !== '__proto__')
3417 : (value === null);
3418 }
3419
3420 /**
3421 * Checks if `func` has its source masked.
3422 *
3423 * @private
3424 * @param {Function} func The function to check.
3425 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
3426 */
3427 function isMasked(func) {
3428 return !!maskSrcKey && (maskSrcKey in func);
3429 }
3430
3431 /**
3432 * Checks if `value` is likely a prototype object.
3433 *
3434 * @private
3435 * @param {*} value The value to check.
3436 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
3437 */
3438 function isPrototype(value) {
3439 var Ctor = value && value.constructor,
3440 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
3441
3442 return value === proto;
3443 }
3444
3445 /**
3446 * This function is like
3447 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
3448 * except that it includes inherited enumerable properties.
3449 *
3450 * @private
3451 * @param {Object} object The object to query.
3452 * @returns {Array} Returns the array of property names.
3453 */
3454 function nativeKeysIn(object) {
3455 var result = [];
3456 if (object != null) {
3457 for (var key in Object(object)) {
3458 result.push(key);
3459 }
3460 }
3461 return result;
3462 }
3463
3464 /**
3465 * Converts `value` to a string using `Object.prototype.toString`.
3466 *
3467 * @private
3468 * @param {*} value The value to convert.
3469 * @returns {string} Returns the converted string.
3470 */
3471 function objectToString(value) {
3472 return nativeObjectToString.call(value);
3473 }
3474
3475 /**
3476 * A specialized version of `baseRest` which transforms the rest array.
3477 *
3478 * @private
3479 * @param {Function} func The function to apply a rest parameter to.
3480 * @param {number} [start=func.length-1] The start position of the rest parameter.
3481 * @param {Function} transform The rest array transform.
3482 * @returns {Function} Returns the new function.
3483 */
3484 function overRest(func, start, transform) {
3485 start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
3486 return function() {
3487 var args = arguments,
3488 index = -1,
3489 length = nativeMax(args.length - start, 0),
3490 array = Array(length);
3491
3492 while (++index < length) {
3493 array[index] = args[start + index];
3494 }
3495 index = -1;
3496 var otherArgs = Array(start + 1);
3497 while (++index < start) {
3498 otherArgs[index] = args[index];
3499 }
3500 otherArgs[start] = transform(array);
3501 return apply(func, this, otherArgs);
3502 };
3503 }
3504
3505 /**
3506 * Sets the `toString` method of `func` to return `string`.
3507 *
3508 * @private
3509 * @param {Function} func The function to modify.
3510 * @param {Function} string The `toString` result.
3511 * @returns {Function} Returns `func`.
3512 */
3513 var setToString = shortOut(baseSetToString);
3514
3515 /**
3516 * Creates a function that'll short out and invoke `identity` instead
3517 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
3518 * milliseconds.
3519 *
3520 * @private
3521 * @param {Function} func The function to restrict.
3522 * @returns {Function} Returns the new shortable function.
3523 */
3524 function shortOut(func) {
3525 var count = 0,
3526 lastCalled = 0;
3527
3528 return function() {
3529 var stamp = nativeNow(),
3530 remaining = HOT_SPAN - (stamp - lastCalled);
3531
3532 lastCalled = stamp;
3533 if (remaining > 0) {
3534 if (++count >= HOT_COUNT) {
3535 return arguments[0];
3536 }
3537 } else {
3538 count = 0;
3539 }
3540 return func.apply(undefined, arguments);
3541 };
3542 }
3543
3544 /**
3545 * Converts `func` to its source code.
3546 *
3547 * @private
3548 * @param {Function} func The function to convert.
3549 * @returns {string} Returns the source code.
3550 */
3551 function toSource(func) {
3552 if (func != null) {
3553 try {
3554 return funcToString.call(func);
3555 } catch (e) {}
3556 try {
3557 return (func + '');
3558 } catch (e) {}
3559 }
3560 return '';
3561 }
3562
3563 /**
3564 * Performs a
3565 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
3566 * comparison between two values to determine if they are equivalent.
3567 *
3568 * @static
3569 * @memberOf _
3570 * @since 4.0.0
3571 * @category Lang
3572 * @param {*} value The value to compare.
3573 * @param {*} other The other value to compare.
3574 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
3575 * @example
3576 *
3577 * var object = { 'a': 1 };
3578 * var other = { 'a': 1 };
3579 *
3580 * _.eq(object, object);
3581 * // => true
3582 *
3583 * _.eq(object, other);
3584 * // => false
3585 *
3586 * _.eq('a', 'a');
3587 * // => true
3588 *
3589 * _.eq('a', Object('a'));
3590 * // => false
3591 *
3592 * _.eq(NaN, NaN);
3593 * // => true
3594 */
3595 function eq(value, other) {
3596 return value === other || (value !== value && other !== other);
3597 }
3598
3599 /**
3600 * Checks if `value` is likely an `arguments` object.
3601 *
3602 * @static
3603 * @memberOf _
3604 * @since 0.1.0
3605 * @category Lang
3606 * @param {*} value The value to check.
3607 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
3608 * else `false`.
3609 * @example
3610 *
3611 * _.isArguments(function() { return arguments; }());
3612 * // => true
3613 *
3614 * _.isArguments([1, 2, 3]);
3615 * // => false
3616 */
3617 var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
3618 return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
3619 !propertyIsEnumerable.call(value, 'callee');
3620 };
3621
3622 /**
3623 * Checks if `value` is classified as an `Array` object.
3624 *
3625 * @static
3626 * @memberOf _
3627 * @since 0.1.0
3628 * @category Lang
3629 * @param {*} value The value to check.
3630 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
3631 * @example
3632 *
3633 * _.isArray([1, 2, 3]);
3634 * // => true
3635 *
3636 * _.isArray(document.body.children);
3637 * // => false
3638 *
3639 * _.isArray('abc');
3640 * // => false
3641 *
3642 * _.isArray(_.noop);
3643 * // => false
3644 */
3645 var isArray = Array.isArray;
3646
3647 /**
3648 * Checks if `value` is array-like. A value is considered array-like if it's
3649 * not a function and has a `value.length` that's an integer greater than or
3650 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
3651 *
3652 * @static
3653 * @memberOf _
3654 * @since 4.0.0
3655 * @category Lang
3656 * @param {*} value The value to check.
3657 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
3658 * @example
3659 *
3660 * _.isArrayLike([1, 2, 3]);
3661 * // => true
3662 *
3663 * _.isArrayLike(document.body.children);
3664 * // => true
3665 *
3666 * _.isArrayLike('abc');
3667 * // => true
3668 *
3669 * _.isArrayLike(_.noop);
3670 * // => false
3671 */
3672 function isArrayLike(value) {
3673 return value != null && isLength(value.length) && !isFunction(value);
3674 }
3675
3676 /**
3677 * This method is like `_.isArrayLike` except that it also checks if `value`
3678 * is an object.
3679 *
3680 * @static
3681 * @memberOf _
3682 * @since 4.0.0
3683 * @category Lang
3684 * @param {*} value The value to check.
3685 * @returns {boolean} Returns `true` if `value` is an array-like object,
3686 * else `false`.
3687 * @example
3688 *
3689 * _.isArrayLikeObject([1, 2, 3]);
3690 * // => true
3691 *
3692 * _.isArrayLikeObject(document.body.children);
3693 * // => true
3694 *
3695 * _.isArrayLikeObject('abc');
3696 * // => false
3697 *
3698 * _.isArrayLikeObject(_.noop);
3699 * // => false
3700 */
3701 function isArrayLikeObject(value) {
3702 return isObjectLike(value) && isArrayLike(value);
3703 }
3704
3705 /**
3706 * Checks if `value` is a buffer.
3707 *
3708 * @static
3709 * @memberOf _
3710 * @since 4.3.0
3711 * @category Lang
3712 * @param {*} value The value to check.
3713 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
3714 * @example
3715 *
3716 * _.isBuffer(new Buffer(2));
3717 * // => true
3718 *
3719 * _.isBuffer(new Uint8Array(2));
3720 * // => false
3721 */
3722 var isBuffer = nativeIsBuffer || stubFalse;
3723
3724 /**
3725 * Checks if `value` is classified as a `Function` object.
3726 *
3727 * @static
3728 * @memberOf _
3729 * @since 0.1.0
3730 * @category Lang
3731 * @param {*} value The value to check.
3732 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
3733 * @example
3734 *
3735 * _.isFunction(_);
3736 * // => true
3737 *
3738 * _.isFunction(/abc/);
3739 * // => false
3740 */
3741 function isFunction(value) {
3742 if (!isObject(value)) {
3743 return false;
3744 }
3745 // The use of `Object#toString` avoids issues with the `typeof` operator
3746 // in Safari 9 which returns 'object' for typed arrays and other constructors.
3747 var tag = baseGetTag(value);
3748 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
3749 }
3750
3751 /**
3752 * Checks if `value` is a valid array-like length.
3753 *
3754 * **Note:** This method is loosely based on
3755 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
3756 *
3757 * @static
3758 * @memberOf _
3759 * @since 4.0.0
3760 * @category Lang
3761 * @param {*} value The value to check.
3762 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
3763 * @example
3764 *
3765 * _.isLength(3);
3766 * // => true
3767 *
3768 * _.isLength(Number.MIN_VALUE);
3769 * // => false
3770 *
3771 * _.isLength(Infinity);
3772 * // => false
3773 *
3774 * _.isLength('3');
3775 * // => false
3776 */
3777 function isLength(value) {
3778 return typeof value == 'number' &&
3779 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
3780 }
3781
3782 /**
3783 * Checks if `value` is the
3784 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
3785 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
3786 *
3787 * @static
3788 * @memberOf _
3789 * @since 0.1.0
3790 * @category Lang
3791 * @param {*} value The value to check.
3792 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
3793 * @example
3794 *
3795 * _.isObject({});
3796 * // => true
3797 *
3798 * _.isObject([1, 2, 3]);
3799 * // => true
3800 *
3801 * _.isObject(_.noop);
3802 * // => true
3803 *
3804 * _.isObject(null);
3805 * // => false
3806 */
3807 function isObject(value) {
3808 var type = typeof value;
3809 return value != null && (type == 'object' || type == 'function');
3810 }
3811
3812 /**
3813 * Checks if `value` is object-like. A value is object-like if it's not `null`
3814 * and has a `typeof` result of "object".
3815 *
3816 * @static
3817 * @memberOf _
3818 * @since 4.0.0
3819 * @category Lang
3820 * @param {*} value The value to check.
3821 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
3822 * @example
3823 *
3824 * _.isObjectLike({});
3825 * // => true
3826 *
3827 * _.isObjectLike([1, 2, 3]);
3828 * // => true
3829 *
3830 * _.isObjectLike(_.noop);
3831 * // => false
3832 *
3833 * _.isObjectLike(null);
3834 * // => false
3835 */
3836 function isObjectLike(value) {
3837 return value != null && typeof value == 'object';
3838 }
3839
3840 /**
3841 * Checks if `value` is a plain object, that is, an object created by the
3842 * `Object` constructor or one with a `[[Prototype]]` of `null`.
3843 *
3844 * @static
3845 * @memberOf _
3846 * @since 0.8.0
3847 * @category Lang
3848 * @param {*} value The value to check.
3849 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
3850 * @example
3851 *
3852 * function Foo() {
3853 * this.a = 1;
3854 * }
3855 *
3856 * _.isPlainObject(new Foo);
3857 * // => false
3858 *
3859 * _.isPlainObject([1, 2, 3]);
3860 * // => false
3861 *
3862 * _.isPlainObject({ 'x': 0, 'y': 0 });
3863 * // => true
3864 *
3865 * _.isPlainObject(Object.create(null));
3866 * // => true
3867 */
3868 function isPlainObject(value) {
3869 if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
3870 return false;
3871 }
3872 var proto = getPrototype(value);
3873 if (proto === null) {
3874 return true;
3875 }
3876 var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
3877 return typeof Ctor == 'function' && Ctor instanceof Ctor &&
3878 funcToString.call(Ctor) == objectCtorString;
3879 }
3880
3881 /**
3882 * Checks if `value` is classified as a typed array.
3883 *
3884 * @static
3885 * @memberOf _
3886 * @since 3.0.0
3887 * @category Lang
3888 * @param {*} value The value to check.
3889 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
3890 * @example
3891 *
3892 * _.isTypedArray(new Uint8Array);
3893 * // => true
3894 *
3895 * _.isTypedArray([]);
3896 * // => false
3897 */
3898 var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
3899
3900 /**
3901 * Converts `value` to a plain object flattening inherited enumerable string
3902 * keyed properties of `value` to own properties of the plain object.
3903 *
3904 * @static
3905 * @memberOf _
3906 * @since 3.0.0
3907 * @category Lang
3908 * @param {*} value The value to convert.
3909 * @returns {Object} Returns the converted plain object.
3910 * @example
3911 *
3912 * function Foo() {
3913 * this.b = 2;
3914 * }
3915 *
3916 * Foo.prototype.c = 3;
3917 *
3918 * _.assign({ 'a': 1 }, new Foo);
3919 * // => { 'a': 1, 'b': 2 }
3920 *
3921 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
3922 * // => { 'a': 1, 'b': 2, 'c': 3 }
3923 */
3924 function toPlainObject(value) {
3925 return copyObject(value, keysIn(value));
3926 }
3927
3928 /**
3929 * Creates an array of the own and inherited enumerable property names of `object`.
3930 *
3931 * **Note:** Non-object values are coerced to objects.
3932 *
3933 * @static
3934 * @memberOf _
3935 * @since 3.0.0
3936 * @category Object
3937 * @param {Object} object The object to query.
3938 * @returns {Array} Returns the array of property names.
3939 * @example
3940 *
3941 * function Foo() {
3942 * this.a = 1;
3943 * this.b = 2;
3944 * }
3945 *
3946 * Foo.prototype.c = 3;
3947 *
3948 * _.keysIn(new Foo);
3949 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
3950 */
3951 function keysIn(object) {
3952 return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
3953 }
3954
3955 /**
3956 * This method is like `_.assign` except that it recursively merges own and
3957 * inherited enumerable string keyed properties of source objects into the
3958 * destination object. Source properties that resolve to `undefined` are
3959 * skipped if a destination value exists. Array and plain object properties
3960 * are merged recursively. Other objects and value types are overridden by
3961 * assignment. Source objects are applied from left to right. Subsequent
3962 * sources overwrite property assignments of previous sources.
3963 *
3964 * **Note:** This method mutates `object`.
3965 *
3966 * @static
3967 * @memberOf _
3968 * @since 0.5.0
3969 * @category Object
3970 * @param {Object} object The destination object.
3971 * @param {...Object} [sources] The source objects.
3972 * @returns {Object} Returns `object`.
3973 * @example
3974 *
3975 * var object = {
3976 * 'a': [{ 'b': 2 }, { 'd': 4 }]
3977 * };
3978 *
3979 * var other = {
3980 * 'a': [{ 'c': 3 }, { 'e': 5 }]
3981 * };
3982 *
3983 * _.merge(object, other);
3984 * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
3985 */
3986 var merge = createAssigner(function(object, source, srcIndex) {
3987 baseMerge(object, source, srcIndex);
3988 });
3989
3990 /**
3991 * Creates a function that returns `value`.
3992 *
3993 * @static
3994 * @memberOf _
3995 * @since 2.4.0
3996 * @category Util
3997 * @param {*} value The value to return from the new function.
3998 * @returns {Function} Returns the new constant function.
3999 * @example
4000 *
4001 * var objects = _.times(2, _.constant({ 'a': 1 }));
4002 *
4003 * console.log(objects);
4004 * // => [{ 'a': 1 }, { 'a': 1 }]
4005 *
4006 * console.log(objects[0] === objects[1]);
4007 * // => true
4008 */
4009 function constant(value) {
4010 return function() {
4011 return value;
4012 };
4013 }
4014
4015 /**
4016 * This method returns the first argument it receives.
4017 *
4018 * @static
4019 * @since 0.1.0
4020 * @memberOf _
4021 * @category Util
4022 * @param {*} value Any value.
4023 * @returns {*} Returns `value`.
4024 * @example
4025 *
4026 * var object = { 'a': 1 };
4027 *
4028 * console.log(_.identity(object) === object);
4029 * // => true
4030 */
4031 function identity(value) {
4032 return value;
4033 }
4034
4035 /**
4036 * This method returns `false`.
4037 *
4038 * @static
4039 * @memberOf _
4040 * @since 4.13.0
4041 * @category Util
4042 * @returns {boolean} Returns `false`.
4043 * @example
4044 *
4045 * _.times(2, _.stubFalse);
4046 * // => [false, false]
4047 */
4048 function stubFalse() {
4049 return false;
4050 }
4051
4052 module.exports = merge;
4053 });
4054
4055 /**
4056 * lodash (Custom Build) <https://lodash.com/>
4057 * Build: `lodash modularize exports="npm" -o ./`
4058 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
4059 * Released under MIT license <https://lodash.com/license>
4060 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
4061 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
4062 */
4063
4064 /** Used as the `TypeError` message for "Functions" methods. */
4065 var FUNC_ERROR_TEXT = 'Expected a function';
4066
4067 /** Used to stand-in for `undefined` hash values. */
4068 var HASH_UNDEFINED = '__lodash_hash_undefined__';
4069
4070 /** Used as references for various `Number` constants. */
4071 var INFINITY = 1 / 0;
4072
4073 /** `Object#toString` result references. */
4074 var funcTag = '[object Function]',
4075 genTag = '[object GeneratorFunction]',
4076 symbolTag = '[object Symbol]';
4077
4078 /** Used to match property names within property paths. */
4079 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
4080 reIsPlainProp = /^\w*$/,
4081 reLeadingDot = /^\./,
4082 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
4083
4084 /**
4085 * Used to match `RegExp`
4086 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
4087 */
4088 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
4089
4090 /** Used to match backslashes in property paths. */
4091 var reEscapeChar = /\\(\\)?/g;
4092
4093 /** Used to detect host constructors (Safari). */
4094 var reIsHostCtor = /^\[object .+?Constructor\]$/;
4095
4096 /** Detect free variable `global` from Node.js. */
4097 var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
4098
4099 /** Detect free variable `self`. */
4100 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
4101
4102 /** Used as a reference to the global object. */
4103 var root = freeGlobal || freeSelf || Function('return this')();
4104
4105 /**
4106 * Gets the value at `key` of `object`.
4107 *
4108 * @private
4109 * @param {Object} [object] The object to query.
4110 * @param {string} key The key of the property to get.
4111 * @returns {*} Returns the property value.
4112 */
4113 function getValue(object, key) {
4114 return object == null ? undefined : object[key];
4115 }
4116
4117 /**
4118 * Checks if `value` is a host object in IE < 9.
4119 *
4120 * @private
4121 * @param {*} value The value to check.
4122 * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
4123 */
4124 function isHostObject(value) {
4125 // Many host objects are `Object` objects that can coerce to strings
4126 // despite having improperly defined `toString` methods.
4127 var result = false;
4128 if (value != null && typeof value.toString != 'function') {
4129 try {
4130 result = !!(value + '');
4131 } catch (e) {}
4132 }
4133 return result;
4134 }
4135
4136 /** Used for built-in method references. */
4137 var arrayProto = Array.prototype,
4138 funcProto = Function.prototype,
4139 objectProto = Object.prototype;
4140
4141 /** Used to detect overreaching core-js shims. */
4142 var coreJsData = root['__core-js_shared__'];
4143
4144 /** Used to detect methods masquerading as native. */
4145 var maskSrcKey = (function() {
4146 var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
4147 return uid ? ('Symbol(src)_1.' + uid) : '';
4148 }());
4149
4150 /** Used to resolve the decompiled source of functions. */
4151 var funcToString = funcProto.toString;
4152
4153 /** Used to check objects for own properties. */
4154 var hasOwnProperty = objectProto.hasOwnProperty;
4155
4156 /**
4157 * Used to resolve the
4158 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
4159 * of values.
4160 */
4161 var objectToString = objectProto.toString;
4162
4163 /** Used to detect if a method is native. */
4164 var reIsNative = RegExp('^' +
4165 funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
4166 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
4167 );
4168
4169 /** Built-in value references. */
4170 var Symbol$1 = root.Symbol,
4171 splice = arrayProto.splice;
4172
4173 /* Built-in method references that are verified to be native. */
4174 var Map = getNative(root, 'Map'),
4175 nativeCreate = getNative(Object, 'create');
4176
4177 /** Used to convert symbols to primitives and strings. */
4178 var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined,
4179 symbolToString = symbolProto ? symbolProto.toString : undefined;
4180
4181 /**
4182 * Creates a hash object.
4183 *
4184 * @private
4185 * @constructor
4186 * @param {Array} [entries] The key-value pairs to cache.
4187 */
4188 function Hash(entries) {
4189 var index = -1,
4190 length = entries ? entries.length : 0;
4191
4192 this.clear();
4193 while (++index < length) {
4194 var entry = entries[index];
4195 this.set(entry[0], entry[1]);
4196 }
4197 }
4198
4199 /**
4200 * Removes all key-value entries from the hash.
4201 *
4202 * @private
4203 * @name clear
4204 * @memberOf Hash
4205 */
4206 function hashClear() {
4207 this.__data__ = nativeCreate ? nativeCreate(null) : {};
4208 }
4209
4210 /**
4211 * Removes `key` and its value from the hash.
4212 *
4213 * @private
4214 * @name delete
4215 * @memberOf Hash
4216 * @param {Object} hash The hash to modify.
4217 * @param {string} key The key of the value to remove.
4218 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
4219 */
4220 function hashDelete(key) {
4221 return this.has(key) && delete this.__data__[key];
4222 }
4223
4224 /**
4225 * Gets the hash value for `key`.
4226 *
4227 * @private
4228 * @name get
4229 * @memberOf Hash
4230 * @param {string} key The key of the value to get.
4231 * @returns {*} Returns the entry value.
4232 */
4233 function hashGet(key) {
4234 var data = this.__data__;
4235 if (nativeCreate) {
4236 var result = data[key];
4237 return result === HASH_UNDEFINED ? undefined : result;
4238 }
4239 return hasOwnProperty.call(data, key) ? data[key] : undefined;
4240 }
4241
4242 /**
4243 * Checks if a hash value for `key` exists.
4244 *
4245 * @private
4246 * @name has
4247 * @memberOf Hash
4248 * @param {string} key The key of the entry to check.
4249 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
4250 */
4251 function hashHas(key) {
4252 var data = this.__data__;
4253 return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
4254 }
4255
4256 /**
4257 * Sets the hash `key` to `value`.
4258 *
4259 * @private
4260 * @name set
4261 * @memberOf Hash
4262 * @param {string} key The key of the value to set.
4263 * @param {*} value The value to set.
4264 * @returns {Object} Returns the hash instance.
4265 */
4266 function hashSet(key, value) {
4267 var data = this.__data__;
4268 data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
4269 return this;
4270 }
4271
4272 // Add methods to `Hash`.
4273 Hash.prototype.clear = hashClear;
4274 Hash.prototype['delete'] = hashDelete;
4275 Hash.prototype.get = hashGet;
4276 Hash.prototype.has = hashHas;
4277 Hash.prototype.set = hashSet;
4278
4279 /**
4280 * Creates an list cache object.
4281 *
4282 * @private
4283 * @constructor
4284 * @param {Array} [entries] The key-value pairs to cache.
4285 */
4286 function ListCache(entries) {
4287 var index = -1,
4288 length = entries ? entries.length : 0;
4289
4290 this.clear();
4291 while (++index < length) {
4292 var entry = entries[index];
4293 this.set(entry[0], entry[1]);
4294 }
4295 }
4296
4297 /**
4298 * Removes all key-value entries from the list cache.
4299 *
4300 * @private
4301 * @name clear
4302 * @memberOf ListCache
4303 */
4304 function listCacheClear() {
4305 this.__data__ = [];
4306 }
4307
4308 /**
4309 * Removes `key` and its value from the list cache.
4310 *
4311 * @private
4312 * @name delete
4313 * @memberOf ListCache
4314 * @param {string} key The key of the value to remove.
4315 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
4316 */
4317 function listCacheDelete(key) {
4318 var data = this.__data__,
4319 index = assocIndexOf(data, key);
4320
4321 if (index < 0) {
4322 return false;
4323 }
4324 var lastIndex = data.length - 1;
4325 if (index == lastIndex) {
4326 data.pop();
4327 } else {
4328 splice.call(data, index, 1);
4329 }
4330 return true;
4331 }
4332
4333 /**
4334 * Gets the list cache value for `key`.
4335 *
4336 * @private
4337 * @name get
4338 * @memberOf ListCache
4339 * @param {string} key The key of the value to get.
4340 * @returns {*} Returns the entry value.
4341 */
4342 function listCacheGet(key) {
4343 var data = this.__data__,
4344 index = assocIndexOf(data, key);
4345
4346 return index < 0 ? undefined : data[index][1];
4347 }
4348
4349 /**
4350 * Checks if a list cache value for `key` exists.
4351 *
4352 * @private
4353 * @name has
4354 * @memberOf ListCache
4355 * @param {string} key The key of the entry to check.
4356 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
4357 */
4358 function listCacheHas(key) {
4359 return assocIndexOf(this.__data__, key) > -1;
4360 }
4361
4362 /**
4363 * Sets the list cache `key` to `value`.
4364 *
4365 * @private
4366 * @name set
4367 * @memberOf ListCache
4368 * @param {string} key The key of the value to set.
4369 * @param {*} value The value to set.
4370 * @returns {Object} Returns the list cache instance.
4371 */
4372 function listCacheSet(key, value) {
4373 var data = this.__data__,
4374 index = assocIndexOf(data, key);
4375
4376 if (index < 0) {
4377 data.push([key, value]);
4378 } else {
4379 data[index][1] = value;
4380 }
4381 return this;
4382 }
4383
4384 // Add methods to `ListCache`.
4385 ListCache.prototype.clear = listCacheClear;
4386 ListCache.prototype['delete'] = listCacheDelete;
4387 ListCache.prototype.get = listCacheGet;
4388 ListCache.prototype.has = listCacheHas;
4389 ListCache.prototype.set = listCacheSet;
4390
4391 /**
4392 * Creates a map cache object to store key-value pairs.
4393 *
4394 * @private
4395 * @constructor
4396 * @param {Array} [entries] The key-value pairs to cache.
4397 */
4398 function MapCache(entries) {
4399 var index = -1,
4400 length = entries ? entries.length : 0;
4401
4402 this.clear();
4403 while (++index < length) {
4404 var entry = entries[index];
4405 this.set(entry[0], entry[1]);
4406 }
4407 }
4408
4409 /**
4410 * Removes all key-value entries from the map.
4411 *
4412 * @private
4413 * @name clear
4414 * @memberOf MapCache
4415 */
4416 function mapCacheClear() {
4417 this.__data__ = {
4418 'hash': new Hash,
4419 'map': new (Map || ListCache),
4420 'string': new Hash
4421 };
4422 }
4423
4424 /**
4425 * Removes `key` and its value from the map.
4426 *
4427 * @private
4428 * @name delete
4429 * @memberOf MapCache
4430 * @param {string} key The key of the value to remove.
4431 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
4432 */
4433 function mapCacheDelete(key) {
4434 return getMapData(this, key)['delete'](key);
4435 }
4436
4437 /**
4438 * Gets the map value for `key`.
4439 *
4440 * @private
4441 * @name get
4442 * @memberOf MapCache
4443 * @param {string} key The key of the value to get.
4444 * @returns {*} Returns the entry value.
4445 */
4446 function mapCacheGet(key) {
4447 return getMapData(this, key).get(key);
4448 }
4449
4450 /**
4451 * Checks if a map value for `key` exists.
4452 *
4453 * @private
4454 * @name has
4455 * @memberOf MapCache
4456 * @param {string} key The key of the entry to check.
4457 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
4458 */
4459 function mapCacheHas(key) {
4460 return getMapData(this, key).has(key);
4461 }
4462
4463 /**
4464 * Sets the map `key` to `value`.
4465 *
4466 * @private
4467 * @name set
4468 * @memberOf MapCache
4469 * @param {string} key The key of the value to set.
4470 * @param {*} value The value to set.
4471 * @returns {Object} Returns the map cache instance.
4472 */
4473 function mapCacheSet(key, value) {
4474 getMapData(this, key).set(key, value);
4475 return this;
4476 }
4477
4478 // Add methods to `MapCache`.
4479 MapCache.prototype.clear = mapCacheClear;
4480 MapCache.prototype['delete'] = mapCacheDelete;
4481 MapCache.prototype.get = mapCacheGet;
4482 MapCache.prototype.has = mapCacheHas;
4483 MapCache.prototype.set = mapCacheSet;
4484
4485 /**
4486 * Gets the index at which the `key` is found in `array` of key-value pairs.
4487 *
4488 * @private
4489 * @param {Array} array The array to inspect.
4490 * @param {*} key The key to search for.
4491 * @returns {number} Returns the index of the matched value, else `-1`.
4492 */
4493 function assocIndexOf(array, key) {
4494 var length = array.length;
4495 while (length--) {
4496 if (eq(array[length][0], key)) {
4497 return length;
4498 }
4499 }
4500 return -1;
4501 }
4502
4503 /**
4504 * The base implementation of `_.get` without support for default values.
4505 *
4506 * @private
4507 * @param {Object} object The object to query.
4508 * @param {Array|string} path The path of the property to get.
4509 * @returns {*} Returns the resolved value.
4510 */
4511 function baseGet(object, path) {
4512 path = isKey(path, object) ? [path] : castPath(path);
4513
4514 var index = 0,
4515 length = path.length;
4516
4517 while (object != null && index < length) {
4518 object = object[toKey(path[index++])];
4519 }
4520 return (index && index == length) ? object : undefined;
4521 }
4522
4523 /**
4524 * The base implementation of `_.isNative` without bad shim checks.
4525 *
4526 * @private
4527 * @param {*} value The value to check.
4528 * @returns {boolean} Returns `true` if `value` is a native function,
4529 * else `false`.
4530 */
4531 function baseIsNative(value) {
4532 if (!isObject(value) || isMasked(value)) {
4533 return false;
4534 }
4535 var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
4536 return pattern.test(toSource(value));
4537 }
4538
4539 /**
4540 * The base implementation of `_.toString` which doesn't convert nullish
4541 * values to empty strings.
4542 *
4543 * @private
4544 * @param {*} value The value to process.
4545 * @returns {string} Returns the string.
4546 */
4547 function baseToString(value) {
4548 // Exit early for strings to avoid a performance hit in some environments.
4549 if (typeof value == 'string') {
4550 return value;
4551 }
4552 if (isSymbol(value)) {
4553 return symbolToString ? symbolToString.call(value) : '';
4554 }
4555 var result = (value + '');
4556 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
4557 }
4558
4559 /**
4560 * Casts `value` to a path array if it's not one.
4561 *
4562 * @private
4563 * @param {*} value The value to inspect.
4564 * @returns {Array} Returns the cast property path array.
4565 */
4566 function castPath(value) {
4567 return isArray(value) ? value : stringToPath(value);
4568 }
4569
4570 /**
4571 * Gets the data for `map`.
4572 *
4573 * @private
4574 * @param {Object} map The map to query.
4575 * @param {string} key The reference key.
4576 * @returns {*} Returns the map data.
4577 */
4578 function getMapData(map, key) {
4579 var data = map.__data__;
4580 return isKeyable(key)
4581 ? data[typeof key == 'string' ? 'string' : 'hash']
4582 : data.map;
4583 }
4584
4585 /**
4586 * Gets the native function at `key` of `object`.
4587 *
4588 * @private
4589 * @param {Object} object The object to query.
4590 * @param {string} key The key of the method to get.
4591 * @returns {*} Returns the function if it's native, else `undefined`.
4592 */
4593 function getNative(object, key) {
4594 var value = getValue(object, key);
4595 return baseIsNative(value) ? value : undefined;
4596 }
4597
4598 /**
4599 * Checks if `value` is a property name and not a property path.
4600 *
4601 * @private
4602 * @param {*} value The value to check.
4603 * @param {Object} [object] The object to query keys on.
4604 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
4605 */
4606 function isKey(value, object) {
4607 if (isArray(value)) {
4608 return false;
4609 }
4610 var type = typeof value;
4611 if (type == 'number' || type == 'symbol' || type == 'boolean' ||
4612 value == null || isSymbol(value)) {
4613 return true;
4614 }
4615 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
4616 (object != null && value in Object(object));
4617 }
4618
4619 /**
4620 * Checks if `value` is suitable for use as unique object key.
4621 *
4622 * @private
4623 * @param {*} value The value to check.
4624 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
4625 */
4626 function isKeyable(value) {
4627 var type = typeof value;
4628 return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
4629 ? (value !== '__proto__')
4630 : (value === null);
4631 }
4632
4633 /**
4634 * Checks if `func` has its source masked.
4635 *
4636 * @private
4637 * @param {Function} func The function to check.
4638 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
4639 */
4640 function isMasked(func) {
4641 return !!maskSrcKey && (maskSrcKey in func);
4642 }
4643
4644 /**
4645 * Converts `string` to a property path array.
4646 *
4647 * @private
4648 * @param {string} string The string to convert.
4649 * @returns {Array} Returns the property path array.
4650 */
4651 var stringToPath = memoize(function(string) {
4652 string = toString(string);
4653
4654 var result = [];
4655 if (reLeadingDot.test(string)) {
4656 result.push('');
4657 }
4658 string.replace(rePropName, function(match, number, quote, string) {
4659 result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
4660 });
4661 return result;
4662 });
4663
4664 /**
4665 * Converts `value` to a string key if it's not a string or symbol.
4666 *
4667 * @private
4668 * @param {*} value The value to inspect.
4669 * @returns {string|symbol} Returns the key.
4670 */
4671 function toKey(value) {
4672 if (typeof value == 'string' || isSymbol(value)) {
4673 return value;
4674 }
4675 var result = (value + '');
4676 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
4677 }
4678
4679 /**
4680 * Converts `func` to its source code.
4681 *
4682 * @private
4683 * @param {Function} func The function to process.
4684 * @returns {string} Returns the source code.
4685 */
4686 function toSource(func) {
4687 if (func != null) {
4688 try {
4689 return funcToString.call(func);
4690 } catch (e) {}
4691 try {
4692 return (func + '');
4693 } catch (e) {}
4694 }
4695 return '';
4696 }
4697
4698 /**
4699 * Creates a function that memoizes the result of `func`. If `resolver` is
4700 * provided, it determines the cache key for storing the result based on the
4701 * arguments provided to the memoized function. By default, the first argument
4702 * provided to the memoized function is used as the map cache key. The `func`
4703 * is invoked with the `this` binding of the memoized function.
4704 *
4705 * **Note:** The cache is exposed as the `cache` property on the memoized
4706 * function. Its creation may be customized by replacing the `_.memoize.Cache`
4707 * constructor with one whose instances implement the
4708 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
4709 * method interface of `delete`, `get`, `has`, and `set`.
4710 *
4711 * @static
4712 * @memberOf _
4713 * @since 0.1.0
4714 * @category Function
4715 * @param {Function} func The function to have its output memoized.
4716 * @param {Function} [resolver] The function to resolve the cache key.
4717 * @returns {Function} Returns the new memoized function.
4718 * @example
4719 *
4720 * var object = { 'a': 1, 'b': 2 };
4721 * var other = { 'c': 3, 'd': 4 };
4722 *
4723 * var values = _.memoize(_.values);
4724 * values(object);
4725 * // => [1, 2]
4726 *
4727 * values(other);
4728 * // => [3, 4]
4729 *
4730 * object.a = 2;
4731 * values(object);
4732 * // => [1, 2]
4733 *
4734 * // Modify the result cache.
4735 * values.cache.set(object, ['a', 'b']);
4736 * values(object);
4737 * // => ['a', 'b']
4738 *
4739 * // Replace `_.memoize.Cache`.
4740 * _.memoize.Cache = WeakMap;
4741 */
4742 function memoize(func, resolver) {
4743 if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
4744 throw new TypeError(FUNC_ERROR_TEXT);
4745 }
4746 var memoized = function() {
4747 var args = arguments,
4748 key = resolver ? resolver.apply(this, args) : args[0],
4749 cache = memoized.cache;
4750
4751 if (cache.has(key)) {
4752 return cache.get(key);
4753 }
4754 var result = func.apply(this, args);
4755 memoized.cache = cache.set(key, result);
4756 return result;
4757 };
4758 memoized.cache = new (memoize.Cache || MapCache);
4759 return memoized;
4760 }
4761
4762 // Assign cache to `_.memoize`.
4763 memoize.Cache = MapCache;
4764
4765 /**
4766 * Performs a
4767 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
4768 * comparison between two values to determine if they are equivalent.
4769 *
4770 * @static
4771 * @memberOf _
4772 * @since 4.0.0
4773 * @category Lang
4774 * @param {*} value The value to compare.
4775 * @param {*} other The other value to compare.
4776 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
4777 * @example
4778 *
4779 * var object = { 'a': 1 };
4780 * var other = { 'a': 1 };
4781 *
4782 * _.eq(object, object);
4783 * // => true
4784 *
4785 * _.eq(object, other);
4786 * // => false
4787 *
4788 * _.eq('a', 'a');
4789 * // => true
4790 *
4791 * _.eq('a', Object('a'));
4792 * // => false
4793 *
4794 * _.eq(NaN, NaN);
4795 * // => true
4796 */
4797 function eq(value, other) {
4798 return value === other || (value !== value && other !== other);
4799 }
4800
4801 /**
4802 * Checks if `value` is classified as an `Array` object.
4803 *
4804 * @static
4805 * @memberOf _
4806 * @since 0.1.0
4807 * @category Lang
4808 * @param {*} value The value to check.
4809 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
4810 * @example
4811 *
4812 * _.isArray([1, 2, 3]);
4813 * // => true
4814 *
4815 * _.isArray(document.body.children);
4816 * // => false
4817 *
4818 * _.isArray('abc');
4819 * // => false
4820 *
4821 * _.isArray(_.noop);
4822 * // => false
4823 */
4824 var isArray = Array.isArray;
4825
4826 /**
4827 * Checks if `value` is classified as a `Function` object.
4828 *
4829 * @static
4830 * @memberOf _
4831 * @since 0.1.0
4832 * @category Lang
4833 * @param {*} value The value to check.
4834 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
4835 * @example
4836 *
4837 * _.isFunction(_);
4838 * // => true
4839 *
4840 * _.isFunction(/abc/);
4841 * // => false
4842 */
4843 function isFunction(value) {
4844 // The use of `Object#toString` avoids issues with the `typeof` operator
4845 // in Safari 8-9 which returns 'object' for typed array and other constructors.
4846 var tag = isObject(value) ? objectToString.call(value) : '';
4847 return tag == funcTag || tag == genTag;
4848 }
4849
4850 /**
4851 * Checks if `value` is the
4852 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
4853 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
4854 *
4855 * @static
4856 * @memberOf _
4857 * @since 0.1.0
4858 * @category Lang
4859 * @param {*} value The value to check.
4860 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
4861 * @example
4862 *
4863 * _.isObject({});
4864 * // => true
4865 *
4866 * _.isObject([1, 2, 3]);
4867 * // => true
4868 *
4869 * _.isObject(_.noop);
4870 * // => true
4871 *
4872 * _.isObject(null);
4873 * // => false
4874 */
4875 function isObject(value) {
4876 var type = typeof value;
4877 return !!value && (type == 'object' || type == 'function');
4878 }
4879
4880 /**
4881 * Checks if `value` is object-like. A value is object-like if it's not `null`
4882 * and has a `typeof` result of "object".
4883 *
4884 * @static
4885 * @memberOf _
4886 * @since 4.0.0
4887 * @category Lang
4888 * @param {*} value The value to check.
4889 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
4890 * @example
4891 *
4892 * _.isObjectLike({});
4893 * // => true
4894 *
4895 * _.isObjectLike([1, 2, 3]);
4896 * // => true
4897 *
4898 * _.isObjectLike(_.noop);
4899 * // => false
4900 *
4901 * _.isObjectLike(null);
4902 * // => false
4903 */
4904 function isObjectLike(value) {
4905 return !!value && typeof value == 'object';
4906 }
4907
4908 /**
4909 * Checks if `value` is classified as a `Symbol` primitive or object.
4910 *
4911 * @static
4912 * @memberOf _
4913 * @since 4.0.0
4914 * @category Lang
4915 * @param {*} value The value to check.
4916 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
4917 * @example
4918 *
4919 * _.isSymbol(Symbol.iterator);
4920 * // => true
4921 *
4922 * _.isSymbol('abc');
4923 * // => false
4924 */
4925 function isSymbol(value) {
4926 return typeof value == 'symbol' ||
4927 (isObjectLike(value) && objectToString.call(value) == symbolTag);
4928 }
4929
4930 /**
4931 * Converts `value` to a string. An empty string is returned for `null`
4932 * and `undefined` values. The sign of `-0` is preserved.
4933 *
4934 * @static
4935 * @memberOf _
4936 * @since 4.0.0
4937 * @category Lang
4938 * @param {*} value The value to process.
4939 * @returns {string} Returns the string.
4940 * @example
4941 *
4942 * _.toString(null);
4943 * // => ''
4944 *
4945 * _.toString(-0);
4946 * // => '-0'
4947 *
4948 * _.toString([1, 2, 3]);
4949 * // => '1,2,3'
4950 */
4951 function toString(value) {
4952 return value == null ? '' : baseToString(value);
4953 }
4954
4955 /**
4956 * Gets the value at `path` of `object`. If the resolved value is
4957 * `undefined`, the `defaultValue` is returned in its place.
4958 *
4959 * @static
4960 * @memberOf _
4961 * @since 3.7.0
4962 * @category Object
4963 * @param {Object} object The object to query.
4964 * @param {Array|string} path The path of the property to get.
4965 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
4966 * @returns {*} Returns the resolved value.
4967 * @example
4968 *
4969 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
4970 *
4971 * _.get(object, 'a[0].b.c');
4972 * // => 3
4973 *
4974 * _.get(object, ['a', '0', 'b', 'c']);
4975 * // => 3
4976 *
4977 * _.get(object, 'a.b.c', 'default');
4978 * // => 'default'
4979 */
4980 function get(object, path, defaultValue) {
4981 var result = object == null ? undefined : baseGet(object, path);
4982 return result === undefined ? defaultValue : result;
4983 }
4984
4985 var lodash_get = get;
4986
4987 const debug = logger.extend('i18n');
4988 const DEFAULT_LOCALE = 'en';
4989 const LOCALE_CHANGED = 'bearer-locale-changed';
4990 class I18n {
4991 constructor() {
4992 this._locale = DEFAULT_LOCALE;
4993 this._dictionnary = {
4994 [DEFAULT_LOCALE]: {}
4995 };
4996 /**
4997 * load a dictionary (key/value) containing all the translations required by a dictionary
4998 * @argument {string} integration the identifier of the Integration you want to connect to ex: 12345-attach-github-pull-request
4999 * @argument {(Object | Promise<Object>)} dictionary dictionary containing all key/value pairs of the integration
5000 * @argument {{locale: string}} options { locale: 'en'}
5001 */
5002 this.load = (integrationName, dictionnary, { locale = this.locale } = {}) => __awaiter(this, void 0, void 0, function* () {
5003 const result = yield dictionnary;
5004 const newEntries = !!integrationName
5005 ? { [integrationName]: result }
5006 : result;
5007 this._dictionnary[locale] = lodash_merge(lodash_get(this._dictionnary, locale), newEntries);
5008 this.localeChanged();
5009 });
5010 this.get = (integrationName, key, options = {}) => {
5011 const path = [options.locale || this.locale, integrationName, key].filter(m => m).join('.');
5012 debug('lookup key', path);
5013 return lodash_get(this._dictionnary, path);
5014 };
5015 }
5016 localeChanged() {
5017 document.dispatchEvent(new CustomEvent(LOCALE_CHANGED, { detail: { locale: this.locale } }));
5018 }
5019 /**
5020 * set the current locale you want your integrations to use
5021 */
5022 set locale(locale) {
5023 this._locale = locale;
5024 this.localeChanged();
5025 }
5026 get locale() {
5027 return this._locale;
5028 }
5029 }
5030 const i18n = new I18n();
5031
5032 /**
5033 * @param {string} clientId Client ID you'll find within the developer portal > Settings
5034 * @param {Partial<TBearerOptions>} options? Fine tune bearer functionalities
5035 */
5036 // @ts-ignore
5037 const bearer = (clientId, options) => {
5038 bearer.instance = new Bearer(clientId, options);
5039 return bearer.instance;
5040 };
5041 // Handle non instantiated bearer client
5042 Object.defineProperty(bearer, 'instance', {
5043 get: function () {
5044 if (!this._instance) {
5045 logMissingInstance();
5046 this._instance = new Bearer(undefined);
5047 }
5048 return this._instance;
5049 },
5050 set: function (bearerInstance) {
5051 this._instance = bearerInstance;
5052 }
5053 });
5054 bearer.version = '0.112.0';
5055 bearer.i18n = i18n;
5056 // fake the presence of secured
5057 bearer.secured = false;
5058 Object.defineProperty(bearer, 'secured', {
5059 get: function () {
5060 return this.instance && this.instance.secured;
5061 },
5062 set: function (secured) {
5063 this.instance.secured = secured;
5064 }
5065 });
5066 const MISSING_INSTANCE_MEESSAGE = '%c No bearer client has been initialized. please make sure you call bearer("YOUR_CLIENT") before using any component of backend function';
5067 const MISSING_INSTANCE_STYLE = 'font-weight:bold;';
5068 function logMissingInstance() {
5069 if (logger.enabled) {
5070 logger.extend('main')(MISSING_INSTANCE_MEESSAGE, MISSING_INSTANCE_STYLE);
5071 }
5072 else {
5073 console.warn(MISSING_INSTANCE_MEESSAGE, MISSING_INSTANCE_STYLE);
5074 }
5075 }
5076
5077 return bearer;
5078
5079})));
5080//# sourceMappingURL=bearer.production.min.js.map