diff --git a/demo/advanced/props/index.htm b/demo/advanced/props/index.htm
index daab38b6..e430bb48 100644
--- a/demo/advanced/props/index.htm
+++ b/demo/advanced/props/index.htm
@@ -5,6 +5,7 @@
+
diff --git a/demo/advanced/props/login.htm b/demo/advanced/props/login.htm
index 49c328ee..944902e9 100644
--- a/demo/advanced/props/login.htm
+++ b/demo/advanced/props/login.htm
@@ -7,6 +7,7 @@
+
diff --git a/demo/advanced/props/login.js b/demo/advanced/props/login.js
index 5157df0e..df2ba601 100644
--- a/demo/advanced/props/login.js
+++ b/demo/advanced/props/login.js
@@ -1,25 +1,2 @@
-window.MyLoginZoidComponent = zoid.create({
-
- // The html tag used to render my component
-
- tag: 'my-login-component',
-
- // The url that will be loaded in the iframe or popup, when someone includes my component on their page
-
- url: new URL('login.htm', window.location.href).href,
-
- // The properties they can (or must) pass down to my component
-
- props: {
-
- prefilledEmail: {
- type: 'string',
- required: false
- },
-
- onLogin: {
- type: 'function'
- }
- }
-});
+window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef);
diff --git a/demo/advanced/react-end-to-end/index.htm b/demo/advanced/react-end-to-end/index.htm
index ead8eac7..118b4270 100644
--- a/demo/advanced/react-end-to-end/index.htm
+++ b/demo/advanced/react-end-to-end/index.htm
@@ -9,6 +9,7 @@
+
@@ -17,7 +18,7 @@
+
diff --git a/demo/advanced/react-end-to-end/login.js b/demo/advanced/react-end-to-end/login.js
index 0976e3b7..df2ba601 100644
--- a/demo/advanced/react-end-to-end/login.js
+++ b/demo/advanced/react-end-to-end/login.js
@@ -1,11 +1,2 @@
-window.LoginZoidComponent = zoid.create({
-
- // The html tag used to render my component
-
- tag: 'my-login-component',
-
- // The url that will be loaded in the iframe or popup, when someone includes my component on their page
-
- url: new URL('login.htm', window.location.href).href
-});
+window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef);
diff --git a/demo/advanced/remote-popup/index.htm b/demo/advanced/remote-popup/index.htm
index a474f351..5b496ecb 100644
--- a/demo/advanced/remote-popup/index.htm
+++ b/demo/advanced/remote-popup/index.htm
@@ -7,6 +7,7 @@
+
diff --git a/demo/advanced/remote-popup/login-button.htm b/demo/advanced/remote-popup/login-button.htm
index 43b1cba4..123268f4 100644
--- a/demo/advanced/remote-popup/login-button.htm
+++ b/demo/advanced/remote-popup/login-button.htm
@@ -9,6 +9,7 @@
+
diff --git a/demo/advanced/remote-popup/login.htm b/demo/advanced/remote-popup/login.htm
index d22246a0..64b9a230 100644
--- a/demo/advanced/remote-popup/login.htm
+++ b/demo/advanced/remote-popup/login.htm
@@ -7,6 +7,7 @@
+
diff --git a/demo/advanced/remote-popup/login.js b/demo/advanced/remote-popup/login.js
index 5145b956..df2ba601 100644
--- a/demo/advanced/remote-popup/login.js
+++ b/demo/advanced/remote-popup/login.js
@@ -1,11 +1,2 @@
-window.MyLoginZoidComponent = zoid.create({
-
- // The html tag used to render my component
-
- tag: 'my-login-component',
-
- // The url that will be loaded in the iframe or popup, when someone includes my component on their page
-
- url: new URL('login.htm', window.location.href).href
-});
+window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef);
diff --git a/demo/advanced/remote/index.htm b/demo/advanced/remote/index.htm
index 3a3eb165..40d80853 100644
--- a/demo/advanced/remote/index.htm
+++ b/demo/advanced/remote/index.htm
@@ -7,6 +7,7 @@
+
diff --git a/demo/advanced/remote/login-button.htm b/demo/advanced/remote/login-button.htm
index 6ed66e46..2dc09711 100644
--- a/demo/advanced/remote/login-button.htm
+++ b/demo/advanced/remote/login-button.htm
@@ -9,6 +9,7 @@
+
diff --git a/demo/advanced/remote/login.htm b/demo/advanced/remote/login.htm
index d22246a0..64b9a230 100644
--- a/demo/advanced/remote/login.htm
+++ b/demo/advanced/remote/login.htm
@@ -7,6 +7,7 @@
+
diff --git a/demo/advanced/remote/login.js b/demo/advanced/remote/login.js
index 5145b956..df2ba601 100644
--- a/demo/advanced/remote/login.js
+++ b/demo/advanced/remote/login.js
@@ -1,11 +1,2 @@
-window.MyLoginZoidComponent = zoid.create({
-
- // The html tag used to render my component
-
- tag: 'my-login-component',
-
- // The url that will be loaded in the iframe or popup, when someone includes my component on their page
-
- url: new URL('login.htm', window.location.href).href
-});
+window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef);
diff --git a/demo/basic/iframe/index.htm b/demo/basic/iframe/index.htm
index c0962914..9a715a6d 100644
--- a/demo/basic/iframe/index.htm
+++ b/demo/basic/iframe/index.htm
@@ -5,6 +5,7 @@
+
diff --git a/demo/basic/iframe/login.htm b/demo/basic/iframe/login.htm
index d22246a0..64b9a230 100644
--- a/demo/basic/iframe/login.htm
+++ b/demo/basic/iframe/login.htm
@@ -7,6 +7,7 @@
+
diff --git a/demo/basic/iframe/login.js b/demo/basic/iframe/login.js
index 290174ea..df2ba601 100644
--- a/demo/basic/iframe/login.js
+++ b/demo/basic/iframe/login.js
@@ -1,15 +1,2 @@
-window.MyLoginZoidComponent = zoid.create({
- dimensions: {
- width: '300px',
- height: '150px',
- },
-
- // The html tag used to render my component
-
- tag: 'my-login-component',
-
- // The url that will be loaded in the iframe or popup, when someone includes my component on their page
-
- url: new URL('login.htm', window.location.href).href
-});
+window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef);
diff --git a/demo/basic/popup/index.htm b/demo/basic/popup/index.htm
index 9f8a6f6c..3caeabd0 100644
--- a/demo/basic/popup/index.htm
+++ b/demo/basic/popup/index.htm
@@ -6,6 +6,7 @@
+
diff --git a/demo/basic/popup/login.htm b/demo/basic/popup/login.htm
index d22246a0..20e6ba3f 100644
--- a/demo/basic/popup/login.htm
+++ b/demo/basic/popup/login.htm
@@ -7,6 +7,7 @@
+
diff --git a/demo/basic/popup/login.js b/demo/basic/popup/login.js
index 462fb925..f0a9561d 100644
--- a/demo/basic/popup/login.js
+++ b/demo/basic/popup/login.js
@@ -1,21 +1,8 @@
window.MyLoginZoidComponent = zoid.create({
-
- // The html tag used to render my component
-
- tag: 'my-login-component',
-
- // The url that will be loaded in the iframe or popup, when someone includes my component on their page
-
- url: new URL('login.htm', window.location.href).href,
-
- dimensions: {
- width: '300px',
- height: '150px'
- },
+ ...MyLoginZoidComponentDef,
// The background overlay
-
containerTemplate: ({ uid, tag, context, focus, close, doc }) => {
function closeComponent(event) {
diff --git a/demo/common/LoginZoidComponentDef.js b/demo/common/LoginZoidComponentDef.js
new file mode 100644
index 00000000..6dd461d8
--- /dev/null
+++ b/demo/common/LoginZoidComponentDef.js
@@ -0,0 +1,16 @@
+const MyLoginZoidComponentDef = {
+ // The html tag used to render my component
+ tag: 'my-login-component',
+ // The url that will be loaded in the iframe or popup, when someone includes my component on their page
+ url: new URL('login.htm', window.location.href).href,
+ props: {
+ prefilledEmail: {
+ type: 'string',
+ required: false
+ },
+ onLogin: {
+ type: 'function'
+ }
+ },
+ dimensions: { width: '300px', height: '150px' }
+};
\ No newline at end of file
diff --git a/demo/frameworks/angular/index.htm b/demo/frameworks/angular/index.htm
index bd6ede60..97ef7d35 100644
--- a/demo/frameworks/angular/index.htm
+++ b/demo/frameworks/angular/index.htm
@@ -7,6 +7,7 @@
+
+
diff --git a/demo/frameworks/angular/login.js b/demo/frameworks/angular/login.js
index 5145b956..df2ba601 100644
--- a/demo/frameworks/angular/login.js
+++ b/demo/frameworks/angular/login.js
@@ -1,11 +1,2 @@
-window.MyLoginZoidComponent = zoid.create({
-
- // The html tag used to render my component
-
- tag: 'my-login-component',
-
- // The url that will be loaded in the iframe or popup, when someone includes my component on their page
-
- url: new URL('login.htm', window.location.href).href
-});
+window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef);
diff --git a/demo/frameworks/angular2/index.htm b/demo/frameworks/angular2/index.htm
index 4fcdcbd1..c61f45d6 100644
--- a/demo/frameworks/angular2/index.htm
+++ b/demo/frameworks/angular2/index.htm
@@ -12,6 +12,7 @@
+
diff --git a/demo/frameworks/angular2/login.htm b/demo/frameworks/angular2/login.htm
index 67ba1502..9ea25fd6 100644
--- a/demo/frameworks/angular2/login.htm
+++ b/demo/frameworks/angular2/login.htm
@@ -7,6 +7,7 @@
+
diff --git a/demo/frameworks/angular2/login.js b/demo/frameworks/angular2/login.js
index 5145b956..df2ba601 100644
--- a/demo/frameworks/angular2/login.js
+++ b/demo/frameworks/angular2/login.js
@@ -1,11 +1,2 @@
-window.MyLoginZoidComponent = zoid.create({
-
- // The html tag used to render my component
-
- tag: 'my-login-component',
-
- // The url that will be loaded in the iframe or popup, when someone includes my component on their page
-
- url: new URL('login.htm', window.location.href).href
-});
+window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef);
diff --git a/demo/frameworks/angular2_TypeScript/config.js b/demo/frameworks/angular2_TypeScript/config.js
index c34f7c03..13baac7b 100644
--- a/demo/frameworks/angular2_TypeScript/config.js
+++ b/demo/frameworks/angular2_TypeScript/config.js
@@ -12,12 +12,12 @@ System.config({
map: {
'app': './',
- '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
- '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
- '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
- '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
- '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
- 'rxjs': 'npm:rxjs',
+ '@angular/core': 'npm:@angular/core@2/bundles/core.umd.js',
+ '@angular/common': 'npm:@angular/common@2/bundles/common.umd.js',
+ '@angular/compiler': 'npm:@angular/compiler@2/bundles/compiler.umd.js',
+ '@angular/platform-browser': 'npm:@angular/platform-browser@2/bundles/platform-browser.umd.js',
+ '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic@2/bundles/platform-browser-dynamic.umd.js',
+ 'rxjs': 'npm:rxjs@5.0.0',
'typescript': 'npm:typescript@2.2.1/lib/typescript.js'
},
// packages defines our app package
diff --git a/demo/frameworks/angular2_TypeScript/index.htm b/demo/frameworks/angular2_TypeScript/index.htm
index c7c66b44..6d82ff79 100644
--- a/demo/frameworks/angular2_TypeScript/index.htm
+++ b/demo/frameworks/angular2_TypeScript/index.htm
@@ -12,8 +12,9 @@
-
+
+
+
diff --git a/demo/frameworks/angular2_TypeScript/login.js b/demo/frameworks/angular2_TypeScript/login.js
index 080226bc..df2ba601 100644
--- a/demo/frameworks/angular2_TypeScript/login.js
+++ b/demo/frameworks/angular2_TypeScript/login.js
@@ -1,24 +1,2 @@
-window.MyLoginZoidComponent = zoid.create({
-
- // The html tag used to render my component
-
- tag: 'my-login-component',
-
- // The url that will be loaded in the iframe or popup, when someone includes my component on their page
-
- url: new URL('login.htm', window.location.href).href,
-
- props: {
-
- prefilledEmail: {
- type: 'string',
- required: false
- },
-
- onLogin: {
- type: 'function',
- required: true
- }
- }
-});
+window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef);
diff --git a/demo/frameworks/react/index.htm b/demo/frameworks/react/index.htm
index 81c36912..e751157e 100644
--- a/demo/frameworks/react/index.htm
+++ b/demo/frameworks/react/index.htm
@@ -9,6 +9,7 @@
+
diff --git a/demo/frameworks/react/login.htm b/demo/frameworks/react/login.htm
index 67ba1502..9ea25fd6 100644
--- a/demo/frameworks/react/login.htm
+++ b/demo/frameworks/react/login.htm
@@ -7,6 +7,7 @@
+
diff --git a/demo/frameworks/react/login.js b/demo/frameworks/react/login.js
index 5145b956..df2ba601 100644
--- a/demo/frameworks/react/login.js
+++ b/demo/frameworks/react/login.js
@@ -1,11 +1,2 @@
-window.MyLoginZoidComponent = zoid.create({
-
- // The html tag used to render my component
-
- tag: 'my-login-component',
-
- // The url that will be loaded in the iframe or popup, when someone includes my component on their page
-
- url: new URL('login.htm', window.location.href).href
-});
+window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef);
diff --git a/demo/frameworks/vue/index.htm b/demo/frameworks/vue/index.htm
index 770642ef..9b5b6678 100644
--- a/demo/frameworks/vue/index.htm
+++ b/demo/frameworks/vue/index.htm
@@ -6,8 +6,9 @@
-
+
+
diff --git a/demo/frameworks/vue/login.htm b/demo/frameworks/vue/login.htm
index 499205b8..991788de 100644
--- a/demo/frameworks/vue/login.htm
+++ b/demo/frameworks/vue/login.htm
@@ -7,6 +7,7 @@
+
diff --git a/demo/frameworks/vue/login.js b/demo/frameworks/vue/login.js
index 891e42b6..df2ba601 100644
--- a/demo/frameworks/vue/login.js
+++ b/demo/frameworks/vue/login.js
@@ -1,12 +1,2 @@
-window.MyLoginZoidComponent = zoid.create({
-
- // The html tag used to render my component
-
- tag: 'my-login-component',
-
- // The url that will be loaded in the iframe or popup, when someone includes my component on their page
-
- url: new URL('login.htm', window.location.href).href
-});
-
+window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef);
diff --git a/demo/frameworks/vue3/index.htm b/demo/frameworks/vue3/index.htm
index e2660bdf..fcf25801 100644
--- a/demo/frameworks/vue3/index.htm
+++ b/demo/frameworks/vue3/index.htm
@@ -9,6 +9,7 @@
+
diff --git a/demo/frameworks/vue3/login.htm b/demo/frameworks/vue3/login.htm
index f64b85e1..66c2d62c 100644
--- a/demo/frameworks/vue3/login.htm
+++ b/demo/frameworks/vue3/login.htm
@@ -8,6 +8,7 @@
+
diff --git a/demo/frameworks/vue3/login.js b/demo/frameworks/vue3/login.js
index 891e42b6..df2ba601 100644
--- a/demo/frameworks/vue3/login.js
+++ b/demo/frameworks/vue3/login.js
@@ -1,12 +1,2 @@
-window.MyLoginZoidComponent = zoid.create({
-
- // The html tag used to render my component
-
- tag: 'my-login-component',
-
- // The url that will be loaded in the iframe or popup, when someone includes my component on their page
-
- url: new URL('login.htm', window.location.href).href
-});
-
+window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef);
diff --git a/dist/zoid.frame.js b/dist/zoid.frame.js
index 1a18a844..8726446e 100644
--- a/dist/zoid.frame.js
+++ b/dist/zoid.frame.js
@@ -423,6 +423,10 @@
function isRegex(item) {
return "[object RegExp]" === {}.toString.call(item);
}
+ var WINDOW_TYPE = {
+ IFRAME: "iframe",
+ POPUP: "popup"
+ };
var IE_WIN_ACCESS_ERROR = "Call was rejected by callee.\r\n";
function getActualProtocol(win) {
void 0 === win && (win = window);
@@ -646,6 +650,21 @@
}
return !1;
}
+ function getFrameByName(win, name) {
+ var winFrames = getFrames(win);
+ for (var _i9 = 0; _i9 < winFrames.length; _i9++) {
+ var childFrame = winFrames[_i9];
+ try {
+ if (isSameDomain(childFrame) && childFrame.name === name && -1 !== winFrames.indexOf(childFrame)) return childFrame;
+ } catch (err) {}
+ }
+ try {
+ if (-1 !== winFrames.indexOf(win.frames[name])) return win.frames[name];
+ } catch (err) {}
+ try {
+ if (-1 !== winFrames.indexOf(win[name])) return win[name];
+ } catch (err) {}
+ }
function getAncestor(win) {
void 0 === win && (win = window);
return getOpener(win = win || window) || utils_getParent(win) || void 0;
@@ -657,6 +676,27 @@
}
return !1;
}
+ function getDistanceFromTop(win) {
+ void 0 === win && (win = window);
+ var distance = 0;
+ var parent = win;
+ for (;parent; ) (parent = utils_getParent(parent)) && (distance += 1);
+ return distance;
+ }
+ function isSameTopWindow(win1, win2) {
+ var top1 = getTop(win1) || win1;
+ var top2 = getTop(win2) || win2;
+ try {
+ if (top1 && top2) return top1 === top2;
+ } catch (err) {}
+ var allFrames1 = getAllFramesInWindow(win1);
+ var allFrames2 = getAllFramesInWindow(win2);
+ if (anyMatch(allFrames1, allFrames2)) return !0;
+ var opener1 = getOpener(top1);
+ var opener2 = getOpener(top2);
+ return opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2) || opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1),
+ !1;
+ }
function matchDomain(pattern, origin) {
if ("string" == typeof pattern) {
if ("string" == typeof origin) return "*" === pattern || origin === pattern;
@@ -667,6 +707,29 @@
return matchDomain(subpattern, origin);
})));
}
+ function getDomainFromUrl(url) {
+ return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : getDomain();
+ }
+ function onCloseWindow(win, callback, delay, maxtime) {
+ void 0 === delay && (delay = 1e3);
+ void 0 === maxtime && (maxtime = 1 / 0);
+ var timeout;
+ !function check() {
+ if (isWindowClosed(win)) {
+ timeout && clearTimeout(timeout);
+ return callback();
+ }
+ if (maxtime <= 0) clearTimeout(timeout); else {
+ maxtime -= delay;
+ timeout = setTimeout(check, delay);
+ }
+ }();
+ return {
+ cancel: function() {
+ timeout && clearTimeout(timeout);
+ }
+ };
+ }
function isWindow(obj) {
try {
if (obj === window) return !0;
@@ -1688,7 +1751,7 @@
}));
var windowTypePromise = winPromise.then((function(window) {
if (isWindowClosed(window)) throw new Error("Window is closed, can not determine type");
- return getOpener(window) ? "popup" : "iframe";
+ return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME;
}));
windowNamePromise.catch(src_util_noop);
windowTypePromise.catch(src_util_noop);
@@ -1806,7 +1869,7 @@
};
_proto.isPopup = function() {
return this.getType().then((function(type) {
- return "popup" === type;
+ return type === WINDOW_TYPE.POPUP;
}));
};
_proto.setLocation = function(href, opts) {
@@ -2149,20 +2212,7 @@
return (win = win || window).navigator.mockUserAgent || win.navigator.userAgent;
}(window).match(/MSIE|rv:11|trident|edge\/12|edge\/13/i)) throw new Error("Global messaging not needed for browser");
if (!isSameDomain(win)) throw new Error("Post message through global disabled between different domain windows");
- if (!1 !== function(win1, win2) {
- var top1 = getTop(win1) || win1;
- var top2 = getTop(win2) || win2;
- try {
- if (top1 && top2) return top1 === top2;
- } catch (err) {}
- var allFrames1 = getAllFramesInWindow(win1);
- var allFrames2 = getAllFramesInWindow(win2);
- if (anyMatch(allFrames1, allFrames2)) return !0;
- var opener1 = getOpener(top1);
- var opener2 = getOpener(top2);
- return opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2) || opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1),
- !1;
- }(window, win)) throw new Error("Can only use global to communicate between two different windows, not between frames");
+ if (!1 !== isSameTopWindow(window, win)) throw new Error("Can only use global to communicate between two different windows, not between frames");
var foreignGlobal = global_getGlobal(win);
if (!foreignGlobal) throw new Error("Can not find postRobot global on foreign window");
foreignGlobal.receiveMessage({
@@ -2600,342 +2650,10 @@
send: send_send
});
}
- function src_util_isRegex(item) {
- return "[object RegExp]" === {}.toString.call(item);
- }
- function utils_getActualProtocol(win) {
- void 0 === win && (win = window);
- return win.location.protocol;
- }
- function utils_getProtocol(win) {
- void 0 === win && (win = window);
- if (win.mockDomain) {
- var protocol = win.mockDomain.split("//")[0];
- if (protocol) return protocol;
- }
- return utils_getActualProtocol(win);
- }
- function utils_isAboutProtocol(win) {
- void 0 === win && (win = window);
- return "about:" === utils_getProtocol(win);
- }
- function src_utils_getParent(win) {
- void 0 === win && (win = window);
- if (win) try {
- if (win.parent && win.parent !== win) return win.parent;
- } catch (err) {}
- }
- function utils_getOpener(win) {
- void 0 === win && (win = window);
- if (win && !src_utils_getParent(win)) try {
- return win.opener;
- } catch (err) {}
- }
- function utils_canReadFromWindow(win) {
- try {
- return !0;
- } catch (err) {}
- return !1;
- }
- function utils_getActualDomain(win) {
- void 0 === win && (win = window);
- var location = win.location;
- if (!location) throw new Error("Can not read window location");
- var protocol = utils_getActualProtocol(win);
- if (!protocol) throw new Error("Can not read window protocol");
- if ("file:" === protocol) return "file://";
- if ("about:" === protocol) {
- var parent = src_utils_getParent(win);
- return parent && utils_canReadFromWindow() ? utils_getActualDomain(parent) : "about://";
- }
- var host = location.host;
- if (!host) throw new Error("Can not read window host");
- return protocol + "//" + host;
- }
- function utils_getDomain(win) {
- void 0 === win && (win = window);
- var domain = utils_getActualDomain(win);
- return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain;
- }
- function utils_isSameDomain(win) {
- if (!function(win) {
- try {
- if (win === window) return !0;
- } catch (err) {}
- try {
- var desc = Object.getOwnPropertyDescriptor(win, "location");
- if (desc && !1 === desc.enumerable) return !1;
- } catch (err) {}
- try {
- if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0;
- } catch (err) {}
- try {
- if (function(win) {
- void 0 === win && (win = window);
- return "mock:" === utils_getProtocol(win);
- }(win) && utils_canReadFromWindow()) return !0;
- } catch (err) {}
- try {
- if (utils_getActualDomain(win) === utils_getActualDomain(window)) return !0;
- } catch (err) {}
- return !1;
- }(win)) return !1;
- try {
- if (win === window) return !0;
- if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0;
- if (utils_getDomain(window) === utils_getDomain(win)) return !0;
- } catch (err) {}
- return !1;
- }
- function utils_assertSameDomain(win) {
- if (!utils_isSameDomain(win)) throw new Error("Expected window to be same domain");
- return win;
- }
- function utils_isAncestorParent(parent, child) {
- if (!parent || !child) return !1;
- var childParent = src_utils_getParent(child);
- return childParent ? childParent === parent : -1 !== function(win) {
- var result = [];
- try {
- for (;win.parent !== win; ) {
- result.push(win.parent);
- win = win.parent;
- }
- } catch (err) {}
- return result;
- }(child).indexOf(parent);
- }
- function utils_getFrames(win) {
- var result = [];
- var frames;
- try {
- frames = win.frames;
- } catch (err) {
- frames = win;
- }
- var len;
- try {
- len = frames.length;
- } catch (err) {}
- if (0 === len) return result;
- if (len) {
- for (var i = 0; i < len; i++) {
- var frame = void 0;
- try {
- frame = frames[i];
- } catch (err) {
- continue;
- }
- result.push(frame);
- }
- return result;
- }
- for (var _i = 0; _i < 100; _i++) {
- var _frame = void 0;
- try {
- _frame = frames[_i];
- } catch (err) {
- return result;
- }
- if (!_frame) return result;
- result.push(_frame);
- }
- return result;
- }
- function utils_getAllChildFrames(win) {
- var result = [];
- for (var _i3 = 0, _getFrames2 = utils_getFrames(win); _i3 < _getFrames2.length; _i3++) {
- var frame = _getFrames2[_i3];
- result.push(frame);
- for (var _i5 = 0, _getAllChildFrames2 = utils_getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) result.push(_getAllChildFrames2[_i5]);
- }
- return result;
- }
- function utils_getTop(win) {
- void 0 === win && (win = window);
- try {
- if (win.top) return win.top;
- } catch (err) {}
- if (src_utils_getParent(win) === win) return win;
- try {
- if (utils_isAncestorParent(window, win) && window.top) return window.top;
- } catch (err) {}
- try {
- if (utils_isAncestorParent(win, window) && window.top) return window.top;
- } catch (err) {}
- for (var _i7 = 0, _getAllChildFrames4 = utils_getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) {
- var frame = _getAllChildFrames4[_i7];
- try {
- if (frame.top) return frame.top;
- } catch (err) {}
- if (src_utils_getParent(frame) === frame) return frame;
- }
- }
- function utils_getAllFramesInWindow(win) {
- var top = utils_getTop(win);
- if (!top) throw new Error("Can not determine top window");
- var result = [].concat(utils_getAllChildFrames(top), [ top ]);
- -1 === result.indexOf(win) && (result = [].concat(result, [ win ], utils_getAllChildFrames(win)));
- return result;
- }
- var utils_iframeWindows = [];
- var utils_iframeFrames = [];
- function utils_isWindowClosed(win, allowMock) {
- void 0 === allowMock && (allowMock = !0);
- try {
- if (win === window) return !1;
- } catch (err) {
- return !0;
- }
- try {
- if (!win) return !0;
- } catch (err) {
- return !0;
- }
- try {
- if (win.closed) return !0;
- } catch (err) {
- return !err || "Call was rejected by callee.\r\n" !== err.message;
- }
- if (allowMock && utils_isSameDomain(win)) try {
- if (win.mockclosed) return !0;
- } catch (err) {}
- try {
- if (!win.parent || !win.top) return !0;
- } catch (err) {}
- var iframeIndex = function(collection, item) {
- for (var i = 0; i < collection.length; i++) try {
- if (collection[i] === item) return i;
- } catch (err) {}
- return -1;
- }(utils_iframeWindows, win);
- if (-1 !== iframeIndex) {
- var frame = utils_iframeFrames[iframeIndex];
- if (frame && function(frame) {
- if (!frame.contentWindow) return !0;
- if (!frame.parentNode) return !0;
- var doc = frame.ownerDocument;
- if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {
- var parent = frame;
- for (;parent.parentNode && parent.parentNode !== parent; ) parent = parent.parentNode;
- if (!parent.host || !doc.documentElement.contains(parent.host)) return !0;
- }
- return !1;
- }(frame)) return !0;
- }
- return !1;
- }
- function utils_getFrameByName(win, name) {
- var winFrames = utils_getFrames(win);
- for (var _i9 = 0; _i9 < winFrames.length; _i9++) {
- var childFrame = winFrames[_i9];
- try {
- if (utils_isSameDomain(childFrame) && childFrame.name === name && -1 !== winFrames.indexOf(childFrame)) return childFrame;
- } catch (err) {}
- }
- try {
- if (-1 !== winFrames.indexOf(win.frames[name])) return win.frames[name];
- } catch (err) {}
- try {
- if (-1 !== winFrames.indexOf(win[name])) return win[name];
- } catch (err) {}
- }
- function utils_getAncestor(win) {
- void 0 === win && (win = window);
- return utils_getOpener(win = win || window) || src_utils_getParent(win) || void 0;
- }
- function utils_anyMatch(collection1, collection2) {
- for (var _i17 = 0; _i17 < collection1.length; _i17++) {
- var item1 = collection1[_i17];
- for (var _i19 = 0; _i19 < collection2.length; _i19++) if (item1 === collection2[_i19]) return !0;
- }
- return !1;
- }
- function utils_getDistanceFromTop(win) {
- void 0 === win && (win = window);
- var distance = 0;
- var parent = win;
- for (;parent; ) (parent = src_utils_getParent(parent)) && (distance += 1);
- return distance;
- }
- function utils_matchDomain(pattern, origin) {
- if ("string" == typeof pattern) {
- if ("string" == typeof origin) return "*" === pattern || origin === pattern;
- if (src_util_isRegex(origin)) return !1;
- if (Array.isArray(origin)) return !1;
- }
- return src_util_isRegex(pattern) ? src_util_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) : !src_util_isRegex(origin) && pattern.some((function(subpattern) {
- return utils_matchDomain(subpattern, origin);
- })));
- }
- function utils_getDomainFromUrl(url) {
- return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : utils_getDomain();
- }
- function utils_onCloseWindow(win, callback, delay, maxtime) {
- void 0 === delay && (delay = 1e3);
- void 0 === maxtime && (maxtime = 1 / 0);
- var timeout;
- !function check() {
- if (utils_isWindowClosed(win)) {
- timeout && clearTimeout(timeout);
- return callback();
- }
- if (maxtime <= 0) clearTimeout(timeout); else {
- maxtime -= delay;
- timeout = setTimeout(check, delay);
- }
- }();
- return {
- cancel: function() {
- timeout && clearTimeout(timeout);
- }
- };
- }
- function utils_isWindow(obj) {
- try {
- if (obj === window) return !0;
- } catch (err) {
- if (err && "Call was rejected by callee.\r\n" === err.message) return !0;
- }
- try {
- if ("[object Window]" === {}.toString.call(obj)) return !0;
- } catch (err) {
- if (err && "Call was rejected by callee.\r\n" === err.message) return !0;
- }
- try {
- if (window.Window && obj instanceof window.Window) return !0;
- } catch (err) {
- if (err && "Call was rejected by callee.\r\n" === err.message) return !0;
- }
- try {
- if (obj && obj.self === obj) return !0;
- } catch (err) {
- if (err && "Call was rejected by callee.\r\n" === err.message) return !0;
- }
- try {
- if (obj && obj.parent === obj) return !0;
- } catch (err) {
- if (err && "Call was rejected by callee.\r\n" === err.message) return !0;
- }
- try {
- if (obj && obj.top === obj) return !0;
- } catch (err) {
- if (err && "Call was rejected by callee.\r\n" === err.message) return !0;
- }
- try {
- if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1;
- } catch (err) {
- return !0;
- }
- try {
- if ("postMessage" in obj && "self" in obj && "location" in obj) return !0;
- } catch (err) {}
- return !1;
- }
function lib_global_getGlobal(win) {
- if (!utils_isSameDomain(win)) throw new Error("Can not get global for window on different domain");
- win.__zoid_9_0_87__ || (win.__zoid_9_0_87__ = {});
- return win.__zoid_9_0_87__;
+ if (!isSameDomain(win)) throw new Error("Can not get global for window on different domain");
+ win.__zoid_9_0_88__ || (win.__zoid_9_0_88__ = {});
+ return win.__zoid_9_0_88__;
}
function tryGlobal(win, handler) {
try {
@@ -3046,10 +2764,7 @@
DOTIFY: "dotify",
BASE64: "base64"
};
- var CONTEXT = {
- IFRAME: "iframe",
- POPUP: "popup"
- };
+ var CONTEXT = WINDOW_TYPE;
var EVENT = {
RENDER: "zoid-render",
RENDERED: "zoid-rendered",
@@ -3081,7 +2796,7 @@
sender: {
win: function(_ref2) {
return function(windowRef) {
- if ("opener" === windowRef.type) return assertExists("opener", utils_getOpener(window));
+ if ("opener" === windowRef.type) return assertExists("opener", getOpener(window));
if ("parent" === windowRef.type && "number" == typeof windowRef.distance) return assertExists("parent", function(win, n) {
void 0 === n && (n = 1);
return function(win, n) {
@@ -3089,19 +2804,19 @@
var parent = win;
for (var i = 0; i < n; i++) {
if (!parent) return;
- parent = src_utils_getParent(parent);
+ parent = utils_getParent(parent);
}
return parent;
- }(win, utils_getDistanceFromTop(win) - n);
+ }(win, getDistanceFromTop(win) - n);
}(window, windowRef.distance));
if ("global" === windowRef.type && windowRef.uid && "string" == typeof windowRef.uid) {
var _ret = function() {
var uid = windowRef.uid;
- var ancestor = utils_getAncestor(window);
+ var ancestor = getAncestor(window);
if (!ancestor) throw new Error("Can not find ancestor window");
- for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) {
+ for (var _i2 = 0, _getAllFramesInWindow2 = getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) {
var frame = _getAllFramesInWindow2[_i2];
- if (utils_isSameDomain(frame)) {
+ if (isSameDomain(frame)) {
var win = tryGlobal(frame, (function(global) {
return global.windows && global.windows[uid];
}));
@@ -3115,15 +2830,15 @@
} else if ("name" === windowRef.type) {
var name = windowRef.name;
return assertExists("namedWindow", function(win, name) {
- return utils_getFrameByName(win, name) || function utils_findChildFrameByName(win, name) {
- var frame = utils_getFrameByName(win, name);
+ return getFrameByName(win, name) || function findChildFrameByName(win, name) {
+ var frame = getFrameByName(win, name);
if (frame) return frame;
- for (var _i11 = 0, _getFrames4 = utils_getFrames(win); _i11 < _getFrames4.length; _i11++) {
- var namedFrame = utils_findChildFrameByName(_getFrames4[_i11], name);
+ for (var _i11 = 0, _getFrames4 = getFrames(win); _i11 < _getFrames4.length; _i11++) {
+ var namedFrame = findChildFrameByName(_getFrames4[_i11], name);
if (namedFrame) return namedFrame;
}
- }(utils_getTop(win) || win, name);
- }(assertExists("ancestor", utils_getAncestor(window)), name));
+ }(getTop(win) || win, name);
+ }(assertExists("ancestor", getAncestor(window)), name));
}
throw new Error("Unable to find " + windowRef.type + " parent component window");
}(_ref2.metaData.windowRef);
@@ -3141,15 +2856,15 @@
}
function window_getWindowRef(targetWindow, currentWindow) {
void 0 === currentWindow && (currentWindow = window);
- if (targetWindow === src_utils_getParent(currentWindow)) return {
+ if (targetWindow === utils_getParent(currentWindow)) return {
type: "parent",
- distance: utils_getDistanceFromTop(targetWindow)
+ distance: getDistanceFromTop(targetWindow)
};
- if (targetWindow === utils_getOpener(currentWindow)) return {
+ if (targetWindow === getOpener(currentWindow)) return {
type: "opener"
};
- if (utils_isSameDomain(targetWindow) && !(win = targetWindow, win === utils_getTop(win))) {
- var windowName = utils_assertSameDomain(targetWindow).name;
+ if (isSameDomain(targetWindow) && !(win = targetWindow, win === getTop(win))) {
+ var windowName = assertSameDomain(targetWindow).name;
if (windowName) return {
type: "name",
name: windowName
@@ -3352,7 +3067,7 @@
for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) {
var key = _Object$keys2[_i2];
var prop = propsDef[key];
- prop && !1 === prop.sendToChild || prop && prop.sameDomain && !utils_matchDomain(initialChildDomain, utils_getDomain(window)) || (result[key] = props[key]);
+ prop && !1 === prop.sendToChild || prop && prop.sameDomain && !matchDomain(initialChildDomain, getDomain(window)) || (result[key] = props[key]);
}
return promise_ZalgoPromise.hash(result);
};
@@ -3413,7 +3128,7 @@
}) : attributes;
};
var getInitialChildDomain = function() {
- return utils_getDomainFromUrl(getUrl());
+ return getDomainFromUrl(getUrl());
};
var openFrame = function(context, _ref2) {
var windowName = _ref2.windowName;
@@ -3447,7 +3162,7 @@
return destroyElement(prerenderFrame);
}));
return awaitFrameWindow(prerenderFrame).then((function(prerenderFrameWindow) {
- return utils_assertSameDomain(prerenderFrameWindow);
+ return assertSameDomain(prerenderFrameWindow);
})).then((function(win) {
return setup_toProxyWindow(win);
}));
@@ -3471,7 +3186,7 @@
return uid;
};
var getWindowRef = function(target, initialChildDomain, context, proxyWin) {
- if (initialChildDomain === utils_getDomain(window)) return {
+ if (initialChildDomain === getDomain(window)) return {
type: "global",
uid: getCurrentWindowReferenceUID()
};
@@ -3479,14 +3194,14 @@
if (props.window) {
var actualComponentWindow = proxyWin.getWindow();
if (!actualComponentWindow) throw new Error("Can not construct cross-domain window reference for lazy window prop");
- if (utils_getAncestor(actualComponentWindow) !== window) throw new Error("Can not construct cross-domain window reference for window prop with different ancestor");
+ if (getAncestor(actualComponentWindow) !== window) throw new Error("Can not construct cross-domain window reference for window prop with different ancestor");
}
if (context === CONTEXT.POPUP) return {
type: "opener"
};
if (context === CONTEXT.IFRAME) return {
type: "parent",
- distance: utils_getDistanceFromTop(window)
+ distance: getDistanceFromTop(window)
};
throw new Error("Can not construct window reference for child");
};
@@ -3521,7 +3236,7 @@
var close = memoize((function(err) {
return promise_ZalgoPromise.try((function() {
if (closeOverride) {
- if (utils_isWindowClosed(closeOverride.__source__)) return;
+ if (isWindowClosed(closeOverride.__source__)) return;
return closeOverride();
}
return promise_ZalgoPromise.try((function() {
@@ -3569,7 +3284,7 @@
var unloadWindowListener = addEventListener(window, "unload", once((function() {
destroy(new Error("Window navigated away"));
})));
- var closeParentWindowListener = utils_onCloseWindow(parentWin, destroy, 3e3);
+ var closeParentWindowListener = onCloseWindow(parentWin, destroy, 3e3);
clean.register(closeParentWindowListener.cancel);
clean.register(unloadWindowListener.cancel);
if (watchForUnloadOverride) return watchForUnloadOverride();
@@ -3636,14 +3351,14 @@
}) : promise_ZalgoPromise.try((function() {
if (prerenderTemplate) {
var prerenderWindow = proxyPrerenderWin.getWindow();
- if (prerenderWindow && utils_isSameDomain(prerenderWindow) && function(win) {
+ if (prerenderWindow && isSameDomain(prerenderWindow) && function(win) {
try {
if (!win.location.href) return !0;
if ("about:blank" === win.location.href) return !0;
} catch (err) {}
return !1;
}(prerenderWindow)) {
- var doc = (prerenderWindow = utils_assertSameDomain(prerenderWindow)).document;
+ var doc = (prerenderWindow = assertSameDomain(prerenderWindow)).document;
var el = renderTemplate(prerenderTemplate, {
context: context,
doc: doc
@@ -3927,22 +3642,9 @@
var childDomainMatch = domainMatch || getInitialChildDomain();
!function(target, childDomainMatch, container) {
if (target !== window) {
- if (!function(win1, win2) {
- var top1 = utils_getTop(win1) || win1;
- var top2 = utils_getTop(win2) || win2;
- try {
- if (top1 && top2) return top1 === top2;
- } catch (err) {}
- var allFrames1 = utils_getAllFramesInWindow(win1);
- var allFrames2 = utils_getAllFramesInWindow(win2);
- if (utils_anyMatch(allFrames1, allFrames2)) return !0;
- var opener1 = utils_getOpener(top1);
- var opener2 = utils_getOpener(top2);
- return opener1 && utils_anyMatch(utils_getAllFramesInWindow(opener1), allFrames2) || opener2 && utils_anyMatch(utils_getAllFramesInWindow(opener2), allFrames1),
- !1;
- }(window, target)) throw new Error("Can only renderTo an adjacent frame");
- var origin = utils_getDomain();
- if (!utils_matchDomain(childDomainMatch, origin) && !utils_isSameDomain(target)) throw new Error("Can not render remotely to " + childDomainMatch.toString() + " - can only render to " + origin);
+ if (!isSameTopWindow(window, target)) throw new Error("Can only renderTo an adjacent frame");
+ var origin = getDomain();
+ if (!matchDomain(childDomainMatch, origin) && !isSameDomain(target)) throw new Error("Can not render remotely to " + childDomainMatch.toString() + " - can only render to " + origin);
if (container && "string" != typeof container) throw new Error("Container passed to renderTo must be a string selector, got " + typeof container + " }");
}
}(target, childDomainMatch, container);
@@ -3969,7 +3671,7 @@
}).then((function(_ref13) {
var parentComp = _ref13.data.parent;
clean.register((function(err) {
- if (!utils_isWindowClosed(target)) return parentComp.destroy(err);
+ if (!isWindowClosed(target)) return parentComp.destroy(err);
}));
return parentComp.getDelegateOverrides();
})).catch((function(err) {
@@ -4072,7 +3774,7 @@
hashString && (originalUrl = originalUrl + "#" + hashString);
return originalUrl;
}(function(url) {
- if (!(domain = utils_getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url;
+ if (!(domain = getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url;
var domain;
throw new Error("Mock urls not supported out of test mode");
}(getUrl()), {
@@ -4091,7 +3793,7 @@
context: context,
tag: tag,
childDomainMatch: childDomainMatch,
- version: "9_0_87",
+ version: "9_0_88",
props: childProps,
exports: (win = proxyWin, {
init: function(childExports) {
@@ -4122,13 +3824,13 @@
windowRef: getWindowRef(target, initialChildDomain, context, proxyWin)
},
sender: {
- domain: utils_getDomain(window)
+ domain: getDomain(window)
},
receiver: {
win: proxyWin,
domain: childDomainMatch
},
- passByReference: initialChildDomain === utils_getDomain()
+ passByReference: initialChildDomain === getDomain()
}), serializedData = _crossDomainSerialize.serializedData;
clean.register(_crossDomainSerialize.cleanReference);
return serializedData;
@@ -4375,10 +4077,10 @@
allowDelegate: !0,
validate: function(_ref2) {
var value = _ref2.value;
- if (!utils_isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error("Expected Window or ProxyWindow");
- if (utils_isWindow(value)) {
- if (utils_isWindowClosed(value)) throw new Error("Window is closed");
- if (!utils_isSameDomain(value)) throw new Error("Window is not same domain");
+ if (!isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error("Expected Window or ProxyWindow");
+ if (isWindow(value)) {
+ if (isWindowClosed(value)) throw new Error("Window is closed");
+ if (!isSameDomain(value)) throw new Error("Window is not same domain");
}
},
decorate: function(_ref3) {
@@ -4394,6 +4096,10 @@
type: PROP_TYPE.STRING,
required: !1
},
+ context: {
+ type: PROP_TYPE.STRING,
+ required: !1
+ },
onDisplay: {
type: PROP_TYPE.FUNCTION,
required: !1,
@@ -4603,7 +4309,7 @@
return !1;
}(name)) {
var _payload = getInitialParentPayload().payload;
- if (_payload.tag === tag && utils_matchDomain(_payload.childDomainMatch, utils_getDomain())) return !0;
+ if (_payload.tag === tag && matchDomain(_payload.childDomainMatch, getDomain())) return !0;
}
return !1;
};
@@ -4621,7 +4327,7 @@
var props;
var exportsPromise = new promise_ZalgoPromise;
var version = payload.version, uid = payload.uid, parentExports = payload.exports, context = payload.context, initialProps = payload.props;
- if ("9_0_87" !== version) throw new Error("Parent window has zoid version " + version + ", child window has version 9_0_87");
+ if ("9_0_88" !== version) throw new Error("Parent window has zoid version " + version + ", child window has version 9_0_88");
var show = parentExports.show, hide = parentExports.hide, close = parentExports.close, onError = parentExports.onError, checkClose = parentExports.checkClose, parentExport = parentExports.export, parentResize = parentExports.resize, parentInit = parentExports.init;
var getParent = function() {
return parentComponentWindow;
@@ -4653,10 +4359,10 @@
var currentParent = props.parent;
void 0 === anyParent && (anyParent = !currentParent);
if (!anyParent && !currentParent) throw new Error("No parent found for " + tag + " child");
- for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(window); _i2 < _getAllFramesInWindow2.length; _i2++) {
+ for (var _i2 = 0, _getAllFramesInWindow2 = getAllFramesInWindow(window); _i2 < _getAllFramesInWindow2.length; _i2++) {
var win = _getAllFramesInWindow2[_i2];
- if (utils_isSameDomain(win)) {
- var xprops = utils_assertSameDomain(win).xprops;
+ if (isSameDomain(win)) {
+ var xprops = assertSameDomain(win).xprops;
if (xprops && getParent() === xprops.getParent()) {
var winParent = xprops.parent;
if (anyParent || !currentParent || winParent && winParent.uid === currentParent.uid) {
@@ -4681,7 +4387,7 @@
for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) {
var key = _Object$keys2[_i2];
var prop = propsDef[key];
- if (!prop || !prop.sameDomain || origin === utils_getDomain(window) && utils_isSameDomain(parentComponentWindow)) {
+ if (!prop || !prop.sameDomain || origin === getDomain(window) && isSameDomain(parentComponentWindow)) {
var value = normalizeChildProp(propsDef, 0, key, props[key], helpers);
result[key] = value;
prop && prop.alias && !result[prop.alias] && (result[prop.alias] = value);
@@ -4718,7 +4424,7 @@
return {
init: function() {
return promise_ZalgoPromise.try((function() {
- utils_isSameDomain(parentComponentWindow) && function(_ref3) {
+ isSameDomain(parentComponentWindow) && function(_ref3) {
var componentName = _ref3.componentName, parentComponentWindow = _ref3.parentComponentWindow;
var _crossDomainDeseriali2 = crossDomainDeserialize({
data: parseWindowName(window.name).serializedInitialPayload,
@@ -4738,7 +4444,7 @@
},
receiver: {
win: window,
- domain: utils_getDomain()
+ domain: getDomain()
},
basic: !0
});
@@ -4757,7 +4463,7 @@
}
});
!function(allowedParentDomains, domain) {
- if (!utils_matchDomain(allowedParentDomains, domain)) throw new Error("Can not be rendered by domain: " + domain);
+ if (!matchDomain(allowedParentDomains, domain)) throw new Error("Can not be rendered by domain: " + domain);
}(allowedParentDomains, parentDomain);
markWindowKnown(parentComponentWindow);
!function() {
@@ -4767,7 +4473,7 @@
window.addEventListener("unload", (function() {
checkClose.fireAndForget();
}));
- utils_onCloseWindow(parentComponentWindow, (function() {
+ onCloseWindow(parentComponentWindow, (function() {
child_destroy();
}));
}();
@@ -4868,7 +4574,7 @@
throw err;
}));
}
- if (!utils_isWindow(target)) throw new Error("Must pass window to renderTo");
+ if (!isWindow(target)) throw new Error("Must pass window to renderTo");
return function(props, context) {
return promise_ZalgoPromise.try((function() {
if (props.window) return setup_toProxyWindow(props.window).getType();
@@ -5053,7 +4759,7 @@
var destroyAll = destroyComponents;
function component_destroy(err) {
destroyAll();
- delete window.__zoid_9_0_87__;
+ delete window.__zoid_9_0_88__;
!function() {
!function() {
var responseListeners = globalStore("responseListeners");
diff --git a/dist/zoid.frame.min.js b/dist/zoid.frame.min.js
index 7d619054..b478b6fa 100644
--- a/dist/zoid.frame.min.js
+++ b/dist/zoid.frame.min.js
@@ -1,2 +1,2 @@
-!function(n,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("zoid",[],e):"object"==typeof exports?exports.zoid=e():n.zoid=e()}("undefined"!=typeof self?self:this,(function(){return function(n){var e={};function r(t){if(e[t])return e[t].exports;var o=e[t]={i:t,l:!1,exports:{}};return n[t].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=n,r.c=e,r.d=function(n,e,t){r.o(n,e)||Object.defineProperty(n,e,{enumerable:!0,get:t})},r.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,e){if(1&e&&(n=r(n)),8&e)return n;if(4&e&&"object"==typeof n&&n&&n.__esModule)return n;var t=Object.create(null);if(r.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:n}),2&e&&"string"!=typeof n)for(var o in n)r.d(t,o,function(e){return n[e]}.bind(null,o));return t},r.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(e,"a",e),e},r.o=function(n,e){return{}.hasOwnProperty.call(n,e)},r.p="",r(r.s=0)}([function(n,e,r){"use strict";function t(n,e){return(t=Object.setPrototypeOf||function(n,e){return n.__proto__=e,n})(n,e)}function o(n,e){n.prototype=Object.create(e.prototype),n.prototype.constructor=n,t(n,e)}function i(){return(i=Object.assign||function(n){for(var e=1;e>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var n=new WeakMap,e={};return Object.freeze(e),n.set(e,"__testvalue__"),"__testvalue__"===n.get(e)}catch(n){return!1}}())try{this.weakmap=new WeakMap}catch(n){}this.keys=[],this.values=[]}var e=n.prototype;return e._cleanupClosedWindows=function(){for(var n=this.weakmap,e=this.keys,r=0;r=3)return"stringifyError stack overflow";try{if(!n)return"";if("string"==typeof n)return n;if(n instanceof Error){var r=n&&n.stack,t=n&&n.message;if(r&&t)return-1!==r.indexOf(t)?r:t+"\n"+r;if(r)return r;if(t)return t}return n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}catch(n){return"Error while stringifying error: "+cn(n,e+1)}}function fn(n){return"string"==typeof n?n:n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}function sn(n,e){if(!e)return n;if(Object.assign)return Object.assign(n,e);for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n}function dn(n){return n}function ln(n,e){var r;return function t(){r=setTimeout((function(){n(),t()}),e)}(),{cancel:function(){clearTimeout(r)}}}function hn(n){return[].slice.call(n)}function wn(n){return null!=n}function pn(n){return"[object RegExp]"==={}.toString.call(n)}function vn(n,e,r){if(n.hasOwnProperty(e))return n[e];var t=r();return n[e]=t,t}function mn(n){var e,r=[],t=!1,o={set:function(e,r){return t||(n[e]=r,o.register((function(){delete n[e]}))),r},register:function(n){var o=un((function(){return n(e)}));return t?n(e):r.push(o),{cancel:function(){var n=r.indexOf(o);-1!==n&&r.splice(n,1)}}},all:function(n){e=n;var o=[];for(t=!0;r.length;){var i=r.shift();o.push(i())}return w.all(o).then(an)}};return o}function yn(n,e){if(null==e)throw new Error("Expected "+n+" to be present");return e}tn.clear=function(){rn=en},tn((function(n){if(Object.values)return Object.values(n);var e=[];for(var r in n)n.hasOwnProperty(r)&&e.push(n[r]);return e}));var gn=function(n){function e(e){var r;return(r=n.call(this,e)||this).name=r.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(n){if(void 0===n)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return n}(r),r.constructor):r.stack=new Error(e).stack,r}return o(e,n),e}(Z(Error));function bn(){var n=document.body;if(!n)throw new Error("Body element not found");return n}function En(){return Boolean(document.body)&&"complete"===document.readyState}function _n(){return Boolean(document.body)&&"interactive"===document.readyState}function xn(n){return encodeURIComponent(n)}function Pn(n){return function(e,r,t){void 0===t&&(t=[]);var o=e.__inline_memoize_cache__=e.__inline_memoize_cache__||{},i=Q(t);return o.hasOwnProperty(i)?o[i]:o[i]=function(){var e={};if(!n)return e;if(-1===n.indexOf("="))return e;for(var r=0,t=n.split("&");r { ... }":"<"+typeof n+">"})).join(", ")+") failed\n\n")+n.stack),n}))})).then((function(n){return{result:n,id:o,name:i}}))}))}));var c=r.__id__||K();n=we.unwrap(n);var f=r.__name__||r.name||t;return"string"==typeof f&&"function"==typeof f.indexOf&&0===f.indexOf("anonymous::")&&(f=f.replace("anonymous::",t+"::")),we.isProxyWindow(n)?(pe(c,r,f,n,e),n.awaitWindow().then((function(n){pe(c,r,f,n,e)}))):pe(c,r,f,n,e),ae("cross_domain_function",{id:c,name:f})}function ye(n,e,r,t){var o,i=t.on,a=t.send;return function(n,e){void 0===e&&(e=fe);var r=JSON.stringify(n,(function(n){var r=this[n];if(oe(this))return r;var t=ie(r);if(!t)return r;var o=e[t]||ce[t];return o?o(r,n):r}));return void 0===r?"undefined":r}(r,((o={}).promise=function(r,t){return function(n,e,r,t,o){return ae("cross_domain_zalgo_promise",{then:me(n,e,(function(n,e){return r.then(n,e)}),t,{on:o.on,send:o.send})})}(n,e,r,t,{on:i,send:a})},o.function=function(r,t){return me(n,e,r,t,{on:i,send:a})},o.object=function(n){return F(n)||we.isProxyWindow(n)?ae("cross_domain_window",we.serialize(n,{send:a})):n},o))}function ge(n,e,r,t){var o,i=t.send;return function(n,e){if(void 0===e&&(e=de),"undefined"!==n)return JSON.parse(n,(function(n,r){if(oe(this))return r;var t,o;if(oe(r)?(t=r.__type__,o=r.__val__):(t=ie(r),o=r),!t)return o;var i=e[t]||se[t];return i?i(o,n):o}))}(r,((o={}).cross_domain_zalgo_promise=function(n){return function(n,e,r){return new w(r.then)}(0,0,n)},o.cross_domain_function=function(r){return function(n,e,r,t){var o=r.id,i=r.name,a=t.send,u=function(r){function t(){var u=arguments;return we.toProxyWindow(n,{send:a}).awaitWindow().then((function(n){var c=ve(n,o);if(c&&c.val!==t)return c.val.apply({source:window,origin:P()},u);var f=[].slice.call(u);return r.fireAndForget?a(n,"postrobot_method",{id:o,name:i,args:f},{domain:e,fireAndForget:!0}):a(n,"postrobot_method",{id:o,name:i,args:f},{domain:e,fireAndForget:!1}).then((function(n){return n.data.result}))})).catch((function(n){throw n}))}return void 0===r&&(r={}),t.__name__=i,t.__origin__=e,t.__source__=n,t.__id__=o,t.origin=e,t},c=u();return c.fireAndForget=u({fireAndForget:!0}),c}(n,e,r,{send:i})},o.cross_domain_window=function(n){return we.deserialize(n,{send:i})},o))}var be={};function Ee(n,e,r,t){var o=t.on,i=t.send;return w.try((function(){var t=Kn().getOrSet(n,(function(){return{}}));return t.buffer=t.buffer||[],t.buffer.push(r),t.flush=t.flush||w.flush().then((function(){if(T(n))throw new Error("Window is closed");var r,a=ye(n,e,((r={}).__post_robot_10_0_46__=t.buffer||[],r),{on:o,send:i});delete t.buffer;for(var u=Object.keys(be),c=[],f=0;f1?e-1:0),o=1;o1?r-1:0),i=1;i iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #"+e+" > iframe.zoid-invisible {\n opacity: 0;\n }\n\n #"+e+" > iframe.zoid-visible {\n opacity: 1;\n }\n ")),s.appendChild(r),s.appendChild(t),s.appendChild(d),t.classList.add("zoid-visible"),r.classList.add("zoid-invisible"),a.on(vr.RENDERED,(function(){t.classList.remove("zoid-visible"),t.classList.add("zoid-invisible"),r.classList.remove("zoid-invisible"),r.classList.add("zoid-visible"),setTimeout((function(){zn(t)}),1)})),a.on(vr.RESIZE,(function(n){var e=n.width,r=n.height;"number"==typeof e&&(s.style.width=Hn(e)),"number"==typeof r&&(s.style.height=Hn(r))})),s}}var jr=mn(),Rr=mn();function Ar(n){var e,r,t=function(n){var e=n.tag,r=n.url,t=n.domain,o=n.bridgeUrl,a=n.props,u=void 0===a?{}:a,c=n.dimensions,f=void 0===c?{}:c,s=n.autoResize,d=void 0===s?{}:s,l=n.allowedParentDomains,h=void 0===l?"*":l,w=n.attributes,p=void 0===w?{}:w,v=n.defaultContext,m=void 0===v?pr.IFRAME:v,y=n.containerTemplate,g=void 0===y?Nr:y,b=n.prerenderTemplate,E=void 0===b?null:b,_=n.validate,x=n.eligible,P=void 0===x?function(){return{eligible:!0}}:x,O=n.logger,C=void 0===O?{info:an}:O,W=n.exports,D=void 0===W?an:W,S=n.method,N=n.children,j=void 0===N?function(){return{}}:N,R=e.replace(/-/g,"_"),A=i({},{window:{type:hr.OBJECT,sendToChild:!1,required:!1,allowDelegate:!0,validate:function(n){var e=n.value;if(!ir(e)&&!we.isProxyWindow(e))throw new Error("Expected Window or ProxyWindow");if(ir(e)){if(Xe(e))throw new Error("Window is closed");if(!qe(e))throw new Error("Window is not same domain")}},decorate:function(n){return Re(n.value)}},timeout:{type:hr.NUMBER,required:!1,sendToChild:!1},cspNonce:{type:hr.STRING,required:!1},onDisplay:{type:hr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Or,decorate:Cr},onRendered:{type:hr.FUNCTION,required:!1,sendToChild:!1,default:Or,decorate:Cr},onRender:{type:hr.FUNCTION,required:!1,sendToChild:!1,default:Or,decorate:Cr},onClose:{type:hr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Or,decorate:Cr},onDestroy:{type:hr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Or,decorate:Cr},onResize:{type:hr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Or},onFocus:{type:hr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Or},close:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.close}},focus:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.focus}},resize:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.resize}},uid:{type:hr.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.uid}},tag:{type:hr.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.tag}},getParent:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParent}},getParentDomain:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParentDomain}},show:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.show}},hide:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.hide}},export:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.export}},onError:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onError}},onProps:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onProps}},getSiblings:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getSiblings}}},u);if(!g)throw new Error("Container template required");return{name:R,tag:e,url:r,domain:t,bridgeUrl:o,method:S,propsDef:A,dimensions:f,autoResize:d,allowedParentDomains:h,attributes:p,defaultContext:m,containerTemplate:g,prerenderTemplate:E,validate:_,logger:C,eligible:P,children:j,exports:"function"==typeof D?D:function(n){for(var e=n.getExports,r={},t=function(n,t){var o=t[n],i=D[o].type,a=e().then((function(n){return n[o]}));r[o]=i===hr.FUNCTION?function(){for(var n=arguments.length,e=new Array(n),r=0;r>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var n=new WeakMap,e={};return Object.freeze(e),n.set(e,"__testvalue__"),"__testvalue__"===n.get(e)}catch(n){return!1}}())try{this.weakmap=new WeakMap}catch(n){}this.keys=[],this.values=[]}var e=n.prototype;return e._cleanupClosedWindows=function(){for(var n=this.weakmap,e=this.keys,r=0;r=3)return"stringifyError stack overflow";try{if(!n)return"";if("string"==typeof n)return n;if(n instanceof Error){var r=n&&n.stack,t=n&&n.message;if(r&&t)return-1!==r.indexOf(t)?r:t+"\n"+r;if(r)return r;if(t)return t}return n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}catch(n){return"Error while stringifying error: "+wn(n,e+1)}}function pn(n){return"string"==typeof n?n:n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}function vn(n,e){if(!e)return n;if(Object.assign)return Object.assign(n,e);for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n}function mn(n){return n}function yn(n,e){var r;return function t(){r=setTimeout((function(){n(),t()}),e)}(),{cancel:function(){clearTimeout(r)}}}function gn(n){return[].slice.call(n)}function bn(n){return null!=n}function En(n){return"[object RegExp]"==={}.toString.call(n)}function _n(n,e,r){if(n.hasOwnProperty(e))return n[e];var t=r();return n[e]=t,t}function xn(n){var e,r=[],t=!1,o={set:function(e,r){return t||(n[e]=r,o.register((function(){delete n[e]}))),r},register:function(n){var o=hn((function(){return n(e)}));return t?n(e):r.push(o),{cancel:function(){var n=r.indexOf(o);-1!==n&&r.splice(n,1)}}},all:function(n){e=n;var o=[];for(t=!0;r.length;){var i=r.shift();o.push(i())}return w.all(o).then(ln)}};return o}function Pn(n,e){if(null==e)throw new Error("Expected "+n+" to be present");return e}sn.clear=function(){fn=cn},sn((function(n){if(Object.values)return Object.values(n);var e=[];for(var r in n)n.hasOwnProperty(r)&&e.push(n[r]);return e}));var On=function(n){function e(e){var r;return(r=n.call(this,e)||this).name=r.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(n){if(void 0===n)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return n}(r),r.constructor):r.stack=new Error(e).stack,r}return o(e,n),e}(Q(Error));function Cn(){var n=document.body;if(!n)throw new Error("Body element not found");return n}function Wn(){return Boolean(document.body)&&"complete"===document.readyState}function Sn(){return Boolean(document.body)&&"interactive"===document.readyState}function Dn(n){return encodeURIComponent(n)}function Nn(n){return function(e,r,t){void 0===t&&(t=[]);var o=e.__inline_memoize_cache__=e.__inline_memoize_cache__||{},i=an(t);return o.hasOwnProperty(i)?o[i]:o[i]=function(){var e={};if(!n)return e;if(-1===n.indexOf("="))return e;for(var r=0,t=n.split("&");r { ... }":"<"+typeof n+">"})).join(", ")+") failed\n\n")+n.stack),n}))})).then((function(n){return{result:n,id:o,name:i}}))}))}));var c=r.__id__||on();n=be.unwrap(n);var f=r.__name__||r.name||t;return"string"==typeof f&&"function"==typeof f.indexOf&&0===f.indexOf("anonymous::")&&(f=f.replace("anonymous::",t+"::")),be.isProxyWindow(n)?(Ee(c,r,f,n,e),n.awaitWindow().then((function(n){Ee(c,r,f,n,e)}))):Ee(c,r,f,n,e),le("cross_domain_function",{id:c,name:f})}function Pe(n,e,r,t){var o,i=t.on,a=t.send;return function(n,e){void 0===e&&(e=pe);var r=JSON.stringify(n,(function(n){var r=this[n];if(se(this))return r;var t=de(r);if(!t)return r;var o=e[t]||we[t];return o?o(r,n):r}));return void 0===r?"undefined":r}(r,((o={}).promise=function(r,t){return function(n,e,r,t,o){return le("cross_domain_zalgo_promise",{then:xe(n,e,(function(n,e){return r.then(n,e)}),t,{on:o.on,send:o.send})})}(n,e,r,t,{on:i,send:a})},o.function=function(r,t){return xe(n,e,r,t,{on:i,send:a})},o.object=function(n){return J(n)||be.isProxyWindow(n)?le("cross_domain_window",be.serialize(n,{send:a})):n},o))}function Oe(n,e,r,t){var o,i=t.send;return function(n,e){if(void 0===e&&(e=me),"undefined"!==n)return JSON.parse(n,(function(n,r){if(se(this))return r;var t,o;if(se(r)?(t=r.__type__,o=r.__val__):(t=de(r),o=r),!t)return o;var i=e[t]||ve[t];return i?i(o,n):o}))}(r,((o={}).cross_domain_zalgo_promise=function(n){return function(n,e,r){return new w(r.then)}(0,0,n)},o.cross_domain_function=function(r){return function(n,e,r,t){var o=r.id,i=r.name,a=t.send,u=function(r){function t(){var u=arguments;return be.toProxyWindow(n,{send:a}).awaitWindow().then((function(n){var c=_e(n,o);if(c&&c.val!==t)return c.val.apply({source:window,origin:O()},u);var f=[].slice.call(u);return r.fireAndForget?a(n,"postrobot_method",{id:o,name:i,args:f},{domain:e,fireAndForget:!0}):a(n,"postrobot_method",{id:o,name:i,args:f},{domain:e,fireAndForget:!1}).then((function(n){return n.data.result}))})).catch((function(n){throw n}))}return void 0===r&&(r={}),t.__name__=i,t.__origin__=e,t.__source__=n,t.__id__=o,t.origin=e,t},c=u();return c.fireAndForget=u({fireAndForget:!0}),c}(n,e,r,{send:i})},o.cross_domain_window=function(n){return be.deserialize(n,{send:i})},o))}var Ce={};function We(n,e,r,t){var o=t.on,i=t.send;return w.try((function(){var t=oe().getOrSet(n,(function(){return{}}));return t.buffer=t.buffer||[],t.buffer.push(r),t.flush=t.flush||w.flush().then((function(){if(I(n))throw new Error("Window is closed");var r,a=Pe(n,e,((r={}).__post_robot_10_0_46__=t.buffer||[],r),{on:o,send:i});delete t.buffer;for(var u=Object.keys(Ce),c=[],f=0;f1?e-1:0),o=1;o1?r-1:0),i=1;i iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #"+e+" > iframe.zoid-invisible {\n opacity: 0;\n }\n\n #"+e+" > iframe.zoid-visible {\n opacity: 1;\n }\n ")),s.appendChild(r),s.appendChild(t),s.appendChild(d),t.classList.add("zoid-visible"),r.classList.add("zoid-invisible"),a.on(Ve.RENDERED,(function(){t.classList.remove("zoid-visible"),t.classList.add("zoid-invisible"),r.classList.remove("zoid-invisible"),r.classList.add("zoid-visible"),setTimeout((function(){Bn(t)}),1)})),a.on(Ve.RESIZE,(function(n){var e=n.width,r=n.height;"number"==typeof e&&(s.style.width=Xn(e)),"number"==typeof r&&(s.style.height=Xn(r))})),s}}var sr=xn(),dr=xn();function lr(n){var e,r,t=function(n){var e=n.tag,r=n.url,t=n.domain,o=n.bridgeUrl,a=n.props,u=void 0===a?{}:a,c=n.dimensions,f=void 0===c?{}:c,s=n.autoResize,d=void 0===s?{}:s,l=n.allowedParentDomains,h=void 0===l?"*":l,w=n.attributes,p=void 0===w?{}:w,v=n.defaultContext,m=void 0===v?Ze.IFRAME:v,y=n.containerTemplate,g=void 0===y?fr:y,b=n.prerenderTemplate,E=void 0===b?null:b,_=n.validate,x=n.eligible,P=void 0===x?function(){return{eligible:!0}}:x,O=n.logger,W=void 0===O?{info:ln}:O,S=n.exports,D=void 0===S?ln:S,N=n.method,j=n.children,R=void 0===j?function(){return{}}:j,T=e.replace(/-/g,"_"),A=i({},{window:{type:Ye.OBJECT,sendToChild:!1,required:!1,allowDelegate:!0,validate:function(n){var e=n.value;if(!J(e)&&!be.isProxyWindow(e))throw new Error("Expected Window or ProxyWindow");if(J(e)){if(I(e))throw new Error("Window is closed");if(!C(e))throw new Error("Window is not same domain")}},decorate:function(n){return Fe(n.value)}},timeout:{type:Ye.NUMBER,required:!1,sendToChild:!1},cspNonce:{type:Ye.STRING,required:!1},context:{type:Ye.STRING,required:!1},onDisplay:{type:Ye.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:or,decorate:ir},onRendered:{type:Ye.FUNCTION,required:!1,sendToChild:!1,default:or,decorate:ir},onRender:{type:Ye.FUNCTION,required:!1,sendToChild:!1,default:or,decorate:ir},onClose:{type:Ye.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:or,decorate:ir},onDestroy:{type:Ye.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:or,decorate:ir},onResize:{type:Ye.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:or},onFocus:{type:Ye.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:or},close:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.close}},focus:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.focus}},resize:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.resize}},uid:{type:Ye.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.uid}},tag:{type:Ye.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.tag}},getParent:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParent}},getParentDomain:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParentDomain}},show:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.show}},hide:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.hide}},export:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.export}},onError:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onError}},onProps:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onProps}},getSiblings:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getSiblings}}},u);if(!g)throw new Error("Container template required");return{name:T,tag:e,url:r,domain:t,bridgeUrl:o,method:N,propsDef:A,dimensions:f,autoResize:d,allowedParentDomains:h,attributes:p,defaultContext:m,containerTemplate:g,prerenderTemplate:E,validate:_,logger:W,eligible:P,children:R,exports:"function"==typeof D?D:function(n){for(var e=n.getExports,r={},t=function(n,t){var o=t[n],i=D[o].type,a=e().then((function(n){return n[o]}));r[o]=i===Ye.FUNCTION?function(){for(var n=arguments.length,e=new Array(n),r=0;r) => void> = [];\n\nexport function dispatchPossiblyUnhandledError(err : mixed, promise : ZalgoPromise) {\n\n if (dispatchedErrors.indexOf(err) !== -1) {\n return;\n }\n\n dispatchedErrors.push(err);\n\n setTimeout(() => {\n if (__DEBUG__) {\n // $FlowFixMe\n throw new Error(`${ err.stack || err.toString() }\\n\\nFrom promise:\\n\\n${ promise.stack }`);\n }\n\n throw err;\n }, 1);\n\n for (let j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) {\n // $FlowFixMe\n possiblyUnhandledPromiseHandlers[j](err, promise);\n }\n}\n\nexport function onPossiblyUnhandledException(handler : (mixed, promise? : ZalgoPromise) => void) : {| cancel : () => void |} {\n possiblyUnhandledPromiseHandlers.push(handler);\n\n return {\n cancel() {\n possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1);\n }\n };\n}\n","/* @flow */\n\nimport type { ZalgoPromise } from './promise';\n\nlet activeCount = 0;\nlet flushPromise;\n\nfunction flushActive() {\n if (!activeCount && flushPromise) {\n const promise = flushPromise;\n flushPromise = null;\n promise.resolve();\n }\n}\n\nexport function startActive() {\n activeCount += 1;\n}\n\nexport function endActive() {\n activeCount -= 1;\n flushActive();\n}\n\nexport function awaitActive(Zalgo : Class>) : ZalgoPromise { // eslint-disable-line no-undef\n const promise = flushPromise = flushPromise || new Zalgo();\n flushActive();\n return promise;\n}\n","/* @flow */\n\nimport { isPromise } from './utils';\nimport { onPossiblyUnhandledException, dispatchPossiblyUnhandledError } from './exceptions';\nimport { startActive, endActive, awaitActive } from './flush';\n\nexport class ZalgoPromise {\n\n resolved : boolean\n rejected : boolean\n errorHandled : boolean\n value : R\n error : mixed\n // eslint-disable-next-line flowtype/no-mutable-array\n handlers : Array<{|\n promise : ZalgoPromise<*>,\n onSuccess : void | (result : R) => mixed,\n onError : void | (error : mixed) => mixed\n |}>\n dispatching : boolean\n stack : string\n\n constructor(handler : ?(resolve : (result : R) => void, reject : (error : mixed) => void) => void) {\n\n this.resolved = false;\n this.rejected = false;\n this.errorHandled = false;\n\n this.handlers = [];\n\n if (handler) {\n\n let result;\n let error;\n let resolved = false;\n let rejected = false;\n let isAsync = false;\n\n startActive();\n\n try {\n handler(res => {\n if (isAsync) {\n this.resolve(res);\n } else {\n resolved = true;\n result = res;\n }\n\n }, err => {\n if (isAsync) {\n this.reject(err);\n } else {\n rejected = true;\n error = err;\n }\n });\n\n } catch (err) {\n endActive();\n this.reject(err);\n return;\n }\n\n endActive();\n\n isAsync = true;\n\n if (resolved) {\n // $FlowFixMe\n this.resolve(result);\n } else if (rejected) {\n this.reject(error);\n }\n }\n\n if (__DEBUG__) {\n try {\n throw new Error(`ZalgoPromise`);\n } catch (err) {\n this.stack = err.stack;\n }\n }\n }\n\n resolve(result : R) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(result)) {\n throw new Error('Can not resolve promise with another promise');\n }\n\n this.resolved = true;\n this.value = result;\n this.dispatch();\n\n return this;\n }\n\n reject(error : mixed) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(error)) {\n throw new Error('Can not reject promise with another promise');\n }\n\n if (!error) {\n // $FlowFixMe\n const err = (error && typeof error.toString === 'function' ? error.toString() : Object.prototype.toString.call(error));\n error = new Error(`Expected reject to be called with Error, got ${ err }`);\n }\n\n this.rejected = true;\n this.error = error;\n\n if (!this.errorHandled) {\n setTimeout(() => {\n if (!this.errorHandled) {\n dispatchPossiblyUnhandledError(error, this);\n }\n }, 1);\n }\n\n this.dispatch();\n\n return this;\n }\n\n asyncReject(error : mixed) : ZalgoPromise {\n this.errorHandled = true;\n this.reject(error);\n return this;\n }\n \n dispatch() {\n\n const { dispatching, resolved, rejected, handlers } = this;\n\n if (dispatching) {\n return;\n }\n\n if (!resolved && !rejected) {\n return;\n }\n\n this.dispatching = true;\n startActive();\n\n const chain = (firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n secondPromise.resolve(res);\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < handlers.length; i++) {\n\n const { onSuccess, onError, promise } = handlers[i];\n\n let result;\n\n if (resolved) {\n\n try {\n result = onSuccess ? onSuccess(this.value) : this.value;\n } catch (err) {\n promise.reject(err);\n continue;\n }\n\n } else if (rejected) {\n\n if (!onError) {\n promise.reject(this.error);\n continue;\n }\n\n try {\n result = onError(this.error);\n } catch (err) {\n promise.reject(err);\n continue;\n }\n }\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n const promiseResult : ZalgoPromise<*> = result;\n\n if (promiseResult.resolved) {\n promise.resolve(promiseResult.value);\n } else {\n promise.reject(promiseResult.error);\n }\n\n promiseResult.errorHandled = true;\n\n } else if (isPromise(result)) {\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n if (result.resolved) {\n promise.resolve(result.value);\n } else {\n promise.reject(result.error);\n }\n\n } else {\n // $FlowFixMe\n chain(result, promise);\n }\n\n } else {\n\n promise.resolve(result);\n }\n }\n\n handlers.length = 0;\n this.dispatching = false;\n endActive();\n }\n\n then(onSuccess : void | (result : R) => (ZalgoPromise | Y), onError : void | (error : mixed) => (ZalgoPromise | Y)) : ZalgoPromise {\n\n if (onSuccess && typeof onSuccess !== 'function' && !onSuccess.call) {\n throw new Error('Promise.then expected a function for success handler');\n }\n\n if (onError && typeof onError !== 'function' && !onError.call) {\n throw new Error('Promise.then expected a function for error handler');\n }\n\n const promise = new ZalgoPromise();\n\n this.handlers.push({\n promise,\n onSuccess,\n onError\n });\n\n this.errorHandled = true;\n\n this.dispatch();\n\n return promise;\n }\n\n catch(onError : (error : mixed) => ZalgoPromise | Y) : ZalgoPromise {\n // $FlowFixMe incompatible-call\n const resultPromise : ZalgoPromise = this.then(undefined, onError);\n return resultPromise;\n }\n\n finally(onFinally : () => mixed) : ZalgoPromise {\n\n if (onFinally && typeof onFinally !== 'function' && !onFinally.call) {\n throw new Error('Promise.finally expected a function');\n }\n\n return this.then((result) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n return result;\n });\n }, (err) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n throw err;\n });\n });\n }\n\n timeout(time : number, err : ?Error) : ZalgoPromise {\n\n if (this.resolved || this.rejected) {\n return this;\n }\n\n const timeout = setTimeout(() => {\n\n if (this.resolved || this.rejected) {\n return;\n }\n\n this.reject(err || new Error(`Promise timed out after ${ time }ms`));\n\n }, time);\n\n return this.then(result => {\n clearTimeout(timeout);\n return result;\n });\n }\n\n // $FlowFixMe\n toPromise() : Promise {\n // $FlowFixMe\n if (typeof Promise === 'undefined') {\n throw new TypeError(`Could not find Promise`);\n }\n // $FlowFixMe\n return Promise.resolve(this); // eslint-disable-line compat/compat\n }\n\n lazy() : ZalgoPromise {\n this.errorHandled = true;\n return this;\n }\n\n static resolve(value : ZalgoPromise | Y) : ZalgoPromise {\n\n if (value instanceof ZalgoPromise) {\n // $FlowFixMe incompatible-type-arg\n const result : ZalgoPromise = value;\n return result;\n }\n\n if (isPromise(value)) {\n // $FlowFixMe\n return new ZalgoPromise((resolve, reject) => value.then(resolve, reject));\n }\n\n return new ZalgoPromise().resolve(value);\n }\n\n static reject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().reject(error);\n }\n\n static asyncReject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().asyncReject(error);\n }\n\n static all>(promises : X) : ZalgoPromise<$TupleMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n\n const promise = new ZalgoPromise();\n let count = promises.length;\n // eslint-disable-next-line no-undef\n const results = ([] : $TupleMap(ZalgoPromise | Y) => Y>).slice();\n\n if (!count) {\n promise.resolve(results);\n return promise;\n }\n\n const chain = (i : number, firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n results[i] = res;\n count -= 1;\n if (count === 0) {\n promise.resolve(results);\n }\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < promises.length; i++) {\n const prom = promises[i];\n\n if (prom instanceof ZalgoPromise) {\n if (prom.resolved) {\n results[i] = prom.value;\n count -= 1;\n continue;\n }\n } else if (!isPromise(prom)) {\n results[i] = prom;\n count -= 1;\n continue;\n }\n\n chain(i, ZalgoPromise.resolve(prom), promise);\n }\n\n if (count === 0) {\n promise.resolve(results);\n }\n\n return promise;\n }\n\n static hash(promises : O) : ZalgoPromise<$ObjMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n const result = {};\n const awaitPromises = [];\n\n for (const key in promises) {\n if (promises.hasOwnProperty(key)) {\n const value = promises[key];\n\n if (isPromise(value)) {\n awaitPromises.push(value.then(res => {\n result[key] = res;\n }));\n } else {\n result[key] = value;\n }\n }\n }\n \n return ZalgoPromise.all(awaitPromises).then(() => result);\n }\n\n static map(items : $ReadOnlyArray, method : (T) => (ZalgoPromise | X)) : ZalgoPromise<$ReadOnlyArray> {\n // $FlowFixMe\n return ZalgoPromise.all(items.map(method));\n }\n\n static onPossiblyUnhandledException(handler : (err : mixed) => void) : {| cancel : () => void |} {\n return onPossiblyUnhandledException(handler);\n }\n\n static try>(method : (...args : $ReadOnlyArray) => (ZalgoPromise | Y), context? : C, args? : A) : ZalgoPromise {\n\n if (method && typeof method !== 'function' && !method.call) {\n throw new Error('Promise.try expected a function');\n }\n\n let result : ZalgoPromise | Y;\n\n startActive();\n \n try {\n result = method.apply(context, args || []);\n } catch (err) {\n endActive();\n return ZalgoPromise.reject(err);\n }\n\n endActive();\n\n // $FlowFixMe incompatible-call\n const resultPromise = ZalgoPromise.resolve(result);\n\n return resultPromise;\n }\n\n static delay(delay : number) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n setTimeout(resolve, delay);\n });\n }\n\n static isPromise(value : mixed) : boolean {\n\n if (value && value instanceof ZalgoPromise) {\n return true;\n }\n\n return isPromise(value);\n }\n\n static flush() : ZalgoPromise {\n return awaitActive(ZalgoPromise);\n }\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nexport const PROTOCOL = {\n MOCK: ('mock:' : 'mock:'),\n FILE: ('file:' : 'file:'),\n ABOUT: ('about:' : 'about:')\n};\n\nexport const WILDCARD = '*';\n\nexport const WINDOW_TYPE = {\n IFRAME: ('iframe' : 'iframe'),\n POPUP: ('popup' : 'popup')\n};\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport function safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nimport { isWindow, isWindowClosed } from 'cross-domain-utils/src';\n\nimport { hasNativeWeakMap } from './native';\nimport { noop, safeIndexOf } from './util';\n\nexport class CrossDomainSafeWeakMap {\n\n name : string\n weakmap : ?WeakMap\n // eslint-disable-next-line flowtype/no-mutable-array\n keys : Array\n // eslint-disable-next-line flowtype/no-mutable-array\n values : Array\n\n constructor() {\n // eslint-disable-next-line no-bitwise\n this.name = `__weakmap_${ Math.random() * 1e9 >>> 0 }__`;\n\n if (hasNativeWeakMap()) {\n try {\n this.weakmap = new WeakMap();\n } catch (err) {\n // pass\n }\n }\n\n this.keys = [];\n this.values = [];\n }\n\n _cleanupClosedWindows() {\n\n const weakmap = this.weakmap;\n const keys = this.keys;\n\n for (let i = 0; i < keys.length; i++) {\n const value = keys[i];\n\n if (isWindow(value) && isWindowClosed(value)) {\n\n if (weakmap) {\n try {\n weakmap.delete(value);\n } catch (err) {\n // pass\n }\n }\n\n keys.splice(i, 1);\n this.values.splice(i, 1);\n\n i -= 1;\n }\n }\n }\n\n isSafeToReadWrite(key : K) : boolean {\n\n if (isWindow(key)) {\n return false;\n }\n\n try {\n noop(key && key.self);\n noop(key && key[this.name]);\n } catch (err) {\n return false;\n }\n\n return true;\n }\n\n set(key : K, value : V) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.set(key, value);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const name = this.name;\n const entry = key[name];\n\n if (entry && entry[0] === key) {\n entry[1] = value;\n } else {\n Object.defineProperty(key, name, {\n value: [ key, value ],\n writable: true\n });\n }\n\n return;\n\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const values = this.values;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n keys.push(key);\n values.push(value);\n } else {\n values[index] = value;\n }\n }\n\n get(key : K) : V | void {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return weakmap.get(key);\n }\n \n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return entry[1];\n }\n\n return;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n return;\n }\n\n return this.values[index];\n }\n\n delete(key : K) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.delete(key);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n entry[0] = entry[1] = undefined;\n }\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index !== -1) {\n keys.splice(index, 1);\n this.values.splice(index, 1);\n }\n }\n\n has(key : K) : boolean {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return true;\n }\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return true;\n }\n\n return false;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const index = safeIndexOf(this.keys, key);\n return index !== -1;\n }\n\n getOrSet(key : K, getter : () => V) : V {\n if (this.has(key)) {\n // $FlowFixMe\n return this.get(key);\n }\n\n const value = getter();\n this.set(key, value);\n return value;\n }\n}\n","\n/* @flow */\n/* eslint max-lines: 0 */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport type { CancelableType } from './types';\n\nexport function isElement(element : mixed) : boolean {\n let passed = false;\n\n try {\n if (element instanceof window.Element) {\n passed = true;\n } else if (element !== null && typeof element === 'object' && element.nodeType === 1 && typeof element.style === 'object' && typeof element.ownerDocument === 'object') {\n passed = true;\n }\n } catch (_) {\n // we don't have an element\n }\n\n return passed;\n}\n\nexport function getFunctionName (fn : T) : string {\n return fn.name || fn.__name__ || fn.displayName || 'anonymous';\n}\n\nexport function setFunctionName (fn : T, name : string) : T {\n try {\n delete fn.name;\n fn.name = name;\n } catch (err) {\n // pass\n }\n\n fn.__name__ = fn.displayName = name;\n return fn;\n}\n\nexport function base64encode(str : string) : string {\n if (typeof btoa === 'function') {\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (m, p1) => {\n return String.fromCharCode(parseInt(p1, 16));\n })).replace(/[=]/g, '');\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf8').toString('base64').replace(/[=]/g, '');\n }\n\n throw new Error(`Can not find window.btoa or Buffer`);\n}\n\nexport function base64decode(str : string) : string {\n if (typeof atob === 'function') {\n // $FlowFixMe[method-unbinding]\n return decodeURIComponent(Array.prototype.map.call(atob(str), c => {\n // eslint-disable-next-line prefer-template\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(''));\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64').toString('utf8');\n }\n\n throw new Error(`Can not find window.atob or Buffer`);\n}\n\nexport function uniqueID() : string {\n\n const chars = '0123456789abcdef';\n\n const randomID = 'xxxxxxxxxx'.replace(/./g, () => {\n return chars.charAt(Math.floor(Math.random() * chars.length));\n });\n\n const timeID = base64encode(\n new Date().toISOString().slice(11, 19).replace('T', '.')\n ).replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n\n return `uid_${ randomID }_${ timeID }`;\n}\n\nexport function getGlobal() : Object {\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (typeof __GLOBAL__ !== 'undefined') {\n return __GLOBAL__;\n }\n throw new Error(`No global found`);\n}\n\nlet objectIDs;\n\nexport function getObjectID(obj : Object) : string {\n\n objectIDs = objectIDs || new WeakMap();\n\n if (obj === null || obj === undefined || (typeof obj !== 'object' && typeof obj !== 'function')) {\n throw new Error(`Invalid object`);\n }\n\n let uid = objectIDs.get(obj);\n\n if (!uid) {\n uid = `${ typeof obj }:${ uniqueID() }`;\n objectIDs.set(obj, uid);\n }\n\n return uid;\n}\n\nfunction serializeArgs(args : $ReadOnlyArray) : string {\n try {\n // $FlowFixMe[method-unbinding]\n return JSON.stringify(Array.prototype.slice.call(args), (subkey, val) => {\n\n // Treat each distinct function as unique for purposes of memoization\n // e.g. even if someFunction.stringify() is the same, we may use a different memoize cache\n // if the actual function is different.\n if (typeof val === 'function') {\n return `memoize[${ getObjectID(val) }]`;\n }\n\n // By default JSON.stringify(domElement) returns '{}'. This ensures that stays true even for non-standard\n // elements (e.g. React-rendered dom elements) with custom properties\n if (isElement(val)) {\n return {};\n }\n\n return val;\n });\n } catch (err) {\n throw new Error(`Arguments not serializable -- can not be used to memoize`);\n }\n}\n\nexport function getEmptyObject() : {||} {\n // $FlowFixMe\n return {};\n}\n\ntype MemoizeOptions = {|\n name? : string,\n time? : number,\n thisNamespace? : boolean\n|};\n\nconst getDefaultMemoizeOptions = () : MemoizeOptions => {\n // $FlowFixMe\n return {};\n};\n\nexport type Memoized = F & {| reset : () => void |};\n\nlet memoizeGlobalIndex = 0;\nlet memoizeGlobalIndexValidFrom = 0;\n\nexport function memoize(method : F, options? : MemoizeOptions = getDefaultMemoizeOptions()) : Memoized {\n const { thisNamespace = false, time: cacheTime } = options;\n\n let simpleCache;\n let thisCache;\n\n let memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n\n const memoizedFunction = function memoizedFunction(...args) : mixed {\n if (memoizeIndex < memoizeGlobalIndexValidFrom) {\n simpleCache = null;\n thisCache = null;\n memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n }\n\n let cache;\n\n if (thisNamespace) {\n thisCache = thisCache || new WeakMap();\n cache = thisCache.getOrSet(this, getEmptyObject);\n } else {\n cache = simpleCache = simpleCache || {};\n }\n\n let cacheKey;\n\n try {\n cacheKey = serializeArgs(args);\n } catch {\n return method.apply(this, arguments);\n }\n\n let cacheResult = cache[cacheKey];\n\n if (cacheResult && cacheTime && (Date.now() - cacheResult.time) < cacheTime) {\n delete cache[cacheKey];\n cacheResult = null;\n }\n\n if (cacheResult) {\n return cacheResult.value;\n }\n\n const time = Date.now();\n const value = method.apply(this, arguments);\n\n cache[cacheKey] = { time, value };\n\n return value;\n };\n\n memoizedFunction.reset = () => {\n simpleCache = null;\n thisCache = null;\n };\n\n // $FlowFixMe\n const result : F = memoizedFunction;\n\n return setFunctionName(result, `${ options.name || getFunctionName(method) }::memoized`);\n}\n\nmemoize.clear = () => {\n memoizeGlobalIndexValidFrom = memoizeGlobalIndex;\n};\n\nexport function promiseIdentity(item : ZalgoPromise | T) : ZalgoPromise {\n // $FlowFixMe\n return ZalgoPromise.resolve(item);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function memoizePromise(method : (...args : $ReadOnlyArray) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n let cache = {};\n\n // eslint-disable-next-line flowtype/no-weak-types\n function memoizedPromiseFunction(...args : $ReadOnlyArray) : ZalgoPromise {\n const key : string = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n cache[key] = ZalgoPromise.try(() => method.apply(this, arguments))\n .finally(() => {\n delete cache[key];\n });\n\n return cache[key];\n }\n\n memoizedPromiseFunction.reset = () => {\n cache = {};\n };\n\n return setFunctionName(memoizedPromiseFunction, `${ getFunctionName(method) }::promiseMemoized`);\n}\n\ntype PromisifyOptions = {|\n name ? : string\n|};\n\nconst getDefaultPromisifyOptions = () : PromisifyOptions => {\n // $FlowFixMe\n return {};\n};\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function promisify(method : (...args : $ReadOnlyArray) => R, options : PromisifyOptions = getDefaultPromisifyOptions()) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n function promisifiedFunction() : ZalgoPromise {\n return ZalgoPromise.try(method, this, arguments);\n }\n\n if (options.name) {\n promisifiedFunction.displayName = `${ options.name }:promisified`;\n }\n\n return setFunctionName(promisifiedFunction, `${ getFunctionName(method) }::promisified`);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function inlineMemoize(method : (...args : $ReadOnlyArray) => R, logic : (...args : $ReadOnlyArray) => R, args : $ReadOnlyArray = []) : R {\n // $FlowFixMe\n const cache : {| [string] : R |} = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {};\n const key = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n const result = cache[key] = logic(...args);\n\n return result;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n\nexport function once(method : Function) : Function {\n let called = false;\n\n const onceFunction = function() : mixed {\n if (!called) {\n called = true;\n return method.apply(this, arguments);\n }\n };\n\n return setFunctionName(onceFunction, `${ getFunctionName(method) }::once`);\n}\n\nexport function hashStr(str : string) : number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash += str[i].charCodeAt(0) * Math.pow((i % 10) + 1, 5);\n }\n return Math.floor(Math.pow(Math.sqrt(hash), 5));\n}\n\nexport function strHashStr(str : string) : string {\n let hash = '';\n\n for (let i = 0; i < str.length; i++) {\n let total = (str[i].charCodeAt(0) * i);\n\n if (str[i + 1]) {\n total += (str[i + 1].charCodeAt(0) * (i - 1));\n }\n\n hash += String.fromCharCode(97 + (Math.abs(total) % 26));\n }\n\n return hash;\n}\n\nexport function match(str : string, pattern : RegExp) : ?string {\n const regmatch = str.match(pattern);\n if (regmatch) {\n return regmatch[1];\n }\n}\n\nexport function awaitKey(obj : Object, key : string) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n\n let value = obj[key];\n\n if (value) {\n return resolve(value);\n }\n\n delete obj[key];\n\n Object.defineProperty(obj, key, {\n\n configurable: true,\n\n set(item) {\n value = item;\n\n if (value) {\n resolve(value);\n }\n },\n\n get() : T {\n return value;\n }\n });\n });\n}\n\nexport function stringifyError(err : mixed, level : number = 1) : string {\n\n if (level >= 3) {\n return 'stringifyError stack overflow';\n }\n\n try {\n if (!err) {\n // $FlowFixMe[method-unbinding]\n return ``;\n }\n\n if (typeof err === 'string') {\n return err;\n }\n\n if (err instanceof Error) {\n const stack = err && err.stack;\n const message = err && err.message;\n\n if (stack && message) {\n if (stack.indexOf(message) !== -1) {\n return stack;\n } else {\n return `${ message }\\n${ stack }`;\n }\n } else if (stack) {\n return stack;\n } else if (message) {\n return message;\n }\n }\n\n if (err && err.toString && typeof err.toString === 'function') {\n // $FlowFixMe\n return err.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(err);\n\n } catch (newErr) {\n return `Error while stringifying error: ${ stringifyError(newErr, level + 1) }`;\n }\n}\n\nexport function stringifyErrorMessage(err : mixed) : string {\n\n // $FlowFixMe[method-unbinding]\n const defaultMessage = ``;\n\n if (!err) {\n return defaultMessage;\n }\n\n if (err instanceof Error) {\n return err.message || defaultMessage;\n }\n\n if (typeof err.message === 'string') {\n return err.message || defaultMessage;\n }\n\n return defaultMessage;\n}\n\nexport function stringify(item : mixed) : string {\n if (typeof item === 'string') {\n return item;\n }\n\n if (item && item.toString && typeof item.toString === 'function') {\n // $FlowFixMe\n return item.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item);\n}\n\nexport function domainMatches(hostname : string, domain : string) : boolean {\n hostname = hostname.split('://')[1];\n const index = hostname.indexOf(domain);\n return (index !== -1 && hostname.slice(index) === domain);\n}\n\nexport function patchMethod(obj : Object, name : string, handler : Function) {\n const original = obj[name];\n\n obj[name] = function patchedMethod() : mixed {\n return handler({\n context: this,\n // $FlowFixMe[method-unbinding]\n args: Array.prototype.slice.call(arguments),\n original,\n callOriginal: () => original.apply(this, arguments)\n });\n };\n}\n\nexport function extend(obj : T, source : Object) : T {\n if (!source) {\n return obj;\n }\n\n if (Object.assign) {\n return Object.assign(obj, source);\n }\n\n for (const key in source) {\n if (source.hasOwnProperty(key)) {\n obj[key] = source[key];\n }\n }\n\n return obj;\n}\n\nexport function values(obj : { [string] : T }) : $ReadOnlyArray {\n if (Object.values) {\n // $FlowFixMe\n return Object.values(obj);\n }\n\n const result : Array = [];\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n // $FlowFixMe[escaped-generic]\n result.push(obj[key]);\n }\n }\n\n // $FlowFixMe\n return result;\n}\n\n// eslint-disable-next-line no-undef\nexport const memoizedValues : ({ [string] : T }) => $ReadOnlyArray = memoize(values);\n\nexport function perc(pixels : number, percentage : number) : number {\n return Math.round((pixels * percentage) / 100);\n}\n\nexport function min(...args : $ReadOnlyArray) : number {\n return Math.min(...args);\n}\n\nexport function max(...args : $ReadOnlyArray) : number {\n return Math.max(...args);\n}\n\nexport function roundUp(num : number, nearest : number) : number {\n const remainder = num % nearest;\n return remainder\n ? (num - remainder) + nearest\n : num;\n}\n\nexport function regexMap(str : string, regexp : RegExp, handler : () => T) : $ReadOnlyArray {\n const results = [];\n\n // $FlowFixMe\n str.replace(regexp, function regexMapMatcher(item) {\n results.push(handler ? handler.apply(null, arguments) : item);\n });\n\n // $FlowFixMe\n return results;\n}\n\nexport function svgToBase64(svg : string) : string {\n return `data:image/svg+xml;base64,${ base64encode(svg) }`;\n}\n\nexport function objFilter(obj : { [string] : T }, filter? : (T, ?string) => mixed = Boolean) : { [string] : R } {\n const result = {};\n\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || !filter(obj[key], key)) {\n continue;\n }\n\n result[key] = obj[key];\n }\n\n return result;\n}\n\nexport function identity (item : T) : T {\n return item;\n}\n\nexport function regexTokenize(text : string, regexp : RegExp) : $ReadOnlyArray {\n const result = [];\n text.replace(regexp, token => {\n result.push(token);\n return '';\n });\n return result;\n}\n\nexport function promiseDebounce(method : () => ZalgoPromise | T, delay : number = 50) : () => ZalgoPromise {\n\n let promise;\n let timeout;\n\n const promiseDebounced = function() : ZalgoPromise {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n const localPromise = promise = promise || new ZalgoPromise();\n\n timeout = setTimeout(() => {\n promise = null;\n timeout = null;\n\n ZalgoPromise.try(method).then(\n result => { localPromise.resolve(result); },\n err => { localPromise.reject(err); }\n );\n }, delay);\n\n return localPromise;\n };\n\n return setFunctionName(promiseDebounced, `${ getFunctionName(method) }::promiseDebounced`);\n}\n\nexport function safeInterval(method : Function, time : number) : {| cancel : () => void |} {\n\n let timeout;\n\n function loop() {\n timeout = setTimeout(() => {\n method();\n loop();\n }, time);\n }\n\n loop();\n\n return {\n cancel() {\n clearTimeout(timeout);\n }\n };\n}\n\nexport function isInteger(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+$/));\n}\n\nexport function isFloat(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+\\.[0-9]+$/));\n}\n\nexport function serializePrimitive(value : string | number | boolean) : string {\n return value.toString();\n}\n\nexport function deserializePrimitive(value : string) : string | number | boolean {\n if (value === 'true') {\n return true;\n } else if (value === 'false') {\n return false;\n } else if (isInteger(value)) {\n return parseInt(value, 10);\n } else if (isFloat(value)) {\n return parseFloat(value);\n } else {\n return value;\n }\n}\n\nexport function dotify(obj : Object, prefix : string = '', newobj : Object = {}) : { [string] : string } {\n prefix = prefix ? `${ prefix }.` : prefix;\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || obj[key] === undefined || obj[key] === null || typeof obj[key] === 'function') {\n continue;\n } else if (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every(val => typeof val !== 'object')) {\n newobj[`${ prefix }${ key }[]`] = obj[key].join(',');\n } else if (obj[key] && typeof obj[key] === 'object') {\n newobj = dotify(obj[key], `${ prefix }${ key }`, newobj);\n } else {\n newobj[`${ prefix }${ key }`] = serializePrimitive(obj[key]);\n }\n }\n return newobj;\n}\n\nexport function undotify(obj : { [string] : string }) : Object {\n\n const result = {};\n\n for (let key in obj) {\n if (!obj.hasOwnProperty(key) || typeof obj[key] !== 'string') {\n continue;\n }\n\n let value = obj[key];\n\n if (key.match(/^.+\\[\\]$/)) {\n key = key.slice(0, -2);\n value = value.split(',').map(deserializePrimitive);\n } else {\n value = deserializePrimitive(value);\n }\n\n let keyResult = result;\n const parts = key.split('.');\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n const isLast = (i + 1 === parts.length);\n const isIndex = !isLast && isInteger(parts[i + 1]);\n\n if (part === 'constructor' || part === 'prototype' || part === '__proto__') {\n throw new Error(`Disallowed key: ${ part }`);\n }\n\n if (isLast) {\n // $FlowFixMe\n keyResult[part] = value;\n } else {\n // $FlowFixMe\n keyResult = keyResult[part] = keyResult[part] || (isIndex ? [] : {});\n }\n }\n }\n\n return result;\n}\n\nexport type EventEmitterType = {|\n on : (eventName : string, handler : Function) => CancelableType,\n once : (eventName : string, handler : Function) => CancelableType,\n trigger : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n triggerOnce : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n reset : () => void\n|};\n\nexport function eventEmitter() : EventEmitterType {\n const triggered = {};\n let handlers = {};\n\n const emitter = {\n\n on(eventName : string, handler : Function) : CancelableType {\n const handlerList = handlers[eventName] = handlers[eventName] || [];\n\n handlerList.push(handler);\n\n let cancelled = false;\n\n return {\n cancel() {\n if (!cancelled) {\n cancelled = true;\n handlerList.splice(handlerList.indexOf(handler), 1);\n }\n\n }\n };\n },\n\n once(eventName : string, handler : Function) : CancelableType {\n\n const listener = emitter.on(eventName, () => {\n listener.cancel();\n handler();\n });\n\n return listener;\n },\n\n trigger(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n const handlerList = handlers[eventName];\n const promises = [];\n\n if (handlerList) {\n for (const handler of handlerList) {\n promises.push(ZalgoPromise.try(() => handler(...args)));\n }\n }\n\n return ZalgoPromise.all(promises).then(noop);\n },\n\n triggerOnce(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n if (triggered[eventName]) {\n return ZalgoPromise.resolve();\n }\n\n triggered[eventName] = true;\n return emitter.trigger(eventName, ...args);\n },\n\n reset() {\n handlers = {};\n }\n };\n\n return emitter;\n}\n\nexport function camelToDasherize(string : string) : string {\n return string.replace(/([A-Z])/g, (g) => {\n return `-${ g.toLowerCase() }`;\n });\n}\n\nexport function dasherizeToCamel(string : string) : string {\n return string.replace(/-([a-z])/g, (g) => {\n return g[1].toUpperCase();\n });\n}\n\nexport function capitalizeFirstLetter(string : string) : string {\n return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();\n}\n\nexport function get(item : Object, path : string, def : mixed) : mixed {\n\n if (!path) {\n return def;\n }\n\n const pathParts = path.split('.');\n\n // Loop through each section of our key path\n\n for (let i = 0; i < pathParts.length; i++) {\n\n // If we have an object, we can get the key\n if (typeof item === 'object' && item !== null) {\n item = item[pathParts[i]];\n\n // Otherwise, we should return the default (undefined if not provided)\n } else {\n return def;\n }\n }\n\n // If our final result is undefined, we should return the default\n\n return item === undefined ? def : item;\n}\n\nexport function safeTimeout(method : Function, time : number) {\n\n const interval = safeInterval(() => {\n time -= 100;\n if (time <= 0) {\n interval.cancel();\n method();\n }\n }, 100);\n}\n\nexport function defineLazyProp(obj : Object | $ReadOnlyArray, key : string | number, getter : () => T) {\n if (Array.isArray(obj)) {\n if (typeof key !== 'number') {\n throw new TypeError(`Array key must be number`);\n }\n } else if (typeof obj === 'object' && obj !== null) {\n if (typeof key !== 'string') {\n throw new TypeError(`Object key must be string`);\n }\n }\n\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n get: () => {\n // $FlowFixMe\n delete obj[key];\n const value = getter();\n // $FlowFixMe\n obj[key] = value;\n return value;\n },\n set: (value : T) => {\n // $FlowFixMe\n delete obj[key];\n // $FlowFixMe\n obj[key] = value;\n }\n });\n}\n\nexport function arrayFrom(item : Iterable) : $ReadOnlyArray { // eslint-disable-line no-undef\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(item);\n}\n\nexport function isObject(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null);\n}\n\nexport function isObjectObject(obj : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return isObject(obj) && Object.prototype.toString.call(obj) === '[object Object]';\n}\n\nexport function isPlainObject(obj : mixed) : boolean {\n if (!isObjectObject(obj)) {\n return false;\n }\n\n // $FlowFixMe\n const constructor = obj.constructor;\n\n if (typeof constructor !== 'function') {\n return false;\n }\n\n const prototype = constructor.prototype;\n\n if (!isObjectObject(prototype)) {\n return false;\n }\n\n if (!prototype.hasOwnProperty('isPrototypeOf')) {\n return false;\n }\n\n return true;\n}\n\nexport function replaceObject | Object> (item : T, replacer : (mixed, string | number, string) => mixed, fullKey : string = '') : T {\n\n if (Array.isArray(item)) {\n const length = item.length;\n const result : Array = [];\n\n for (let i = 0; i < length; i++) {\n\n\n defineLazyProp(result, i, () => {\n const itemKey = fullKey ? `${ fullKey }.${ i }` : `${ i }`;\n const el = item[i];\n\n let child = replacer(el, i, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else if (isPlainObject(item)) {\n const result = {};\n\n for (const key in item) {\n if (!item.hasOwnProperty(key)) {\n continue;\n }\n\n defineLazyProp(result, key, () => {\n const itemKey = fullKey ? `${ fullKey }.${ key }` : `${ key }`;\n // $FlowFixMe\n const el = item[key];\n\n let child = replacer(el, key, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else {\n throw new Error(`Pass an object or array`);\n }\n}\n\n\nexport function copyProp(source : Object, target : Object, name : string, def : mixed) {\n if (source.hasOwnProperty(name)) {\n const descriptor = Object.getOwnPropertyDescriptor(source, name);\n // $FlowFixMe\n Object.defineProperty(target, name, descriptor);\n\n } else {\n target[name] = def;\n }\n}\n\ntype RegexResultType = {|\n text : string,\n groups : $ReadOnlyArray,\n start : number,\n end : number,\n length : number,\n replace : (text : string) => string\n|};\n\nexport function regex(pattern : string | RegExp, string : string, start : number = 0) : ?RegexResultType {\n\n if (typeof pattern === 'string') {\n // eslint-disable-next-line security/detect-non-literal-regexp\n pattern = new RegExp(pattern);\n }\n\n const result = string.slice(start).match(pattern);\n\n if (!result) {\n return;\n }\n\n // $FlowFixMe\n const index : number = result.index;\n const regmatch = result[0];\n\n return {\n text: regmatch,\n groups: result.slice(1),\n start: start + index,\n end: start + index + regmatch.length,\n length: regmatch.length,\n\n replace(text : string) : string {\n\n if (!regmatch) {\n return '';\n }\n\n return `${ regmatch.slice(0, start + index) }${ text }${ regmatch.slice(index + regmatch.length) }`;\n }\n };\n}\n\nexport function regexAll(pattern : string | RegExp, string : string) : $ReadOnlyArray {\n\n const matches = [];\n let start = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const regmatch = regex(pattern, string, start);\n\n if (!regmatch) {\n break;\n }\n\n matches.push(regmatch);\n start = match.end;\n }\n\n return matches;\n}\n\nexport function isDefined(value : ?mixed) : boolean {\n return value !== null && value !== undefined;\n}\n\nexport function cycle(method : Function) : ZalgoPromise {\n return ZalgoPromise.try(method).then(() => cycle(method));\n}\n\nexport function debounce(method : (...args : $ReadOnlyArray) => T, time : number = 100) : (...args : $ReadOnlyArray) => void {\n\n let timeout;\n\n const debounceWrapper = function() {\n clearTimeout(timeout);\n\n timeout = setTimeout(() => {\n return method.apply(this, arguments);\n }, time);\n };\n\n return setFunctionName(debounceWrapper, `${ getFunctionName(method) }::debounced`);\n}\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\ntype FunctionProxy = (method : T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoize : FunctionProxy<*> = (method : (arg : any) => R) : ((...args : $ReadOnlyArray) => R) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoized(arg : any) : R {\n return weakmap.getOrSet(arg, () => method.call(this, arg));\n };\n};\n\ntype FunctionPromiseProxy) => ZalgoPromise> = (T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoizePromise : FunctionPromiseProxy<*, *> = (method : (arg : any) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoizedPromise(arg : any) : ZalgoPromise {\n return weakmap.getOrSet(arg, () =>\n method.call(this, arg).finally(() => {\n weakmap.delete(arg);\n }));\n };\n};\n\nexport function getOrSet(obj : O, key : string, getter : () => T) : T {\n if (obj.hasOwnProperty(key)) {\n return obj[key];\n }\n\n const val = getter();\n obj[key] = val;\n return val;\n}\n\nexport type CleanupType = {|\n set : (string, T) => T, // eslint-disable-line no-undef\n register : (Function) => {| cancel : () => void |},\n all : (err? : mixed) => ZalgoPromise\n|};\n\nexport function cleanup(obj : Object) : CleanupType {\n\n const tasks = [];\n let cleaned = false;\n let cleanErr;\n\n const cleaner = {\n set(name : string, item : T) : T {\n if (!cleaned) {\n obj[name] = item;\n cleaner.register(() => {\n delete obj[name];\n });\n }\n return item;\n },\n\n register(method : Function) : {| cancel : () => void |} {\n const task = once(() => method(cleanErr));\n\n if (cleaned) {\n method(cleanErr);\n } else {\n tasks.push(task);\n }\n\n return {\n cancel: () => {\n const index = tasks.indexOf(task);\n if (index !== -1) {\n tasks.splice(index, 1);\n }\n }\n };\n },\n\n all(err? : mixed) : ZalgoPromise {\n cleanErr = err;\n\n const results = [];\n cleaned = true;\n\n while (tasks.length) {\n const task = tasks.shift();\n results.push(task());\n }\n\n return ZalgoPromise.all(results).then(noop);\n }\n };\n\n return cleaner;\n}\n\nexport function tryCatch(fn : () => T) : {| result : T, error : void |} | {| result : void, error : mixed |} {\n let result;\n let error;\n\n try {\n result = fn();\n } catch (err) {\n error = err;\n }\n\n // $FlowFixMe\n return { result, error };\n}\n\n// eslint-disable-next-line flowtype/no-mutable-array\nexport function removeFromArray>(arr : T, item : X) {\n const index = arr.indexOf(item);\n if (index !== -1) {\n arr.splice(index, 1);\n }\n}\n\nexport function assertExists(name : string, thing : void | null | T) : T {\n if (thing === null || typeof thing === 'undefined') {\n throw new Error(`Expected ${ name } to be present`);\n }\n\n return thing;\n}\n\nexport function unique(arr : $ReadOnlyArray) : $ReadOnlyArray {\n const result = {};\n for (const item of arr) {\n result[item] = true;\n }\n return Object.keys(result);\n}\n\nexport const constHas = (constant : T, value : X) : boolean => {\n return memoizedValues(constant).indexOf(value) !== -1;\n};\n\nexport function dedupeErrors(handler : (mixed) => T) : (mixed) => (T | void) {\n const seenErrors = [];\n const seenStringifiedErrors = {};\n\n return (err) => {\n if (seenErrors.indexOf(err) !== -1) {\n return;\n }\n\n seenErrors.push(err);\n\n const stringifiedError = stringifyError(err);\n if (seenStringifiedErrors[stringifiedError]) {\n return;\n }\n\n seenStringifiedErrors[stringifiedError] = true;\n return handler(err);\n };\n}\n\nexport class ExtendableError extends Error {\n constructor(message : string) {\n super(message);\n // eslint-disable-next-line unicorn/custom-error-definition\n this.name = this.constructor.name;\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error(message)).stack;\n }\n }\n}\n","/* @flow */\n\nexport function hasNativeWeakMap() : boolean {\n\n if (typeof WeakMap === 'undefined') {\n return false;\n }\n\n if (typeof Object.freeze === 'undefined') {\n return false;\n }\n\n try {\n\n const testWeakMap = new WeakMap();\n const testKey = {};\n const testValue = '__testvalue__';\n\n Object.freeze(testKey);\n\n testWeakMap.set(testKey, testValue);\n\n if (testWeakMap.get(testKey) === testValue) {\n return true;\n }\n\n return false;\n\n } catch (err) {\n\n return false;\n }\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeReflectConstruct from \"@babel/runtime/helpers/esm/isNativeReflectConstruct\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}","import getPrototypeOf from \"@babel/runtime/helpers/esm/getPrototypeOf\";\nimport setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeFunction from \"@babel/runtime/helpers/esm/isNativeFunction\";\nimport construct from \"@babel/runtime/helpers/esm/construct\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","/* @flow */\n/* eslint max-lines: off */\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { linkFrameWindow, isWindowClosed, assertSameDomain,\n type SameDomainWindowType, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport { isElement, inlineMemoize, memoize, noop, stringify, capitalizeFirstLetter,\n once, extend, safeInterval, uniqueID, arrayFrom, ExtendableError, strHashStr } from './util';\nimport { isDevice } from './device';\nimport { KEY_CODES, ATTRIBUTES, UID_HASH_LENGTH } from './constants';\nimport type { CancelableType } from './types';\n\ntype ElementRefType = string | HTMLElement;\n\nexport function getBody() : HTMLBodyElement {\n // eslint-disable-next-line compat/compat\n const body = document.body;\n\n if (!body) {\n throw new Error(`Body element not found`);\n }\n\n return body;\n}\n\nexport function isDocumentReady() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'complete');\n}\n\nexport function isDocumentInteractive() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'interactive');\n}\n\nexport function urlEncode(str : string) : string {\n return encodeURIComponent(str);\n}\n\nexport function waitForWindowReady() : ZalgoPromise {\n return inlineMemoize(waitForWindowReady, () : ZalgoPromise => {\n return new ZalgoPromise(resolve => {\n if (isDocumentReady()) {\n resolve();\n }\n\n window.addEventListener('load', () => resolve());\n });\n });\n}\n\ntype WaitForDocumentReady = () => ZalgoPromise;\n\nexport const waitForDocumentReady : WaitForDocumentReady = memoize(() => {\n return new ZalgoPromise(resolve => {\n\n if (isDocumentReady() || isDocumentInteractive()) {\n return resolve();\n }\n\n const interval = setInterval(() => {\n if (isDocumentReady() || isDocumentInteractive()) {\n clearInterval(interval);\n return resolve();\n }\n }, 10);\n });\n});\n\nexport function waitForDocumentBody() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (document.body) {\n return document.body;\n }\n\n return waitForDocumentReady().then(() => {\n if (document.body) {\n return document.body;\n }\n\n throw new Error('Document ready but document.body not present');\n });\n });\n}\n\nexport function parseQuery(queryString : string) : Object {\n return inlineMemoize(parseQuery, () : Object => {\n const params = {};\n\n if (!queryString) {\n return params;\n }\n\n if (queryString.indexOf('=') === -1) {\n return params;\n }\n\n for (let pair of queryString.split('&')) {\n pair = pair.split('=');\n\n if (pair[0] && pair[1]) {\n params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n }\n\n return params;\n }, [ queryString ]);\n}\n\n\nexport function getQueryParam(name : string) : string {\n return parseQuery(window.location.search.slice(1))[name];\n}\n\nexport function urlWillRedirectPage(url : string) : boolean {\n\n if (url.indexOf('#') === -1) {\n return true;\n }\n\n if (url.indexOf('#') === 0) {\n return false;\n }\n\n if (url.split('#')[0] === window.location.href.split('#')[0]) {\n return false;\n }\n\n return true;\n}\n\nexport type Query = {\n [ string ] : boolean | string\n};\n\nexport function formatQuery(obj : Query = {}) : string {\n\n return Object.keys(obj).filter(key => {\n return typeof obj[key] === 'string' || typeof obj[key] === 'boolean';\n }).map(key => {\n const val = obj[key];\n\n if (typeof val !== 'string' && typeof val !== 'boolean') {\n throw new TypeError(`Invalid type for query`);\n }\n\n return `${ urlEncode(key) }=${ urlEncode(val.toString()) }`;\n }).join('&');\n}\n\nexport function extendQuery(originalQuery : string, props : Query = {}) : string {\n\n if (!props || !Object.keys(props).length) {\n return originalQuery;\n }\n\n return formatQuery({\n ...parseQuery(originalQuery),\n ...props\n });\n}\n\nexport function extendUrl(url : string, options : {| query? : Query, hash? : Query |}) : string {\n\n const query = options.query || {};\n const hash = options.hash || {};\n\n let originalUrl;\n let originalQuery;\n let originalHash;\n\n [ originalUrl, originalHash ] = url.split('#');\n [ originalUrl, originalQuery ] = originalUrl.split('?');\n\n const queryString = extendQuery(originalQuery, query);\n const hashString = extendQuery(originalHash, hash);\n\n if (queryString) {\n originalUrl = `${ originalUrl }?${ queryString }`;\n }\n\n if (hashString) {\n originalUrl = `${ originalUrl }#${ hashString }`;\n }\n\n return originalUrl;\n}\n\nexport function redirect(url : string, win : CrossDomainWindowType = window) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n win.location = url;\n if (!urlWillRedirectPage(url)) {\n resolve();\n }\n });\n}\n\nexport function hasMetaViewPort() : boolean {\n const meta = document.querySelector('meta[name=viewport]');\n\n if (isDevice() && window.screen.width < 660 && !meta) {\n return false;\n }\n\n return true;\n}\n\nexport function isElementVisible(el : HTMLElement) : boolean {\n return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length);\n}\n\nexport function getPerformance() : ?Performance {\n return inlineMemoize(getPerformance, () : ?Performance => {\n const performance = window.performance;\n\n if (\n performance &&\n performance.now &&\n performance.timing &&\n performance.timing.connectEnd &&\n performance.timing.navigationStart &&\n (Math.abs(performance.now() - Date.now()) > 1000) &&\n (performance.now() - (performance.timing.connectEnd - performance.timing.navigationStart)) > 0\n ) {\n return performance;\n }\n });\n}\n\nexport function enablePerformance() : boolean {\n return Boolean(getPerformance());\n}\n\nexport function getPageRenderTime() : ZalgoPromise {\n return waitForDocumentReady().then(() => {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n const timing = performance.timing;\n\n if (timing.connectEnd && timing.domInteractive) {\n return timing.domInteractive - timing.connectEnd;\n }\n });\n}\n\nexport function htmlEncode(html : string = '') : string {\n return html.toString()\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(/\\//g, '/');\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined') && window.location !== undefined;\n}\n\nexport function querySelectorAll(selector : string, doc : HTMLElement = window.document) : $ReadOnlyArray {\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(doc.querySelectorAll(selector));\n}\n\nexport function onClick(element : HTMLElement, handler : (Event) => void) {\n element.addEventListener('touchstart', noop);\n element.addEventListener('click', handler);\n element.addEventListener('keypress', (event : Event) => {\n // $FlowFixMe\n if (event.keyCode === KEY_CODES.ENTER || event.keyCode === KEY_CODES.SPACE) {\n return handler(event);\n }\n });\n}\n\nexport function getScript({ host = window.location.host, path, reverse = false } : {| host? : string, path : string, reverse? : boolean |}) : ?HTMLScriptElement {\n return inlineMemoize(getScript, () : ?HTMLScriptElement => {\n\n const url = `${ host }${ path }`;\n // $FlowFixMe[method-unbinding]\n const scripts = Array.prototype.slice.call(document.getElementsByTagName('script'));\n\n if (reverse) {\n scripts.reverse();\n }\n\n for (const script of scripts) {\n if (!script.src) {\n continue;\n }\n\n const src = script.src.replace(/^https?:\\/\\//, '').split('?')[0];\n\n if (src === url) {\n return script;\n }\n }\n }, [ path ]);\n}\n\nexport function isLocalStorageEnabled() : boolean {\n return inlineMemoize(isLocalStorageEnabled, () => {\n try {\n if (typeof window === 'undefined') {\n return false;\n }\n\n if (window.localStorage) {\n const value = Math.random().toString();\n window.localStorage.setItem('__test__localStorage__', value);\n const result = window.localStorage.getItem('__test__localStorage__');\n window.localStorage.removeItem('__test__localStorage__');\n if (value === result) {\n return true;\n }\n }\n } catch (err) {\n // pass\n }\n return false;\n });\n}\n\nexport function getBrowserLocales() : $ReadOnlyArray<{| country? : string, lang : string |}> {\n const nav = window.navigator;\n\n const locales = nav.languages\n ? [ ...nav.languages ]\n : [];\n\n if (nav.language) {\n locales.push(nav.language);\n }\n\n if (nav.userLanguage) {\n locales.push(nav.userLanguage);\n }\n\n return locales.map(locale => {\n\n if (locale && locale.match(/^[a-z]{2}[-_][A-Z]{2}$/)) {\n const [ lang, country ] = locale.split(/[-_]/);\n return { country, lang };\n }\n\n if (locale && locale.match(/^[a-z]{2}$/)) {\n return { lang: locale };\n }\n\n return null;\n\n }).filter(Boolean);\n}\n\n\nexport function appendChild(container : HTMLElement, child : HTMLElement | Text) {\n container.appendChild(child);\n}\n\nexport function getElementSafe(id : ElementRefType, doc : Document | HTMLElement = document) : ?HTMLElement {\n\n if (isElement(id)) {\n // $FlowFixMe\n return id;\n }\n\n if (typeof id === 'string') {\n return doc.querySelector(id);\n }\n}\n\nexport function getElement(id : ElementRefType, doc : Document | HTMLElement = document) : HTMLElement {\n\n const element = getElementSafe(id, doc);\n\n if (element) {\n return element;\n }\n\n throw new Error(`Can not find element: ${ stringify(id) }`);\n}\n\nexport function elementReady(id : ElementRefType) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const name = stringify(id);\n let el = getElementSafe(id);\n\n if (el) {\n return resolve(el);\n }\n\n if (isDocumentReady()) {\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n\n const interval = setInterval(() => {\n\n el = getElementSafe(id);\n\n if (el) {\n resolve(el);\n clearInterval(interval);\n return;\n }\n\n if (isDocumentReady()) {\n clearInterval(interval);\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n }, 10);\n });\n}\n\n// eslint-disable-next-line unicorn/custom-error-definition\nexport class PopupOpenError extends ExtendableError {}\n\ntype PopupOptions = {|\n name? : string,\n width? : number,\n height? : number,\n top? : number,\n left? : number,\n status? : 0 | 1,\n resizable? : 0 | 1,\n toolbar? : 0 | 1,\n menubar? : 0 | 1,\n scrollbars? : 0 | 1,\n closeOnUnload? : 0 | 1\n|};\n\nexport function popup(url : string, options? : PopupOptions) : CrossDomainWindowType {\n\n // $FlowFixMe\n options = options || {};\n\n const { closeOnUnload = 1, name = '', width, height } = options;\n\n let top = 0;\n let left = 0;\n\n if (width) {\n if (window.outerWidth) {\n left = Math.round((window.outerWidth - width) / 2) + window.screenX;\n } else if (window.screen.width) {\n left = Math.round((window.screen.width - width) / 2);\n }\n }\n\n if (height) {\n if (window.outerHeight) {\n top = Math.round((window.outerHeight - height) / 2) + window.screenY;\n } else if (window.screen.height) {\n top = Math.round((window.screen.height - height) / 2);\n }\n }\n\n delete options.closeOnUnload;\n delete options.name;\n\n if (width && height) {\n // $FlowFixMe\n options = {\n top,\n left,\n width,\n height,\n status: 1,\n toolbar: 0,\n menubar: 0,\n resizable: 1,\n scrollbars: 1,\n ...options\n };\n }\n\n // eslint-disable-next-line array-callback-return\n const params = Object.keys(options).map(key => {\n // $FlowFixMe\n if (options[key] !== null && options[key] !== undefined) {\n return `${ key }=${ stringify(options[key]) }`;\n }\n }).filter(Boolean).join(',');\n\n let win;\n\n try {\n win = window.open(url, name, params);\n } catch (err) {\n throw new PopupOpenError(`Can not open popup window - ${ err.stack || err.message }`);\n }\n\n if (isWindowClosed(win)) {\n const err = new PopupOpenError(`Can not open popup window - blocked`);\n throw err;\n }\n\n if (closeOnUnload) {\n window.addEventListener('unload', () => win.close());\n }\n\n return win;\n}\n\n\nexport function writeToWindow(win : SameDomainWindowType, html : string) {\n try {\n win.document.open();\n win.document.write(html);\n win.document.close();\n } catch (err) {\n try {\n win.location = `javascript: document.open(); document.write(${ JSON.stringify(html) }); document.close();`;\n } catch (err2) {\n // pass\n }\n }\n}\n\nexport function writeElementToWindow(win : SameDomainWindowType, el : HTMLElement) {\n\n const tag = el.tagName.toLowerCase();\n\n if (tag !== 'html') {\n throw new Error(`Expected element to be html, got ${ tag }`);\n }\n\n const documentElement = win.document.documentElement;\n\n for (const child of arrayFrom(documentElement.children)) {\n documentElement.removeChild(child);\n }\n\n for (const child of arrayFrom(el.children)) {\n documentElement.appendChild(child);\n }\n}\n\nexport function setStyle(el : HTMLElement, styleText : string, doc : Document = window.document) {\n // $FlowFixMe\n if (el.styleSheet) {\n // $FlowFixMe\n el.styleSheet.cssText = styleText;\n } else {\n el.appendChild(doc.createTextNode(styleText));\n }\n}\n\nexport type ElementOptionsType = {|\n style? : { [ string ] : string },\n id? : string,\n class? : ?$ReadOnlyArray,\n attributes? : { [ string ] : string },\n styleSheet? : ?string,\n html? : ?string\n|};\n\nlet awaitFrameLoadPromises : WeakMap>;\n\nexport function awaitFrameLoad(frame : HTMLIFrameElement) : ZalgoPromise {\n awaitFrameLoadPromises = awaitFrameLoadPromises || new WeakMap();\n\n if (awaitFrameLoadPromises.has(frame)) {\n const promise = awaitFrameLoadPromises.get(frame);\n if (promise) {\n return promise;\n }\n }\n\n const promise = new ZalgoPromise((resolve, reject) => {\n frame.addEventListener('load', () => {\n linkFrameWindow(frame);\n resolve(frame);\n });\n\n frame.addEventListener('error', (err : Event) => {\n if (frame.contentWindow) {\n resolve(frame);\n } else {\n reject(err);\n }\n });\n });\n\n awaitFrameLoadPromises.set(frame, promise);\n\n return promise;\n}\n\nexport function awaitFrameWindow(frame : HTMLIFrameElement) : ZalgoPromise {\n return awaitFrameLoad(frame).then(loadedFrame => {\n\n if (!loadedFrame.contentWindow) {\n throw new Error(`Could not find window in iframe`);\n }\n\n return loadedFrame.contentWindow;\n });\n}\n\nconst getDefaultCreateElementOptions = () : ElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function createElement(tag : string = 'div', options : ElementOptionsType = getDefaultCreateElementOptions(), container : ?HTMLElement) : HTMLElement {\n\n tag = tag.toLowerCase();\n const element = document.createElement(tag);\n\n if (options.style) {\n extend(element.style, options.style);\n }\n\n if (options.class) {\n element.className = options.class.join(' ');\n }\n\n if (options.id) {\n element.setAttribute('id', options.id);\n }\n\n if (options.attributes) {\n for (const key of Object.keys(options.attributes)) {\n element.setAttribute(key, options.attributes[key]);\n }\n }\n\n if (options.styleSheet) {\n setStyle(element, options.styleSheet);\n }\n\n if (container) {\n appendChild(container, element);\n }\n\n if (options.html) {\n if (tag === 'iframe') {\n // $FlowFixMe\n if (!container || !element.contentWindow) {\n throw new Error(`Iframe html can not be written unless container provided and iframe in DOM`);\n }\n\n // $FlowFixMe\n writeToWindow(element.contentWindow, options.html);\n\n } else {\n element.innerHTML = options.html;\n }\n }\n\n return element;\n}\n\ntype StringMap = {|\n [ string ] : string\n|};\n\nexport type IframeElementOptionsType = {|\n style? : StringMap,\n class? : ?$ReadOnlyArray,\n attributes? : StringMap,\n styleSheet? : ?string,\n html? : ?string,\n url? : ?string\n|};\n\nconst getDefaultIframeOptions = () : IframeElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultStringMap = () : StringMap => {\n // $FlowFixMe\n return {};\n};\n\nexport function iframe(options : IframeElementOptionsType = getDefaultIframeOptions(), container : ?HTMLElement) : HTMLIFrameElement {\n\n const attributes = options.attributes || getDefaultStringMap();\n const style = options.style || getDefaultStringMap();\n\n // $FlowFixMe\n const newAttributes = {\n allowTransparency: 'true',\n ...attributes\n };\n\n // $FlowFixMe\n const newStyle = {\n backgroundColor: 'transparent',\n border: 'none',\n ...style\n };\n\n const frame = createElement('iframe', {\n attributes: newAttributes,\n style: newStyle,\n html: options.html,\n class: options.class\n });\n\n const isIE = window.navigator.userAgent.match(/MSIE|Edge/i);\n\n if (!frame.hasAttribute('id')) {\n frame.setAttribute('id', uniqueID());\n }\n\n // $FlowFixMe\n awaitFrameLoad(frame);\n\n if (container) {\n const el = getElement(container);\n el.appendChild(frame);\n }\n\n if (options.url || isIE) {\n frame.setAttribute('src', options.url || 'about:blank');\n }\n\n // $FlowFixMe\n return frame;\n}\n\nexport function addEventListener(obj : HTMLElement, event : string, handler : (event : Event) => void) : CancelableType {\n obj.addEventListener(event, handler);\n return {\n cancel() {\n obj.removeEventListener(event, handler);\n }\n };\n}\n\nexport function bindEvents(element : HTMLElement, eventNames : $ReadOnlyArray, handler : (event : Event) => void) : CancelableType {\n\n handler = once(handler);\n\n for (const eventName of eventNames) {\n element.addEventListener(eventName, handler);\n }\n\n return {\n cancel: once(() => {\n for (const eventName of eventNames) {\n element.removeEventListener(eventName, handler);\n }\n })\n };\n}\n\nconst VENDOR_PREFIXES = [ 'webkit', 'moz', 'ms', 'o' ];\n\nexport function setVendorCSS(element : HTMLElement, name : string, value : string) {\n\n // $FlowFixMe\n element.style[name] = value;\n\n const capitalizedName = capitalizeFirstLetter(name);\n\n for (const prefix of VENDOR_PREFIXES) {\n // $FlowFixMe\n element.style[`${ prefix }${ capitalizedName }`] = value;\n }\n}\n\nconst ANIMATION_START_EVENTS = [ 'animationstart', 'webkitAnimationStart', 'oAnimationStart', 'MSAnimationStart' ];\nconst ANIMATION_END_EVENTS = [ 'animationend', 'webkitAnimationEnd', 'oAnimationEnd', 'MSAnimationEnd' ];\n\nexport function animate(element : ElementRefType, name : string, clean : (Function) => void, timeout : number = 1000) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const el = getElement(element);\n\n if (!el) {\n return resolve();\n }\n\n let hasStarted = false;\n\n // eslint-disable-next-line prefer-const\n let startTimeout;\n let endTimeout;\n // eslint-disable-next-line prefer-const\n let startEvent;\n // eslint-disable-next-line prefer-const\n let endEvent;\n\n function cleanUp() {\n clearTimeout(startTimeout);\n clearTimeout(endTimeout);\n startEvent.cancel();\n endEvent.cancel();\n }\n\n startEvent = bindEvents(el, ANIMATION_START_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n clearTimeout(startTimeout);\n\n event.stopPropagation();\n\n startEvent.cancel();\n hasStarted = true;\n\n endTimeout = setTimeout(() => {\n cleanUp();\n resolve();\n }, timeout);\n });\n\n endEvent = bindEvents(el, ANIMATION_END_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n cleanUp();\n\n // $FlowFixMe\n if (typeof event.animationName === 'string' && event.animationName !== name) {\n return reject(`Expected animation name to be ${ name }, found ${ event.animationName }`);\n }\n\n return resolve();\n });\n\n setVendorCSS(el, 'animationName', name);\n\n startTimeout = setTimeout(() => {\n if (!hasStarted) {\n cleanUp();\n return resolve();\n }\n }, 200);\n\n if (clean) {\n clean(cleanUp);\n }\n });\n}\n\nexport function makeElementVisible(element : HTMLElement) {\n element.style.setProperty('visibility', '');\n}\n\nexport function makeElementInvisible(element : HTMLElement) {\n element.style.setProperty('visibility', 'hidden', 'important');\n}\n\n\nexport function showElement(element : HTMLElement) {\n element.style.setProperty('display', '');\n}\n\nexport function hideElement(element : HTMLElement) {\n element.style.setProperty('display', 'none', 'important');\n}\n\nexport function destroyElement(element : HTMLElement) {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n}\n\nexport function showAndAnimate(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n const animation = animate(element, name, clean);\n showElement(element);\n return animation;\n}\n\nexport function animateAndHide(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n return animate(element, name, clean).then(() => {\n hideElement(element);\n });\n}\n\nexport function addClass(element : HTMLElement, name : string) {\n element.classList.add(name);\n}\n\nexport function removeClass(element : HTMLElement, name : string) {\n element.classList.remove(name);\n}\n\nexport function isElementClosed(el : HTMLElement) : boolean {\n if (!el || !el.parentNode || !el.ownerDocument || !el.ownerDocument.documentElement || !el.ownerDocument.documentElement.contains(el)) {\n return true;\n }\n return false;\n}\n\nexport function watchElementForClose(element : HTMLElement, handler : () => mixed) : CancelableType {\n handler = once(handler);\n\n let cancelled = false;\n const mutationObservers = [];\n // eslint-disable-next-line prefer-const\n let interval;\n // eslint-disable-next-line prefer-const\n let sacrificialFrame;\n let sacrificialFrameWin;\n\n const cancel = () => {\n cancelled = true;\n for (const observer of mutationObservers) {\n observer.disconnect();\n }\n if (interval) {\n interval.cancel();\n }\n if (sacrificialFrameWin) {\n // eslint-disable-next-line no-use-before-define\n sacrificialFrameWin.removeEventListener('unload', elementClosed);\n }\n if (sacrificialFrame) {\n destroyElement(sacrificialFrame);\n }\n };\n\n const elementClosed = () => {\n if (!cancelled) {\n handler();\n cancel();\n }\n };\n\n if (isElementClosed(element)) {\n elementClosed();\n return { cancel };\n }\n\n // Strategy 1: Mutation observer\n\n if (window.MutationObserver) {\n let mutationElement = element.parentElement;\n while (mutationElement) {\n const mutationObserver = new window.MutationObserver(() => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n });\n\n mutationObserver.observe(mutationElement, { childList: true });\n mutationObservers.push(mutationObserver);\n mutationElement = mutationElement.parentElement;\n }\n }\n\n // Strategy 2: Sacrificial iframe\n\n sacrificialFrame = document.createElement('iframe');\n sacrificialFrame.setAttribute('name', `__detect_close_${ uniqueID() }__`);\n sacrificialFrame.style.display = 'none';\n awaitFrameWindow(sacrificialFrame).then(frameWin => {\n sacrificialFrameWin = assertSameDomain(frameWin);\n sacrificialFrameWin.addEventListener('unload', elementClosed);\n });\n element.appendChild(sacrificialFrame);\n\n // Strategy 3: Poller\n\n const check = () => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n };\n interval = safeInterval(check, 1000);\n\n return { cancel };\n}\n\nexport function fixScripts(el : HTMLElement, doc : Document = window.document) {\n for (const script of querySelectorAll('script', el)) {\n const parentNode = script.parentNode;\n\n if (!parentNode) {\n continue;\n }\n\n const newScript = doc.createElement('script');\n newScript.text = script.textContent;\n parentNode.replaceChild(newScript, script);\n }\n}\n\ntype OnResizeOptions = {|\n width? : boolean,\n height? : boolean,\n interval? : number,\n win? : SameDomainWindowType\n|};\n\nexport function onResize(el : HTMLElement, handler : ({| width : number, height : number |}) => void, { width = true, height = true, interval = 100, win = window } : OnResizeOptions = {}) : {| cancel : () => void |} {\n let currentWidth = el.offsetWidth;\n let currentHeight = el.offsetHeight;\n let canceled = false;\n\n handler({ width: currentWidth, height: currentHeight });\n\n const check = () => {\n if (canceled || !isElementVisible(el)) {\n return;\n }\n\n const newWidth = el.offsetWidth;\n const newHeight = el.offsetHeight;\n\n if ((width && newWidth !== currentWidth) || (height && newHeight !== currentHeight)) {\n handler({ width: newWidth, height: newHeight });\n }\n\n currentWidth = newWidth;\n currentHeight = newHeight;\n };\n\n let observer;\n let timeout;\n\n win.addEventListener('resize', check);\n\n if (typeof win.ResizeObserver !== 'undefined') {\n observer = new win.ResizeObserver(check);\n observer.observe(el);\n timeout = safeInterval(check, interval * 10);\n\n } else if (typeof win.MutationObserver !== 'undefined') {\n observer = new win.MutationObserver(check);\n observer.observe(el, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: false\n });\n timeout = safeInterval(check, interval * 10);\n } else {\n timeout = safeInterval(check, interval);\n }\n\n return {\n cancel: () => {\n canceled = true;\n observer.disconnect();\n window.removeEventListener('resize', check);\n timeout.cancel();\n }\n };\n}\n\nexport function getResourceLoadTime(url : string) : ?number {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n if (typeof performance.getEntries !== 'function') {\n return;\n }\n\n const entries = performance.getEntries();\n\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n\n if (entry && entry.name && entry.name.indexOf(url) === 0 && typeof entry.duration === 'number') {\n return Math.floor(entry.duration);\n }\n }\n}\n\nexport function isShadowElement(element : Node) : boolean {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n return element.toString() === '[object ShadowRoot]';\n}\n\nexport function getShadowRoot(element : Node) : ?Node {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n if (isShadowElement(element)) {\n return element;\n }\n}\n\nexport function getShadowHost(element : Node) : ?HTMLElement {\n const shadowRoot = getShadowRoot(element);\n\n // $FlowFixMe\n if (shadowRoot && shadowRoot.host) {\n // $FlowFixMe\n return shadowRoot.host;\n }\n}\n\n\nexport function insertShadowSlot(element : HTMLElement) : HTMLElement {\n const shadowHost = getShadowHost(element);\n\n if (!shadowHost) {\n throw new Error(`Element is not in shadow dom`);\n }\n\n const slotName = `shadow-slot-${ uniqueID() }`;\n const slot = document.createElement('slot');\n slot.setAttribute('name', slotName);\n element.appendChild(slot);\n\n const slotProvider = document.createElement('div');\n slotProvider.setAttribute('slot', slotName);\n shadowHost.appendChild(slotProvider);\n\n if (isShadowElement(shadowHost)) {\n return insertShadowSlot(slotProvider);\n }\n\n return slotProvider;\n}\n\nexport function preventClickFocus(el : HTMLElement) {\n const onFocus = (event : Event) => {\n el.removeEventListener('focus', onFocus);\n event.preventDefault();\n el.blur();\n return false;\n };\n\n el.addEventListener('mousedown', () => {\n el.addEventListener('focus', onFocus);\n setTimeout(() => {\n el.removeEventListener('focus', onFocus);\n }, 1);\n });\n}\n\nexport function getStackTrace() : string {\n try {\n throw new Error('_');\n }\n catch (err) {\n return err.stack || '';\n }\n}\n\nfunction inferCurrentScript() : ?HTMLScriptElement {\n try {\n const stack = getStackTrace();\n const stackDetails = (/.*at [^(]*\\((.*):(.+):(.+)\\)$/ig).exec(stack);\n const scriptLocation = stackDetails && stackDetails[1];\n\n if (!scriptLocation) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n for (const script of Array.prototype.slice.call(document.getElementsByTagName('script')).reverse()) {\n if (script.src && script.src === scriptLocation) {\n return script;\n }\n }\n\n } catch (err) {\n // pass\n }\n}\n\n// eslint-disable-next-line compat/compat\nlet currentScript = typeof document !== 'undefined' ? document.currentScript : null;\n\ntype GetCurrentScript = () => HTMLScriptElement;\n\nexport const getCurrentScript : GetCurrentScript = memoize(() => {\n if (currentScript) {\n return currentScript;\n }\n\n currentScript = inferCurrentScript();\n\n if (currentScript) {\n return currentScript;\n }\n\n throw new Error('Can not determine current script');\n});\n\nconst currentUID = uniqueID();\n\ntype GetCurrentScriptUID = () => string;\n\nexport const getCurrentScriptUID : GetCurrentScriptUID = memoize(() => {\n let script;\n\n try {\n script = getCurrentScript();\n } catch (err) {\n return currentUID;\n }\n\n let uid = script.getAttribute(ATTRIBUTES.UID);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n uid = script.getAttribute(`${ ATTRIBUTES.UID }-auto`);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n if (script.src) {\n\n const { src, dataset } = script;\n const stringToHash = JSON.stringify({ src, dataset });\n const hashedString = strHashStr(stringToHash);\n const hashResult = hashedString.slice(hashedString.length - UID_HASH_LENGTH);\n\n uid = `uid_${ hashResult }`;\n } else {\n uid = uniqueID();\n }\n\n script.setAttribute(`${ ATTRIBUTES.UID }-auto`, uid);\n\n return uid;\n});\n\ntype SubmitFormOptions = {|\n url : string,\n target : string,\n body? : {| [string] : string | boolean |},\n method? : string\n|};\n\nexport function submitForm({ url, target, body, method = 'post' } : SubmitFormOptions) {\n const form = document.createElement('form');\n form.setAttribute('target', target);\n form.setAttribute('method', method);\n form.setAttribute('action', url);\n form.style.display = 'none';\n\n if (body) {\n for (const key of Object.keys(body)) {\n const input = document.createElement('input');\n input.setAttribute('name', key);\n input.setAttribute('value', body[key]?.toString());\n form.appendChild(input);\n }\n }\n\n getBody().appendChild(form);\n form.submit();\n getBody().removeChild(form);\n}\n","/* @flow */\n\nexport function isPerc(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+%$/).test(str);\n}\n\nexport function isPx(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+px$/).test(str);\n}\n\nexport function toNum(val : string | number) : number {\n\n if (typeof val === 'number') {\n return val;\n }\n\n const match = val.match(/^([0-9]+)(px|%)$/);\n\n if (!match) {\n throw new Error(`Could not match css value from ${ val }`);\n }\n\n return parseInt(match[1], 10);\n}\n\nexport function toPx(val : number | string) : string {\n return `${ toNum(val) }px`;\n}\n\nexport function toCSS(val : number | string) : string {\n\n if (typeof val === 'number') {\n return toPx(val);\n }\n\n return isPerc(val) ? val : toPx(val);\n}\n\nexport function percOf(num : number, perc : string) : number {\n return parseInt(num * toNum(perc) / 100, 10);\n}\n\nexport function normalizeDimension(dim : string | number, max : number) : number {\n if (typeof dim === 'number') {\n return dim;\n } else if (isPerc(dim)) {\n return percOf(max, dim);\n } else if (isPx(dim)) {\n return toNum(dim);\n } else {\n throw new Error(`Can not normalize dimension: ${ dim }`);\n }\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type SameDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\nimport { getOrSet, getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__POST_ROBOT__.__SCRIPT_NAMESPACE__) {\n return `${ __POST_ROBOT__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __POST_ROBOT__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : SameDomainWindowType = window) : Object {\n const globalKey = getGlobalKey();\n\n if (win !== window) {\n return win[globalKey];\n }\n const global : Object = win[globalKey] = win[globalKey] || {};\n return global;\n}\n\nexport function deleteGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n\ntype ObjectGetter = () => Object;\nconst getObj : ObjectGetter = () => ({});\n\ntype GetOrSet = ((string, () => T) => T) & ((string, () => void) => void);\n\ntype GlobalStore = {|\n get : ((string, T) => T) & ((string, void) => T | void),\n set : (string, T) => T,\n has : (string) => boolean,\n del : (string) => void,\n getOrSet : GetOrSet,\n reset : () => void,\n keys : () => $ReadOnlyArray\n|};\n\nexport function globalStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : GlobalStore {\n return getOrSet(getGlobal(), key, () => {\n let store = defStore();\n\n return {\n has: (storeKey) => {\n return store.hasOwnProperty(storeKey);\n },\n get: (storeKey, defVal) => {\n // $FlowFixMe\n return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal;\n },\n set: (storeKey, val) => {\n store[storeKey] = val;\n return val;\n },\n del: (storeKey) => {\n delete store[storeKey];\n },\n getOrSet: (storeKey, getter) => {\n // $FlowFixMe\n return getOrSet(store, storeKey, getter);\n },\n reset: () => {\n store = defStore();\n },\n keys: () => {\n return Object.keys(store);\n }\n };\n });\n}\n\nexport class WildCard {}\n\nexport function getWildcard() : WildCard {\n const global = getGlobal();\n global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard();\n return global.WINDOW_WILDCARD;\n}\n\ntype WindowStore = {|\n get : ((CrossDomainWindowType | WildCard, T) => T) & ((CrossDomainWindowType | WildCard, void) => T | void),\n set : (CrossDomainWindowType | WildCard, T) => T,\n has : (CrossDomainWindowType | WildCard) => boolean,\n del : (CrossDomainWindowType | WildCard) => void,\n getOrSet : (CrossDomainWindowType | WildCard, () => T) => T\n|};\n\nexport function windowStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : WindowStore {\n return globalStore('windowStore').getOrSet(key, () => {\n const winStore = new WeakMap();\n\n const getStore = (win : CrossDomainWindowType | WildCard) : ObjectGetter => {\n return winStore.getOrSet(win, defStore);\n };\n \n return {\n has: (win) => {\n const store = getStore(win);\n return store.hasOwnProperty(key);\n },\n get: (win, defVal) => {\n const store = getStore(win);\n // $FlowFixMe\n return store.hasOwnProperty(key) ? store[key] : defVal;\n },\n set: (win, val) => {\n const store = getStore(win);\n store[key] = val;\n return val;\n },\n del: (win) => {\n const store = getStore(win);\n delete store[key];\n },\n getOrSet: (win, getter) => {\n const store = getStore(win);\n return getOrSet(store, key, getter);\n }\n };\n });\n}\n","/* @flow */\n\nexport const KEY_CODES = {\n ENTER: 13,\n SPACE: 32\n};\n\nexport const ATTRIBUTES = {\n UID: 'data-uid'\n};\n\nexport const UID_HASH_LENGTH = 30;\n","/* @flow */\n\nimport { getAncestor, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { windowStore, globalStore, getGlobal } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nfunction getInstanceID() : string {\n return globalStore('instance').getOrSet('instanceID', uniqueID);\n}\n\nfunction getHelloPromise(win : CrossDomainWindowType) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n return helloPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nfunction resolveHelloPromise(win : CrossDomainWindowType, { domain }) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n const existingPromise = helloPromises.get(win);\n if (existingPromise) {\n existingPromise.resolve({ domain });\n }\n const newPromise = ZalgoPromise.resolve({ domain });\n helloPromises.set(win, newPromise);\n return newPromise;\n}\n\nfunction listenForHello({ on } : {| on : OnType |}) : CancelableType {\n return on(MESSAGE_NAME.HELLO, { domain: WILDCARD }, ({ source, origin }) => {\n resolveHelloPromise(source, { domain: origin });\n return { instanceID: getInstanceID() };\n });\n}\n\nexport function sayHello(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise<{| win : CrossDomainWindowType, domain : string, instanceID : string |}> {\n return send(win, MESSAGE_NAME.HELLO, { instanceID: getInstanceID() }, { domain: WILDCARD, timeout: -1 })\n .then(({ origin, data: { instanceID } }) => {\n resolveHelloPromise(win, { domain: origin });\n return { win, domain: origin, instanceID };\n });\n}\n\nexport function getWindowInstanceID(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return windowStore('windowInstanceIDPromises').getOrSet(win, () => {\n return sayHello(win, { send }).then(({ instanceID }) => instanceID);\n });\n}\n\nexport function initHello({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('helloListener', () => {\n const listener = listenForHello({ on });\n\n const parent = getAncestor();\n if (parent) {\n sayHello(parent, { send }).catch(err => {\n // $FlowFixMe\n if (__TEST__ && getGlobal(parent)) {\n throw err;\n }\n });\n }\n\n return listener;\n });\n}\n\nexport function awaitWindowHello(win : CrossDomainWindowType, timeout : number = 5000, name : string = 'Window') : ZalgoPromise<{| domain : string |}> {\n let promise = getHelloPromise(win);\n\n if (timeout !== -1) {\n promise = promise.timeout(timeout, new Error(`${ name } did not load after ${ timeout }ms`));\n }\n\n return promise;\n}\n","/* @flow */\n\nexport const MESSAGE_TYPE = {\n REQUEST: ('postrobot_message_request' : 'postrobot_message_request'),\n RESPONSE: ('postrobot_message_response' : 'postrobot_message_response'),\n ACK: ('postrobot_message_ack' : 'postrobot_message_ack')\n};\n\nexport const MESSAGE_ACK = {\n SUCCESS: ('success' : 'success'),\n ERROR: ('error' : 'error')\n};\n\nexport const MESSAGE_NAME = {\n METHOD: ('postrobot_method' : 'postrobot_method'),\n HELLO: ('postrobot_hello' : 'postrobot_hello'),\n OPEN_TUNNEL: ('postrobot_open_tunnel' : 'postrobot_open_tunnel')\n};\n\nexport const SEND_STRATEGY = {\n POST_MESSAGE: ('postrobot_post_message' : 'postrobot_post_message'),\n BRIDGE: ('postrobot_bridge' : 'postrobot_bridge'),\n GLOBAL: ('postrobot_global' : 'postrobot_global')\n};\n\nexport const BRIDGE_NAME_PREFIX = '__postrobot_bridge__';\nexport const POSTROBOT_PROXY = '__postrobot_proxy__';\n\nexport const WILDCARD = '*';\n\nexport const SERIALIZATION_TYPE = {\n CROSS_DOMAIN_ZALGO_PROMISE: ('cross_domain_zalgo_promise' : 'cross_domain_zalgo_promise'),\n CROSS_DOMAIN_FUNCTION: ('cross_domain_function' : 'cross_domain_function'),\n CROSS_DOMAIN_WINDOW: ('cross_domain_window' : 'cross_domain_window')\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { windowStore } from '../global';\n\nexport function markWindowKnown(win : CrossDomainWindowType) {\n const knownWindows = windowStore('knownWindows');\n knownWindows.set(win, true);\n}\n\nexport function isWindowKnown(win : CrossDomainWindowType) : boolean {\n const knownWindows = windowStore('knownWindows');\n return knownWindows.get(win, false);\n}\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { CustomSerializedType } from './types';\n\nexport function isSerializedType(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null && typeof item.__type__ === 'string');\n}\n\nexport function determineType(val : mixed) : $Values | void {\n if (typeof val === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n if (val === null) {\n return TYPE.NULL;\n }\n\n if (Array.isArray(val)) {\n return TYPE.ARRAY;\n }\n\n if (typeof val === 'function') {\n return TYPE.FUNCTION;\n }\n\n if (typeof val === 'object') {\n\n if (val instanceof Error) {\n return TYPE.ERROR;\n }\n\n if (typeof val.then === 'function') {\n return TYPE.PROMISE;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object RegExp]') {\n return TYPE.REGEX;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object Date]') {\n return TYPE.DATE;\n }\n\n return TYPE.OBJECT;\n }\n\n if (typeof val === 'string') {\n return TYPE.STRING;\n }\n\n if (typeof val === 'number') {\n return TYPE.NUMBER;\n }\n\n if (typeof val === 'boolean') {\n return TYPE.BOOLEAN;\n }\n}\n\nexport function serializeType(type : T, val : V) : CustomSerializedType {\n return {\n __type__: type,\n __val__: val\n };\n}\n","/* @flow */\n\nexport const TYPE = {\n FUNCTION: ('function' : 'function'),\n ERROR: ('error' : 'error'),\n PROMISE: ('promise' : 'promise'),\n REGEX: ('regex' : 'regex'),\n DATE: ('date' : 'date'),\n ARRAY: ('array' : 'array'),\n OBJECT: ('object' : 'object'),\n STRING: ('string' : 'string'),\n NUMBER: ('number' : 'number'),\n BOOLEAN: ('boolean' : 'boolean'),\n NULL: ('null' : 'null'),\n UNDEFINED: ('undefined' : 'undefined')\n};\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { Thenable, CustomSerializedType, NativeSerializedType } from './types';\nimport { determineType, isSerializedType } from './common';\nimport {\n serializeFunction,\n serializeError, type SerializedError,\n serializePromise,\n serializeRegex, type SerializedRegex,\n serializeDate, type SerializedDate,\n serializeArray,\n serializeObject,\n serializeString,\n serializeNumber,\n serializeBoolean,\n serializeNull,\n serializeUndefined\n} from './serializers';\n\ntype NativeSerializer> = (value : V, key : string) => NativeSerializedType;\ntype CustomSerializer = (value : V, key : string) => CustomSerializedType;\ntype PrimitiveSerializer = (value : V, key : string) => S;\ntype CustomOrPrimitiveSerializer = CustomSerializer | PrimitiveSerializer;\ntype NativeOrCustomOrPrimitiveSerializer = NativeSerializer | CustomOrPrimitiveSerializer;\n\ntype Serializers = {|\n function? : CustomOrPrimitiveSerializer,\n error? : NativeOrCustomOrPrimitiveSerializer,\n promise? : CustomOrPrimitiveSerializer,\n regex? : NativeOrCustomOrPrimitiveSerializer,\n date? : NativeOrCustomOrPrimitiveSerializer,\n array? : CustomOrPrimitiveSerializer<$ReadOnlyArray, typeof TYPE.ARRAY>,\n object? : CustomOrPrimitiveSerializer