UNPKG

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