{"version":3,"sources":["webpack://zoid/webpack/universalModuleDefinition","webpack://zoid/webpack/bootstrap","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/extends.js","webpack://zoid/./node_modules/zalgo-promise/src/utils.js","webpack://zoid/./node_modules/zalgo-promise/src/exceptions.js","webpack://zoid/./node_modules/zalgo-promise/src/flush.js","webpack://zoid/./node_modules/zalgo-promise/src/promise.js","webpack://zoid/./node_modules/cross-domain-utils/src/util.js","webpack://zoid/./node_modules/cross-domain-utils/src/constants.js","webpack://zoid/./node_modules/cross-domain-utils/src/utils.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/util.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/weakmap.js","webpack://zoid/./node_modules/belter/src/util.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/native.js","webpack://zoid/./node_modules/belter/src/dom.js","webpack://zoid/./node_modules/belter/src/css.js","webpack://zoid/./node_modules/post-robot/src/global.js","webpack://zoid/./node_modules/post-robot/src/lib/hello.js","webpack://zoid/./node_modules/post-robot/src/conf/constants.js","webpack://zoid/./node_modules/post-robot/src/lib/windows.js","webpack://zoid/./node_modules/universal-serialize/src/common.js","webpack://zoid/./node_modules/universal-serialize/src/constants.js","webpack://zoid/./node_modules/universal-serialize/src/serialize.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/function.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/error.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/promise.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/regex.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/date.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/array.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/object.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/string.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/number.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/boolean.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/null.js","webpack://zoid/./node_modules/universal-serialize/src/deserialize.js","webpack://zoid/./node_modules/post-robot/src/serialize/window.js","webpack://zoid/./node_modules/post-robot/src/bridge/common.js","webpack://zoid/./node_modules/post-robot/src/serialize/function.js","webpack://zoid/./node_modules/post-robot/src/serialize/serialize.js","webpack://zoid/./node_modules/post-robot/src/serialize/promise.js","webpack://zoid/./node_modules/post-robot/src/drivers/send/strategies.js","webpack://zoid/./node_modules/post-robot/src/drivers/send/index.js","webpack://zoid/./node_modules/post-robot/src/drivers/listeners.js","webpack://zoid/./node_modules/post-robot/src/lib/compat.js","webpack://zoid/./node_modules/post-robot/src/drivers/receive/types.js","webpack://zoid/./node_modules/post-robot/src/drivers/receive/index.js","webpack://zoid/./node_modules/post-robot/src/public/on.js","webpack://zoid/./node_modules/post-robot/src/public/send.js","webpack://zoid/./node_modules/post-robot/src/conf/config.js","webpack://zoid/./node_modules/post-robot/src/setup.js","webpack://zoid/./src/lib/global.js","webpack://zoid/./src/lib/serialize.js","webpack://zoid/./src/constants.js","webpack://zoid/./src/child/props.js","webpack://zoid/./src/child/window.js","webpack://zoid/./src/child/child.js","webpack://zoid/./src/parent/props.js","webpack://zoid/./src/parent/parent.js","webpack://zoid/./node_modules/post-robot/src/clean.js","webpack://zoid/./src/component/templates/container.js","webpack://zoid/./src/component/props.js","webpack://zoid/./src/component/component.js"],"names":["root","factory","exports","module","define","amd","self","this","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","hasOwnProperty","p","s","_extends","assign","target","arguments","length","source","apply","isPromise","item","Promise","window","Window","constructor","toString","then","err","flushPromise","dispatchedErrors","possiblyUnhandledPromiseHandlers","activeCount","flushActive","promise","resolve","startActive","endActive","ZalgoPromise","handler","resolved","rejected","errorHandled","error","handlers","dispatching","stack","result","isAsync","res","reject","Error","dispatch","setTimeout","indexOf","push","j","dispatchPossiblyUnhandledError","asyncReject","chain","firstPromise","secondPromise","onSuccess","onError","catch","undefined","finally","onFinally","try","timeout","time","clearTimeout","toPromise","TypeError","all","promises","count","results","prom","hash","awaitPromises","map","items","method","onPossiblyUnhandledException","cancel","splice","context","args","delay","flush","isRegex","WINDOW_TYPE","IFRAME","POPUP","IE_WIN_ACCESS_ERROR","isAboutProtocol","win","location","protocol","getParent","parent","getOpener","opener","canReadFromWindow","getActualDomain","PROTOCOL","host","getDomain","domain","mockDomain","isSameDomain","desc","getOwnPropertyDescriptor","isActuallySameDomain","assertSameDomain","isAncestorParent","child","childParent","getParents","getFrames","frames","len","frame","getAllChildFrames","getTop","top","getAllFramesInWindow","iframeWindows","iframeFrames","isWindowClosed","allowMock","closed","message","mockclosed","iframeIndex","collection","safeIndexOf","contentWindow","parentNode","doc","ownerDocument","documentElement","contains","isFrameWindowClosed","getAncestor","anyMatch","collection1","collection2","item1","getDistanceFromTop","distance","isSameTopWindow","win1","win2","top1","top2","allFrames1","allFrames2","opener1","opener2","matchDomain","pattern","origin","Array","isArray","Boolean","match","JSON","stringify","some","subpattern","getDomainFromUrl","url","split","slice","join","onCloseWindow","callback","maxtime","Infinity","check","isWindow","obj","__cross_domain_utils_window_check__","closeWindow","close","objectIDs","CrossDomainSafeWeakMap","weakmap","keys","values","Math","random","WeakMap","freeze","testWeakMap","testKey","set","hasNativeWeakMap","_cleanupClosedWindows","delete","isSafeToReadWrite","entry","writable","index","has","getOrSet","getFunctionName","fn","__name__","displayName","setFunctionName","base64encode","str","btoa","encodeURIComponent","replace","p1","String","fromCharCode","parseInt","Buffer","from","uniqueID","chars","charAt","floor","Date","toISOString","toLowerCase","serializeArgs","subkey","val","uid","getObjectID","awaitFrameLoadPromises","memoizedFunctions","memoize","options","cacheMap","memoizedFunction","cache","thisNamespace","cacheTime","now","reset","memoizePromise","memoizedPromiseFunction","inlineMemoize","logic","__inline_memoize_cache__","noop","once","called","stringifyError","level","newErr","extend","identity","safeInterval","loop","arrayFrom","isDefined","cleanup","tasks","cleaned","register","task","shift","assertExists","thing","isDocumentReady","document","body","readyState","urlEncode","waitForDocumentReady","interval","setInterval","clearInterval","parseQuery","queryString","params","pair","decodeURIComponent","extendQuery","originalQuery","props","filter","appendChild","container","isElement","element","Element","nodeType","style","getElementSafe","id","querySelector","PopupOpenError","awaitFrameLoad","addEventListener","cleanIframes","linkFrameWindow","awaitFrameWindow","loadedFrame","iframe","tag","el","styleText","createElement","class","className","setAttribute","attributes","styleSheet","cssText","createTextNode","html","innerHTML","allowTransparency","backgroundColor","border","isIE","navigator","userAgent","hasAttribute","getElement","event","removeEventListener","showElement","setProperty","hideElement","destroyElement","removeChild","isElementClosed","onResize","width","height","currentWidth","offsetWidth","currentHeight","offsetHeight","observer","newWidth","newHeight","ResizeObserver","observe","MutationObserver","childList","subtree","characterData","disconnect","isShadowElement","toPx","toNum","toCSS","test","getGlobal","clear","prototype","getObj","globalStore","defStore","store","storeKey","defVal","del","WildCard","getWildcard","global","WINDOW_WILDCARD","windowStore","winStore","getStore","getInstanceID","resolveHelloPromise","helloPromises","existingPromise","newPromise","sayHello","send","instanceID","data","getWindowInstanceID","markWindowKnown","isSerializedType","__type__","determineType","serializeType","type","__val__","SERIALIZER","code","toJSON","defaultSerializers","DESERIALIZER","RegExp","defaultDeserializers","cleanupProxyWindows","idToProxyWindow","shouldClean","getSerializedWindow","winPromise","windowNamePromise","windowTypePromise","getType","getName","focus","isClosed","setLocation","href","setName","sameDomain","frameElement","querySelectorAll","getFrameForWindow","ProxyWindow","serializedWindow","isProxyWindow","actualWindow","actualWindowPromise","getID","setWindow","isPopup","isPopupPromise","getNamePromise","reopenPromise","open","focusPromise","getWindow","awaitWindow","matchWindow","proxyInstanceID","knownWindowInstanceID","unwrap","serialize","toProxyWindow","deserialize","addMethod","methodStore","proxyWindowMethods","lookupMethod","serializeFunction","destination","on","meth","methodSource","arg","__id__","serializeMessage","serializers","serializer","serializePromise","deserializeMessage","deserializers","parse","deserializer","serializedPromise","deserializePromise","serializedFunction","getDeserializedFunction","opts","crossDomainFunctionWrapper","fireAndForget","__origin__","__source__","deserializeFunction","SEND_MESSAGE_STRATEGIES","sendMessage","domainBuffer","buffer","serializedMessage","strategies","errors","strategyName","getResponseListener","deleteResponseListener","isResponseListenerErrored","getRequestListener","requestListeners","winQualifier","nameListeners","domainListeners","listener","regex","postMessage","mockUserAgent","getUserAgent","foreignGlobal","receiveMessage","RECEIVE_MESSAGE_TYPES","logName","sendResponse","ack","pathname","handleError","receivedMessages","messages","parsedMessage","parseMessages","deserializeMessages","requestListener","addRequestListener","listenersCollection","existingListener","regexListeners","regexListener","strDomain","errorHandler","domainMatcher","responseTimeout","childTimeout","validateOptions","actualParent","isAncestor","getHelloPromise","awaitWindowHello","targetDomain","actualDomain","normalizedDomain","normalizeDomain","responseListener","addResponseListener","reqPromises","markResponseListenerErrored","totalAckTimeout","isWindowKnown","totalResTimeout","ackTimeout","resTimeout","cancelled","max","internalSerializeMessage","internalDeserializeMessage","getProxyObject","PROP_TYPE","STRING","OBJECT","FUNCTION","BOOLEAN","NUMBER","ARRAY","PROP_SERIALIZATION","DOTIFY","BASE64","CONTEXT","EVENT","RENDER","RENDERED","DISPLAY","ERROR","CLOSE","DESTROY","PROPS","RESIZE","FOCUS","normalizeChildProp","propsDef","helpers","prop","childDecorate","onProps","resize","getParentDomain","show","hide","parseChildWindowName","windowName","zoidcomp","encodedPayload","atob","charCodeAt","base64decode","getChildPayload","destroy","getQueryParam","queryParam","getQueryValue","queryValue","parentComponent","overrides","parentWin","triggered","currentProxyWin","currentProxyContainer","childComponent","containerTemplate","prerenderTemplate","dimensions","autoResize","domainMatch","initPromise","handledErrors","clean","state","internalState","visible","eventName","handlerList","trigger","triggerOnce","onErrorOverride","getProxyContainerOverride","getProxyContainer","showOverride","hideOverride","closeOverride","renderContainerOverride","renderContainer","getProxyWindowOverride","getProxyWindow","setProxyWinOverride","setProxyWin","openFrameOverride","openFrame","openPrerenderFrameOverride","openPrerenderFrame","prerenderOverride","prerender","openOverride","openPrerenderOverride","openPrerender","watchForUnloadOverride","watchForUnload","getInternalStateOverride","getInternalState","setInternalStateOverride","setInternalState","getPropsForChild","sendToChild","newInternalState","windowProp","proxyWin","containerElement","shadowHost","shadowRoot","getShadowRoot","getShadowHost","slotName","slot","slotProvider","insertShadowSlot","setState","getUrl","getAttributes","getChildDomain","getDomainMatcher","title","proxyPrerenderFrame","prerenderFrame","prerenderFrameWindow","getWindowRef","windows","initChild","childExports","proxyFrame","frameWatcher","cleanUpWindow","unloadWindowListener","closeParentWindowListener","checkWindowClose","secondIsClosed","renderTemplate","renderer","proxyPrerenderWin","prerenderWindow","isBlankDomain","tagName","children","writeElementToWindow","prerenderResizeListener","proxyContainer","innerContainer","getHelpers","updateProps","setProps","newProps","isUpdate","inputProps","propNames","aliases","propDef","alias","default","decorate","required","extendProps","childProps","init","onRender","onDisplay","onRendered","onClose","onDestroy","onFocus","render","ZOID","childDomain","checkAllowRender","delegatePromise","delegateProps","propName","allowDelegate","childOverridesPromise","POST_MESSAGE","getDelegateOverrides","childOverrides","delegate","watchForUnloadPromise","buildUrlPromise","serialization","dotify","prefix","newobj","every","dotkey","propsToQuery","query","originalUrl","originalHash","hashString","extendUrl","normalizeMockUrl","onRenderPromise","getProxyContainerPromise","getProxyWindowPromise","buildWindowNamePromise","propRef","getPropsRef","propsRef","version","__ZOID__","parentDomain","checkClose","buildChildPayload","childPayload","openFramePromise","openPrerenderFramePromise","renderContainerPromise","openPromise","openPrerenderPromise","setStatePromise","prerenderPromise","setWindowNamePromise","loadUrlPromise","builtUrl","watchForClosePromise","watchForClose","onDisplayPromise","openBridgePromise","runTimeoutPromise","onRenderedPromise","defaultContainerTemplate","div","cspNonce","classList","add","remove","defaultNoop","decorateOnce","component","bridgeUrl","allowedParentDomains","defaultContext","validate","eligible","logger","info","normalizeOptions","instances","isChild","payload","registerChild","xprops","components","onPropHandlers","parentComponentWindow","ref","getNthParent","ancestor","getParentComponentWindow","normalizedProps","normalizeChildProps","checkParentDomain","getAutoResize","getProps","getPropsByRef","instance","eligibility","reason","getDefaultContext","finalContext","getDefaultContainer","isEligible","clone","renderTo","driver","driverName","dep","canRenderTo","initialized","sourceElement","originalEvent","messageListener","listenForMessages","initHello","comp","destroyAll","destroyPromise","destroyComponents","responseListeners","cancelResponseListeners"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,OAAQ,GAAIH,GACO,iBAAZC,QACdA,QAAc,KAAID,IAElBD,EAAW,KAAIC,IARjB,CASoB,oBAATK,KAAuBA,KAAOC,MAAO,WAChD,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUR,QAGnC,IAAIC,EAASK,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHV,QAAS,IAUV,OANAW,EAAQH,GAAUI,KAAKX,EAAOD,QAASC,EAAQA,EAAOD,QAASO,GAG/DN,EAAOS,GAAI,EAGJT,EAAOD,QA0Df,OArDAO,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASf,EAASgB,EAAMC,GAC3CV,EAAoBW,EAAElB,EAASgB,IAClCG,OAAOC,eAAepB,EAASgB,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEV,EAAoBgB,EAAI,SAASvB,GACX,oBAAXwB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAepB,EAASwB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAepB,EAAS,aAAc,CAAE0B,OAAO,KAQvDnB,EAAoBoB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQnB,EAAoBmB,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,iBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF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,EAAK4G,OAAS,SAACzyB,EAAM2yB,GAAP,OAAeQ,EAAKV,OAAOzyB,EAAM2yB,IAC/C9G,EAAKkF,QAAU,kBAAMoC,EAAKpC,WAC1BlF,EAAK+G,YAAc,SAAChsB,GAAD,OAASusB,EAAKP,YAAYhsB,IAC7CilB,EAAKiF,UAAYqC,EAAKrC,UAEtB,IAAM9oB,EAAQmrB,EAAKlC,gBAKnB,OAJIjpB,IACA9F,OAAOgvB,OAASrF,EAAKqF,OAASlpB,EAAM8pB,YAGjCjG,EAGJ,SAASuH,KAKZ,IAAMC,EAAiBvN,GAAMzgB,MAE7B,OADAygB,GAAQ3U,KACDkiB,EAGJ,IAAMC,GAAoBF,GAE1B,SAASzO,KZ7YT,IJiHG3F,EgB6RNoU,YXtaOlxB,OAAM,gBRgCV,WAAmC,IACtC,IAAMqxB,EAAoBjc,GAAY,qBADA,MAEnBic,EAAkB9mB,OAFC,eAEO,CAAxC,IAAM/G,EAAI,KACLsZ,EAAWuU,EAAkBjzB,IAAIoF,GACnCsZ,IACAA,EAAS+C,WAAY,GAEzBwR,EAAkB5b,IAAIjS,IOd1B8tB,IJgHMxU,EAAW1H,KAAchX,IAAI,yBAE/B0e,EAAShZ,gB7B9IN9D,OAAM","file":"zoid.frame.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"zoid\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"zoid\"] = factory();\n\telse\n\t\troot[\"zoid\"] = factory();\n})((typeof self !== 'undefined' ? self : this), function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export default function _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}","/* @flow */\n\nexport function isPromise(item : mixed) : boolean {\n try {\n if (!item) {\n return false;\n }\n\n if (typeof Promise !== 'undefined' && item instanceof Promise) {\n return true;\n }\n\n if (typeof window !== 'undefined' && typeof window.Window === 'function' && item instanceof window.Window) {\n return false;\n }\n\n if (typeof window !== 'undefined' && typeof window.constructor === 'function' && item instanceof window.constructor) {\n return false;\n }\n\n let toString = ({}).toString;\n\n if (toString) {\n let name = toString.call(item);\n\n if (name === '[object Window]' || name === '[object global]' || name === '[object DOMWindow]') {\n return false;\n }\n }\n\n if (typeof item.then === 'function') {\n return true;\n }\n } catch (err) {\n return false;\n }\n\n return false;\n}\n","/* @flow */\n\nimport type { ZalgoPromise } from './promise';\n\nconst dispatchedErrors = [];\nconst possiblyUnhandledPromiseHandlers : Array<(mixed, promise? : ZalgoPromise) => 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 let 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 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 let 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 let { 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 let { 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\n if (result.resolved) {\n promise.resolve(result.value);\n } else {\n promise.reject(result.error);\n }\n\n result.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 let promise : ZalgoPromise = 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 return this.then(undefined, onError);\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 let 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 static resolve(value : X | ZalgoPromise) : ZalgoPromise {\n\n if (value instanceof ZalgoPromise) {\n return value;\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 let promise = new ZalgoPromise();\n let count = promises.length;\n let results = [];\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 let 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 let result = {};\n let awaitPromises = [];\n\n for (const key in promises) {\n if (promises.hasOwnProperty(key)) {\n let 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 : Array, method : (T) => (ZalgoPromise | X)) : ZalgoPromise> {\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 : A) => (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;\n\n startActive();\n \n try {\n // $FlowFixMe\n result = method.apply(context, args || []);\n } catch (err) {\n endActive();\n return ZalgoPromise.reject(err);\n }\n\n endActive();\n\n return ZalgoPromise.resolve(result);\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 return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : Array) {\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\nlet IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return win.location.protocol === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return win.location.protocol === PROTOCOL.ABOUT;\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 let location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n let protocol = location.protocol;\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 let parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n let 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 let 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 let 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 (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\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) : Array {\n\n let 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 let 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) : Array {\n\n let 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) : Array {\n\n let result = [];\n\n for (let frame of getFrames(win)) {\n result.push(frame);\n\n for (let 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 (let 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 let 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 let 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 let frames = getAllFramesInWindow(win);\n let 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 let 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 : Array, 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\nlet iframeWindows = [];\nlet 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 let iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n let 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 let winFrames = getFrames(win);\n\n for (let 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 let frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (let childFrame of getFrames(win)) {\n let namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n let frame;\n\n frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n let top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n let frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (let 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 let opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n let parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : Array {\n\n let 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 let 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 (let 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 (let item1 of collection1) {\n for (let 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 let top1 = getTop(win1) || win1;\n let 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 let allFrames1 = getAllFramesInWindow(win1);\n let allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n let opener1 = getOpener(top1);\n let 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 let 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 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 closeWindow(win : CrossDomainWindowType) {\n try {\n win.close();\n } catch (err) {\n // pass\n }\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","/* @flow */\n\nexport function safeIndexOf(collection : Array, 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 : Array) {\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 keys : 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 let weakmap = this.weakmap;\n let keys = this.keys;\n\n for (let i = 0; i < keys.length; i++) {\n let 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 let 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 let name = this.name;\n let 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 let keys = this.keys;\n let values = this.values;\n let 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 let 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 let 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 let keys = this.keys;\n let 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 let 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 let 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 let keys = this.keys;\n let 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 let 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 let 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 let 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 let value = getter();\n this.set(key, value);\n return value;\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 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 }));\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf8').toString('base64');\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 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 `${ 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 return JSON.stringify(Array.prototype.slice.call(args), (subkey, val) => {\n if (typeof val === 'function') {\n return `memoize[${ getObjectID(val) }]`;\n }\n return val;\n });\n } catch (err) {\n throw new Error(`Arguments not serializable -- can not be used to memoize`);\n }\n}\ntype MemoizeOptions = {|\n name? : string,\n time? : number,\n thisNamespace? : boolean\n|};\n\nconst getDefaultMemoizeOptions = () : MemoizeOptions => {\n // $FlowFixMe\n return {};\n};\n\nconst memoizedFunctions = [];\n\nexport function memoize(method : F, options? : MemoizeOptions = getDefaultMemoizeOptions()) : F & {| reset : () => void |} {\n const cacheMap = new WeakMap();\n\n const memoizedFunction = function memoizedFunction(...args) : mixed {\n const cache = cacheMap.getOrSet(options.thisNamespace ? this : method, () => ({}));\n\n const key : string = serializeArgs(args);\n\n const cacheTime = options.time;\n if (cache[key] && cacheTime && (Date.now() - cache[key].time) < cacheTime) {\n delete cache[key];\n }\n\n if (cache[key]) {\n return cache[key].value;\n }\n\n const time = Date.now();\n const value = method.apply(this, arguments);\n\n cache[key] = { time, value };\n\n return cache[key].value;\n };\n\n memoizedFunction.reset = () => {\n cacheMap.delete(options.thisNamespace ? this : method);\n };\n\n memoizedFunctions.push(memoizedFunction);\n\n // $FlowFixMe\n const result : F = memoizedFunction;\n\n return setFunctionName(result, `${ options.name || getFunctionName(method) }::memoized`);\n}\n\nmemoize.clear = () => {\n for (const memoizedFunction of memoizedFunctions) {\n memoizedFunction.reset();\n }\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() : mixed {\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 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 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 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 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 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 const result = [];\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n result.push(obj[key]);\n }\n }\n return result;\n}\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 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 return {\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 = this.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 this.trigger(eventName, ...args);\n },\n\n reset() {\n handlers = {};\n }\n };\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 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 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 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) => void,\n all : () => ZalgoPromise\n|};\n\nexport function cleanup(obj : Object) : CleanupType {\n\n const tasks = [];\n let cleaned = false;\n\n return {\n set(name : string, item : T) : T {\n if (!cleaned) {\n obj[name] = item;\n this.register(() => {\n delete obj[name];\n });\n }\n return item;\n },\n\n register(method : Function) {\n if (cleaned) {\n method();\n } else {\n tasks.push(once(method));\n }\n },\n\n all() : ZalgoPromise {\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\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 memoizedValues = memoize(values);\n\nexport const constHas = (constant : T, value : X) : boolean => {\n return memoizedValues(constant).indexOf(value) !== -1;\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 let testWeakMap = new WeakMap();\n let testKey = {};\n let 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","/* @flow */\n/* eslint max-lines: off */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { linkFrameWindow, isWindowClosed,\n type SameDomainWindowType, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport { inlineMemoize, noop, stringify, capitalizeFirstLetter,\n once, extend, safeInterval, uniqueID, arrayFrom } from './util';\nimport { isDevice } from './device';\nimport { KEY_CODES } from './constants';\nimport type { CancelableType } from './types';\n\ntype ElementRefType = string | HTMLElement;\n\nexport function isDocumentReady() : boolean {\n return Boolean(document.body) && document.readyState === 'complete';\n}\n\nexport function urlEncode(str : string) : string {\n return str.replace(/\\?/g, '%3F').replace(/&/g, '%26').replace(/#/g, '%23').replace(/\\+/g, '%2B');\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\nexport function waitForDocumentReady() : ZalgoPromise {\n return inlineMemoize(waitForDocumentReady, () : ZalgoPromise => {\n return new ZalgoPromise(resolve => {\n\n if (isDocumentReady()) {\n return resolve();\n }\n\n const interval = setInterval(() => {\n if (isDocumentReady()) {\n clearInterval(interval);\n return resolve();\n }\n }, 10);\n });\n });\n}\n\nexport function waitForDocumentBody() : ZalgoPromise {\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\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 function formatQuery(obj : { [ string ] : string } = {}) : string {\n\n return Object.keys(obj).filter(key => {\n return typeof obj[key] === 'string';\n }).map(key => {\n return `${ urlEncode(key) }=${ urlEncode(obj[key]) }`;\n }).join('&');\n}\n\nexport function extendQuery(originalQuery : string, props : { [ string ] : string } = {}) : 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? : { [string] : string }, hash? : { [string] : string } |}) : 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');\n}\n\nexport function querySelectorAll(selector : string, doc : HTMLElement = window.document) : $ReadOnlyArray {\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) { // eslint-disable-line unicorn/prefer-event-key\n return handler(event);\n }\n });\n}\n\nexport function getScript({ host = window.location.host, path } : {| host? : string, path : string |}) : ?HTMLScriptElement {\n return inlineMemoize(getScript, () : ?HTMLScriptElement => {\n\n const url = `${ host }${ path }`;\n const scripts = Array.prototype.slice.call(document.getElementsByTagName('script'));\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; // eslint-disable-line compat/compat\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 isElement(element : mixed) : boolean {\n\n if (element instanceof window.Element) {\n return true;\n }\n\n if (element !== null && typeof element === 'object' && element.nodeType === 1 && typeof element.style === 'object' && typeof element.ownerDocument === 'object') {\n return true;\n }\n\n return false;\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 clearInterval(interval);\n return resolve(el);\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\nexport function PopupOpenError(message : string) {\n this.message = message;\n}\n\nPopupOpenError.prototype = Object.create(Error.prototype);\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|};\n\nexport function popup(url : string, options? : PopupOptions) : CrossDomainWindowType {\n\n // $FlowFixMe\n options = options || {};\n\n const { 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 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 const name = options.name || '';\n delete options.name;\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, true);\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 window.addEventListener('unload', () => win.close());\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); // eslint-disable-line compat/compat\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) {\n return true;\n }\n return false;\n}\n\nexport function watchElementForClose(element : HTMLElement, handler : () => mixed) : CancelableType {\n handler = once(handler);\n\n let interval;\n\n if (isElementClosed(element)) {\n handler();\n } else {\n interval = safeInterval(() => {\n if (isElementClosed(element)) {\n interval.cancel();\n handler();\n }\n }, 50);\n }\n\n return {\n cancel() {\n if (interval) {\n interval.cancel();\n }\n }\n };\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\n handler({ width: currentWidth, height: currentHeight });\n\n const check = () => {\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 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 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.host) {\n // $FlowFixMe\n return shadowRoot.host;\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 if (isShadowElement(shadowHost)) {\n throw new Error(`Host element is also in shadow dom`);\n }\n\n const slotName = `shadow-slot-${ uniqueID() }`;\n\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 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","/* @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 } from 'belter/src';\n\nexport function getGlobal(win : SameDomainWindowType = window) : Object {\n if (win !== window) {\n return win[__POST_ROBOT__.__GLOBAL_KEY__];\n }\n const global : Object = win[__POST_ROBOT__.__GLOBAL_KEY__] = win[__POST_ROBOT__.__GLOBAL_KEY__] || {};\n return global;\n}\n\nexport function deleteGlobal() {\n delete window[__POST_ROBOT__.__GLOBAL_KEY__];\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\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 } 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 if (__TEST__ && parent[__POST_ROBOT__.__GLOBAL_KEY__]) {\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","/* @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 if (Object.prototype.toString.call(val) === '[object RegExp]') {\n return TYPE.REGEX;\n }\n\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} 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,\n string? : CustomOrPrimitiveSerializer,\n number? : CustomOrPrimitiveSerializer,\n boolean? : CustomOrPrimitiveSerializer,\n null? : CustomOrPrimitiveSerializer\n|};\n\nconst SERIALIZER : Serializers = {\n [ TYPE.FUNCTION ]: serializeFunction,\n [ TYPE.ERROR ]: serializeError,\n [ TYPE.PROMISE ]: serializePromise,\n [ TYPE.REGEX ]: serializeRegex,\n [ TYPE.DATE ]: serializeDate,\n [ TYPE.ARRAY ]: serializeArray,\n [ TYPE.OBJECT ]: serializeObject,\n [ TYPE.STRING ]: serializeString,\n [ TYPE.NUMBER ]: serializeNumber,\n [ TYPE.BOOLEAN ]: serializeBoolean,\n [ TYPE.NULL ]: serializeNull\n};\n\n// $FlowFixMe\nconst defaultSerializers : Serializers = {};\n\nexport function serialize(obj : T, serializers : Serializers = defaultSerializers) : string {\n\n function replacer(key) : ?mixed {\n const val = this[key];\n\n if (isSerializedType(this)) {\n return val;\n }\n \n const type = determineType(val);\n\n if (!type) {\n return val;\n }\n\n // $FlowFixMe\n const serializer = serializers[type] || SERIALIZER[type];\n\n if (!serializer) {\n return val;\n }\n\n return serializer(val, key);\n }\n\n const result = JSON.stringify(obj, replacer);\n\n if (typeof result === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n return result;\n}\n","/* @flow */\n\nexport type SerializedFunction = void;\n\nexport function serializeFunction() : SerializedFunction {\n // pass\n}\n\nexport function deserializeFunction() {\n throw new Error(`Function serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nimport { serializeObject } from './object';\n\nexport type SerializedError = {|\n message : string,\n stack : string,\n code : string | number | void,\n data : mixed\n|};\n\n// $FlowFixMe\nexport function serializeError({ message, stack, code, data } : Error) : NativeSerializedType {\n return serializeType(TYPE.ERROR, { message, stack, code, data });\n}\n\nexport function deserializeError({ message, stack, code, data } : SerializedError) : Error {\n const error = new Error(message);\n // $FlowFixMe\n error.code = code;\n\n if (data) {\n // $FlowFixMe\n error.data = serializeObject(data);\n }\n\n error.stack = `${ stack }\\n\\n${ error.stack }`;\n return error;\n}\n","/* @flow */\n\nexport type SerializedPromise = void;\n\nexport function serializePromise() : SerializedPromise {\n // pass\n}\n\nexport function deserializePromise() {\n throw new Error(`Promise serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedRegex = string;\n\nexport function serializeRegex(val : RegExp) : NativeSerializedType {\n return serializeType(TYPE.REGEX, val.source);\n}\n\nexport function deserializeRegex(val : string) : RegExp {\n // eslint-disable-next-line security/detect-non-literal-regexp\n return new RegExp(val);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedDate = string;\n\nexport function serializeDate(val : Date) : NativeSerializedType {\n return serializeType(TYPE.DATE, val.toJSON());\n}\n\nexport function deserializeDate(val : string) : Date {\n return new Date(val);\n}\n","/* @flow */\n\nexport type SerializedArray = $ReadOnlyArray;\n\nexport function serializeArray(val : $ReadOnlyArray) : SerializedArray {\n return val;\n}\n\nexport function deserializeArray(val : SerializedArray) : $ReadOnlyArray {\n return val;\n}\n","/* @flow */\n\nexport type SerializedObject = Object;\n\nexport function serializeObject(val : Object) : SerializedObject {\n return val;\n}\n\nexport function deserializeObject(val : SerializedObject) : Object {\n return val;\n}\n","/* @flow */\n\nexport type SerializedString = string;\n\nexport function serializeString(val : string) : SerializedString {\n return val;\n}\n\nexport function deserializeString(val : SerializedString) : string {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNumber = number;\n\nexport function serializeNumber(val : number) : SerializedNumber {\n return val;\n}\n\nexport function deserializeNumber(val : SerializedNumber) : number {\n return val;\n}\n","/* @flow */\n\nexport type SerializedBoolean = boolean;\n\nexport function serializeBoolean(val : boolean) : SerializedBoolean {\n return val;\n}\n\nexport function deserializeBoolean(val : SerializedBoolean) : boolean {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNull = null;\n\nexport function serializeNull(val : null) : SerializedNull {\n return val;\n}\n\nexport function deserializeNull(val : SerializedNull) : null {\n return val;\n}\n","/* @flow */\n\nimport type { Thenable } from './types';\nimport { TYPE } from './constants';\nimport { determineType, isSerializedType } from './common';\nimport {\n deserializeFunction,\n deserializeError, type SerializedError,\n deserializePromise,\n deserializeRegex, type SerializedRegex,\n deserializeDate, type SerializedDate,\n deserializeArray,\n deserializeObject,\n deserializeString,\n deserializeNumber,\n deserializeBoolean,\n deserializeNull\n} from './serializers';\n\ntype Deserializer = (serializedValue : S, key : string) => V;\ntype PrimitiveDeserializer = (serializedValue : S, key : string) => V;\n\ntype Deserializers = {\n function? : Deserializer,\n error? : Deserializer,\n promise? : Deserializer,\n regex? : Deserializer,\n date? : Deserializer,\n array? : PrimitiveDeserializer<$ReadOnlyArray>,\n object? : PrimitiveDeserializer,\n string? : PrimitiveDeserializer,\n number? : PrimitiveDeserializer,\n boolean? : PrimitiveDeserializer,\n null? : PrimitiveDeserializer,\n [string] : Deserializer\n};\n\n// $FlowFixMe\nconst DESERIALIZER : Deserializers = {\n [ TYPE.FUNCTION ]: deserializeFunction,\n [ TYPE.ERROR ]: deserializeError,\n [ TYPE.PROMISE ]: deserializePromise,\n [ TYPE.REGEX ]: deserializeRegex,\n [ TYPE.DATE ]: deserializeDate,\n [ TYPE.ARRAY ]: deserializeArray,\n [ TYPE.OBJECT ]: deserializeObject,\n [ TYPE.STRING ]: deserializeString,\n [ TYPE.NUMBER ]: deserializeNumber,\n [ TYPE.BOOLEAN ]: deserializeBoolean,\n [ TYPE.NULL ]: deserializeNull\n};\n\n// $FlowFixMe\nconst defaultDeserializers : Deserializers = {};\n\nexport function deserialize(str : string, deserializers : Deserializers = defaultDeserializers) : T {\n if (str === TYPE.UNDEFINED) {\n // $FlowFixMe\n return;\n }\n\n function replacer(key, val) : ?mixed {\n if (isSerializedType(this)) {\n return val;\n }\n\n let type;\n let value;\n\n if (isSerializedType(val)) {\n type = val.__type__;\n value = val.__val__;\n } else {\n type = determineType(val);\n value = val;\n }\n\n if (!type) {\n return value;\n }\n\n // $FlowFixMe\n const deserializer = deserializers[type] || DESERIALIZER[type];\n\n if (!deserializer) {\n return value;\n }\n\n return deserializer(value, key);\n }\n\n return JSON.parse(str, replacer);\n}\n","/* @flow */\n\nimport { isSameDomain, isWindowClosed, type CrossDomainWindowType, closeWindow,\n type DomainMatcher, getOpener, WINDOW_TYPE, isWindow, assertSameDomain, getFrameForWindow } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, memoizePromise, noop } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport { getWindowInstanceID } from '../lib';\nimport { linkWindow } from '../bridge';\nimport type { SendType } from '../types';\n\nfunction cleanupProxyWindows() {\n const idToProxyWindow = globalStore('idToProxyWindow');\n for (const id of idToProxyWindow.keys()) {\n // $FlowFixMe\n if (idToProxyWindow.get(id).shouldClean()) {\n idToProxyWindow.del(id);\n }\n }\n}\n\ntype SerializedWindowType = {|\n id : string,\n getType : () => ZalgoPromise<$Values>,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n isClosed : () => ZalgoPromise,\n setLocation : (string) => ZalgoPromise,\n getName : () => ZalgoPromise,\n setName : (string) => ZalgoPromise,\n getInstanceID : () => ZalgoPromise\n|};\n\nfunction getSerializedWindow(winPromise : ZalgoPromise, { send, id = uniqueID() } : {| send : SendType, id? : string |}) : SerializedWindowType {\n \n let windowNamePromise = winPromise.then(win => {\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n });\n \n const windowTypePromise = winPromise.then(window => {\n if (!isWindowClosed(window)) {\n return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME;\n } else {\n throw new Error(`Window is closed, can not determine type`);\n }\n });\n\n windowNamePromise.catch(noop);\n windowTypePromise.catch(noop);\n\n return {\n id,\n getType: () => {\n return windowTypePromise;\n },\n getInstanceID: memoizePromise(() => winPromise.then(win => getWindowInstanceID(win, { send }))),\n close: () => winPromise.then(closeWindow),\n getName: () => winPromise.then(win => {\n if (isWindowClosed(win)) {\n return;\n }\n\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n\n return windowNamePromise;\n }),\n focus: () => winPromise.then(win => {\n win.focus();\n }),\n isClosed: () => winPromise.then(win => {\n return isWindowClosed(win);\n }),\n setLocation: (href) => winPromise.then(win => {\n const domain = `${ window.location.protocol }//${ window.location.host }`;\n\n if (href.indexOf('/') === 0) {\n href = `${ domain }${ href }`;\n } else if (!href.match(/^https?:\\/\\//) && href.indexOf(domain) !== 0) {\n throw new Error(`Expected url to be http or https url, or absolute path, got ${ JSON.stringify(href) }`);\n }\n\n if (isSameDomain(win)) {\n try {\n if (win.location && typeof win.location.replace === 'function') {\n // $FlowFixMe\n win.location.replace(href);\n return;\n }\n } catch (err) {\n // pass\n }\n }\n\n win.location = href;\n }),\n setName: (name) => winPromise.then(win => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n linkWindow({ win, name });\n }\n\n const sameDomain = isSameDomain(win);\n const frame = getFrameForWindow(win);\n\n if (!sameDomain) {\n throw new Error(`Can not set name for cross-domain window: ${ name }`);\n }\n\n assertSameDomain(win).name = name;\n if (frame) {\n frame.setAttribute('name', name);\n }\n\n windowNamePromise = ZalgoPromise.resolve(name);\n })\n };\n}\n\nexport class ProxyWindow {\n\n id : string\n isProxyWindow : true = true\n serializedWindow : SerializedWindowType\n actualWindow : ?CrossDomainWindowType\n actualWindowPromise : ZalgoPromise\n send : SendType\n name : string\n\n constructor({ send, win, serializedWindow } : {| win? : CrossDomainWindowType, serializedWindow? : SerializedWindowType, send : SendType |}) {\n this.actualWindowPromise = new ZalgoPromise();\n this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, { send });\n \n globalStore('idToProxyWindow').set(this.getID(), this);\n if (win) {\n this.setWindow(win, { send });\n }\n }\n\n getID() : string {\n return this.serializedWindow.id;\n }\n\n getType() : ZalgoPromise<$Values> {\n return this.serializedWindow.getType();\n }\n\n isPopup() : ZalgoPromise {\n return this.getType().then(type => {\n return type === WINDOW_TYPE.POPUP;\n });\n }\n\n setLocation(href : string) : ZalgoPromise {\n return this.serializedWindow.setLocation(href).then(() => this);\n }\n\n getName() : ZalgoPromise {\n return this.serializedWindow.getName();\n }\n\n setName(name : string) : ZalgoPromise {\n return this.serializedWindow.setName(name).then(() => this);\n }\n\n close() : ZalgoPromise {\n return this.serializedWindow.close().then(() => this);\n }\n\n focus() : ZalgoPromise {\n const isPopupPromise = this.isPopup();\n const getNamePromise = this.getName();\n\n const reopenPromise = ZalgoPromise.hash({ isPopup: isPopupPromise, name: getNamePromise }).then(({ isPopup, name }) => {\n if (isPopup && name) {\n window.open('', name);\n }\n });\n const focusPromise = this.serializedWindow.focus();\n\n return ZalgoPromise.all([\n reopenPromise,\n focusPromise\n ]).then(() => this);\n }\n\n isClosed() : ZalgoPromise {\n return this.serializedWindow.isClosed();\n }\n\n getWindow() : ?CrossDomainWindowType {\n return this.actualWindow;\n }\n\n setWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) {\n this.actualWindow = win;\n this.actualWindowPromise.resolve(this.actualWindow);\n this.serializedWindow = getSerializedWindow(this.actualWindowPromise, { send, id: this.getID() });\n windowStore('winToProxyWindow').set(win, this);\n }\n\n awaitWindow() : ZalgoPromise {\n return this.actualWindowPromise;\n }\n\n matchWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (this.actualWindow) {\n return win === this.actualWindow;\n }\n \n return ZalgoPromise.hash({\n proxyInstanceID: this.getInstanceID(),\n knownWindowInstanceID: getWindowInstanceID(win, { send })\n }).then(({ proxyInstanceID, knownWindowInstanceID }) => {\n const match = proxyInstanceID === knownWindowInstanceID;\n\n if (match) {\n this.setWindow(win, { send });\n }\n\n return match;\n });\n });\n }\n\n unwrap() : CrossDomainWindowType | ProxyWindow {\n return this.actualWindow || this;\n }\n\n getInstanceID() : ZalgoPromise {\n return this.serializedWindow.getInstanceID();\n }\n\n shouldClean() : boolean {\n return Boolean(this.actualWindow && isWindowClosed(this.actualWindow));\n }\n\n serialize() : SerializedWindowType {\n return this.serializedWindow;\n }\n\n static unwrap(win : CrossDomainWindowType | ProxyWindow) : CrossDomainWindowType | ProxyWindow {\n return ProxyWindow.isProxyWindow(win)\n // $FlowFixMe\n ? win.unwrap()\n : win;\n }\n\n static serialize(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : SerializedWindowType {\n cleanupProxyWindows();\n return ProxyWindow.toProxyWindow(win, { send }).serialize();\n }\n\n static deserialize(serializedWindow : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n return globalStore('idToProxyWindow').get(serializedWindow.id) || new ProxyWindow({ serializedWindow, send });\n }\n\n static isProxyWindow(obj : CrossDomainWindowType | ProxyWindow) : boolean {\n // $FlowFixMe\n return Boolean(obj && !isWindow(obj) && obj.isProxyWindow);\n }\n\n static toProxyWindow(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n\n if (ProxyWindow.isProxyWindow(win)) {\n // $FlowFixMe\n return win;\n }\n\n // $FlowFixMe\n const actualWindow : CrossDomainWindowType = win;\n \n return windowStore('winToProxyWindow').get(actualWindow) || new ProxyWindow({ win: actualWindow, send });\n }\n}\n\nexport type SerializedWindow = CustomSerializedType;\n\nexport function serializeWindow(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, win : CrossDomainWindowType, { send } : {| send : SendType |}) : SerializedWindow {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW, ProxyWindow.serialize(win, { send }));\n}\n\nexport function deserializeWindow(source : CrossDomainWindowType | ProxyWindow, origin : string, win : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n return ProxyWindow.deserialize(win, { send });\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isSameDomain, isOpener, isSameTopWindow, matchDomain, getUserAgent, getDomainFromUrl, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { BRIDGE_NAME_PREFIX } from '../conf';\nimport { windowStore } from '../global';\n\nexport function needsBridgeForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForWin(win : CrossDomainWindowType) : boolean {\n\n if (!isSameTopWindow(window, win)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForDomain(domain : ?string, win : ?CrossDomainWindowType) : boolean {\n\n if (domain) {\n if (getDomain() !== getDomainFromUrl(domain)) {\n return true;\n }\n } else if (win) {\n if (!isSameDomain(win)) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function needsBridge({ win, domain } : {| win? : CrossDomainWindowType, domain? : string |}) : boolean {\n\n if (!needsBridgeForBrowser()) {\n return false;\n }\n\n if (domain && !needsBridgeForDomain(domain, win)) {\n return false;\n }\n\n if (win && !needsBridgeForWin(win)) {\n return false;\n }\n\n return true;\n}\n\nexport function getBridgeName(domain : string) : string {\n\n domain = domain || getDomainFromUrl(domain);\n\n const sanitizedDomain = domain.replace(/[^a-zA-Z0-9]+/g, '_');\n\n const id = `${ BRIDGE_NAME_PREFIX }_${ sanitizedDomain }`;\n\n return id;\n}\n\nexport function isBridge() : boolean {\n return Boolean(window.name && window.name === getBridgeName(getDomain()));\n}\n\nexport const documentBodyReady = new ZalgoPromise(resolve => {\n\n if (window.document && window.document.body) {\n return resolve(window.document.body);\n }\n\n const interval = setInterval(() => {\n if (window.document && window.document.body) {\n clearInterval(interval);\n return resolve(window.document.body);\n }\n }, 10);\n});\n\nexport function registerRemoteWindow(win : CrossDomainWindowType) {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n remoteWindowPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nexport function findRemoteWindow(win : CrossDomainWindowType) : ZalgoPromise<(remoteWin : CrossDomainWindowType, message : string, remoteDomain : string) => void> {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n const remoteWinPromise = remoteWindowPromises.get(win);\n\n if (!remoteWinPromise) {\n throw new Error(`Remote window promise not found`);\n }\n\n return remoteWinPromise;\n}\n\ntype SendMessageType = {|\n (string) : void,\n fireAndForget : (string) => void\n|};\n\nexport function registerRemoteSendMessage(win : CrossDomainWindowType, domain : string, sendMessage : SendMessageType) {\n const sendMessageWrapper = (remoteWin : CrossDomainWindowType, remoteDomain : string, message : string) => {\n if (remoteWin !== win) {\n throw new Error(`Remote window does not match window`);\n }\n\n if (!matchDomain(remoteDomain, domain)) {\n throw new Error(`Remote domain ${ remoteDomain } does not match domain ${ domain }`);\n }\n\n sendMessage.fireAndForget(message);\n };\n\n findRemoteWindow(win).resolve(sendMessageWrapper);\n}\n\nexport function rejectRemoteSendMessage(win : CrossDomainWindowType, err : Error) {\n findRemoteWindow(win).reject(err).catch(noop);\n}\n\nexport function sendBridgeMessage(win : CrossDomainWindowType, domain : string, message : string) : ZalgoPromise {\n\n const messagingChild = isOpener(window, win);\n const messagingParent = isOpener(win, window);\n\n if (!messagingChild && !messagingParent) {\n throw new Error(`Can only send messages to and from parent and popup windows`);\n }\n\n return findRemoteWindow(win).then(sendMessage => {\n return sendMessage(win, domain, message);\n });\n}\n","/* @flow */\n\nimport { matchDomain, getDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, isRegex, arrayFrom } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { MESSAGE_NAME, WILDCARD, SERIALIZATION_TYPE } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nimport { ProxyWindow } from './window';\n\ntype StoredMethod = {|\n name : string,\n domain : DomainMatcher,\n val : Function,\n source : CrossDomainWindowType | ProxyWindow\n|};\n\nfunction addMethod(id : string, val : Function, name : string, source : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher) {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n \n if (ProxyWindow.isProxyWindow(source)) {\n proxyWindowMethods.set(id, { val, name, domain, source });\n } else {\n proxyWindowMethods.del(id);\n // $FlowFixMe\n const methods = methodStore.getOrSet(source, () => ({}));\n methods[id] = { domain, name, val, source };\n }\n}\n\nfunction lookupMethod(source : CrossDomainWindowType, id : string) : ?StoredMethod {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n const methods = methodStore.getOrSet(source, () => ({}));\n return methods[id] || proxyWindowMethods.get(id);\n}\n\nfunction stringifyArguments(args : $ReadOnlyArray = []) : string {\n return arrayFrom(args).map(arg => {\n if (typeof arg === 'string') {\n return `'${ arg }'`;\n }\n if (arg === undefined) {\n return 'undefined';\n }\n if (arg === null) {\n return 'null';\n }\n if (typeof arg === 'boolean') {\n return arg.toString();\n }\n if (Array.isArray(arg)) {\n return '[ ... ]';\n }\n if (typeof arg === 'object') {\n return '{ ... }';\n }\n if (typeof arg === 'function') {\n return '() => { ... }';\n }\n return `<${ typeof arg }>`;\n }).join(', ');\n}\n\nfunction listenForFunctionCalls({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('functionCalls', () => {\n return on(MESSAGE_NAME.METHOD, { domain: WILDCARD }, ({ source, origin, data } : {| source : CrossDomainWindowType, origin : string, data : Object |}) => {\n const { id, name } = data;\n\n const meth = lookupMethod(source, id);\n \n if (!meth) {\n throw new Error(`Could not find method '${ name }' with id: ${ data.id } in ${ getDomain(window) }`);\n }\n\n const { source: methodSource, domain, val } = meth;\n \n return ZalgoPromise.try(() => {\n if (!matchDomain(domain, origin)) {\n // $FlowFixMe\n throw new Error(`Method '${ data.name }' domain ${ JSON.stringify(isRegex(meth.domain) ? meth.domain.source : meth.domain) } does not match origin ${ origin } in ${ getDomain(window) }`);\n }\n \n if (ProxyWindow.isProxyWindow(methodSource)) {\n // $FlowFixMe\n return methodSource.matchWindow(source, { send }).then(match => {\n if (!match) {\n throw new Error(`Method call '${ data.name }' failed - proxy window does not match source in ${ getDomain(window) }`);\n }\n });\n }\n }).then(() => {\n return val.apply({ source, origin }, data.args);\n }, err => {\n return ZalgoPromise.try(() => {\n if (val.onError) {\n return val.onError(err);\n }\n }).then(() => {\n // $FlowFixMe\n if (err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(data.args) }) failed\\n\\n${ err.stack }`;\n }\n\n throw err;\n });\n }).then(result => {\n return { result, id, name };\n });\n });\n });\n}\n\nexport type SerializedFunction = CustomSerializedType;\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype SerializableFunction = {\n () : ZalgoPromise | T,\n __id__? : string,\n __name__? : string\n};\n\nexport function serializeFunction(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : SerializableFunction, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedFunction {\n listenForFunctionCalls({ on, send });\n \n const id = val.__id__ || uniqueID();\n destination = ProxyWindow.unwrap(destination);\n let name = val.__name__ || val.name || key;\n\n if (typeof name === 'string' && typeof name.indexOf === 'function' && name.indexOf('anonymous::') === 0) {\n name = name.replace('anonymous::', `${ key }::`);\n }\n\n if (ProxyWindow.isProxyWindow(destination)) {\n addMethod(id, val, name, destination, domain);\n\n // $FlowFixMe\n destination.awaitWindow().then(win => {\n addMethod(id, val, name, win, domain);\n });\n } else {\n addMethod(id, val, name, destination, domain);\n }\n\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION, { id, name });\n}\n\nexport function deserializeFunction(source : CrossDomainWindowType | ProxyWindow, origin : string, { id, name } : {| id : string, name : string |}, { send } : {| send : SendType |}) : (...args : $ReadOnlyArray) => ZalgoPromise {\n const getDeserializedFunction = (opts? : Object = {}) => {\n function crossDomainFunctionWrapper() : ZalgoPromise {\n let originalStack;\n \n if (__DEBUG__) {\n originalStack = (new Error(`Original call to ${ name }():`)).stack;\n }\n \n return ProxyWindow.toProxyWindow(source, { send }).awaitWindow().then(win => {\n const meth = lookupMethod(win, id);\n \n if (meth && meth.val !== crossDomainFunctionWrapper) {\n return meth.val.apply({ source: window, origin: getDomain() }, arguments);\n } else {\n const args = Array.prototype.slice.call(arguments);\n\n if (opts.fireAndForget) {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: true });\n } else {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: false })\n .then(res => res.data.result);\n }\n }\n \n }).catch(err => {\n // $FlowFixMe\n if (__DEBUG__ && originalStack && err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(arguments) }) failed\\n\\n${ err.stack }\\n\\n${ originalStack }`;\n }\n throw err;\n });\n }\n\n crossDomainFunctionWrapper.__name__ = name;\n crossDomainFunctionWrapper.__origin__ = origin;\n crossDomainFunctionWrapper.__source__ = source;\n crossDomainFunctionWrapper.__id__ = id;\n\n crossDomainFunctionWrapper.origin = origin;\n\n return crossDomainFunctionWrapper;\n };\n\n const crossDomainFunctionWrapper = getDeserializedFunction();\n crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({ fireAndForget: true });\n\n return crossDomainFunctionWrapper;\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindow, type DomainMatcher } from 'cross-domain-utils/src';\nimport { TYPE, serialize, deserialize, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, deserializeFunction, type SerializedFunction } from './function';\nimport { serializePromise, deserializePromise, type SerializedPromise } from './promise';\nimport { serializeWindow, deserializeWindow, type SerializedWindow, ProxyWindow } from './window';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T, { on, send } : {| on : OnType, send : SendType |}) : string {\n return serialize(obj, {\n [ TYPE.PROMISE ]: (val : Thenable, key : string) : SerializedPromise => serializePromise(destination, domain, val, key, { on, send }),\n [ TYPE.FUNCTION ]: (val : Function, key : string) : SerializedFunction => serializeFunction(destination, domain, val, key, { on, send }),\n [ TYPE.OBJECT ]: (val : CrossDomainWindowType) : Object | SerializedWindow => {\n return (isWindow(val) || ProxyWindow.isProxyWindow(val)) ? serializeWindow(destination, domain, val, { send }) : val;\n }\n });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string, { send } : {| on : OnType, send : SendType |}) : T {\n return deserialize(message, {\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE ]: (serializedPromise) => deserializePromise(source, origin, serializedPromise),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION ]: (serializedFunction) => deserializeFunction(source, origin, serializedFunction, { send }),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW ]: (serializedWindow) => deserializeWindow(source, origin, serializedWindow, { send })\n });\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeType, type CustomSerializedType, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, type SerializedFunction } from './function';\nimport { ProxyWindow } from './window';\n\nexport type SerializedPromise = CustomSerializedType;\n\nexport function serializePromise(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : Thenable, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedPromise {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE, {\n then: serializeFunction(destination, domain, (resolve, reject) => val.then(resolve, reject), key, { on, send })\n });\n}\n\nexport function deserializePromise(source : CrossDomainWindowType | ProxyWindow, origin : string, { then } : {| then : Function |}) : ZalgoPromise {\n return new ZalgoPromise(then);\n}\n","/* @flow */\n\nimport { isSameDomain, isSameTopWindow, isActuallySameDomain, getActualDomain,\n getDomain, type CrossDomainWindowType, PROTOCOL } from 'cross-domain-utils/src';\n\nimport { SEND_STRATEGY, WILDCARD } from '../../conf';\nimport { needsGlobalMessagingForBrowser } from '../../lib';\nimport { getGlobal } from '../../global';\nimport { sendBridgeMessage, needsBridgeForBrowser, isBridge } from '../../bridge';\n\nexport const SEND_MESSAGE_STRATEGIES = {};\n\nSEND_MESSAGE_STRATEGIES[SEND_STRATEGY.POST_MESSAGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n if (domain.indexOf(PROTOCOL.FILE) === 0) {\n domain = WILDCARD;\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(window, win) === false) {\n return;\n }\n\n if (domain.indexOf(PROTOCOL.MOCK) === 0) {\n if (!isActuallySameDomain(win)) {\n throw new Error(`Attempting to send message to mock domain ${ domain }, but window is actually cross-domain`);\n }\n\n // $FlowFixMe\n const windowDomain = getDomain(win);\n \n if (windowDomain !== domain) {\n throw new Error(`Mock domain target ${ domain } does not match window domain ${ windowDomain }`);\n }\n\n // $FlowFixMe\n domain = getActualDomain(win);\n\n }\n }\n\n win.postMessage(serializedMessage, domain);\n};\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n\n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.BRIDGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n\n if (!needsBridgeForBrowser() && !isBridge()) {\n throw new Error(`Bridge not needed for browser`);\n }\n\n if (isSameDomain(win)) {\n throw new Error(`Post message through bridge disabled between same domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use bridge to communicate between two different windows, not between frames`);\n }\n\n sendBridgeMessage(win, domain, serializedMessage);\n };\n}\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__ || __POST_ROBOT__.__GLOBAL_MESSAGE_SUPPORT__) {\n \n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.GLOBAL] = (win : CrossDomainWindowType, serializedMessage : string) => {\n\n if (!needsGlobalMessagingForBrowser()) {\n throw new Error(`Global messaging not needed for browser`);\n }\n\n if (!isSameDomain(win)) {\n throw new Error(`Post message through global disabled between different domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use global to communicate between two different windows, not between frames`);\n }\n\n // $FlowFixMe\n const foreignGlobal = getGlobal(win);\n\n if (!foreignGlobal) {\n throw new Error(`Can not find postRobot global on foreign window`);\n }\n\n foreignGlobal.receiveMessage({\n source: window,\n origin: getDomain(),\n data: serializedMessage\n });\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { stringifyError, noop } from 'belter/src';\n\nimport { serializeMessage } from '../../serialize';\nimport { windowStore } from '../../global';\nimport type { Message, PackedMessages } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nimport { SEND_MESSAGE_STRATEGIES } from './strategies';\n\nfunction packMessages(messages : $ReadOnlyArray) : PackedMessages {\n return {\n [ __POST_ROBOT__.__GLOBAL_KEY__ ]: messages\n };\n}\n\nexport function sendMessage(win : CrossDomainWindowType, domain : string, message : Message, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n const messageBuffer = windowStore();\n\n const domainBuffer = messageBuffer.getOrSet(win, () => ({}));\n\n domainBuffer.buffer = domainBuffer.buffer || [];\n domainBuffer.buffer.push(message);\n\n domainBuffer.flush = domainBuffer.flush || ZalgoPromise.flush().then(() => {\n if (isWindowClosed(win)) {\n throw new Error('Window is closed');\n }\n\n const serializedMessage = serializeMessage(win, domain, packMessages(domainBuffer.buffer || []), { on, send });\n delete domainBuffer.buffer;\n\n const strategies = Object.keys(SEND_MESSAGE_STRATEGIES);\n const errors = [];\n\n for (const strategyName of strategies) {\n try {\n SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain);\n } catch (err) {\n errors.push(err);\n }\n }\n\n if (errors.length === strategies.length) {\n throw new Error(`All post-robot messaging strategies failed:\\n\\n${ errors.map((err, i) => `${ i }. ${ stringifyError(err) }`).join('\\n\\n') }`);\n }\n });\n\n return domainBuffer.flush.then(() => {\n delete domainBuffer.flush;\n });\n }).then(noop);\n}\n","/* @flow */\n\nimport { type ZalgoPromise } from 'zalgo-promise/src';\nimport { matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { isRegex, getOrSet } from 'belter/src';\n\nimport { getWildcard, type WildCard, globalStore, windowStore } from '../global';\nimport { WILDCARD } from '../conf';\n\nexport function resetListeners() {\n const responseListeners = globalStore('responseListeners');\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n responseListeners.reset();\n erroredResponseListeners.reset();\n}\n\nconst __DOMAIN_REGEX__ = '__domain_regex__';\n\nexport type RequestListenerType = {|\n handler : ({| source : CrossDomainWindowType, origin : string, data : mixed |}) => (mixed | ZalgoPromise),\n handleError : (err : mixed) => void,\n window : ?CrossDomainWindowType,\n name : string,\n domain : DomainMatcher\n|};\n\nexport type ResponseListenerType = {|\n name : string,\n win : CrossDomainWindowType,\n domain : DomainMatcher,\n promise : ZalgoPromise<*>,\n ack? : ?boolean,\n cancelled? : ?boolean\n|};\n\nexport function addResponseListener(hash : string, listener : ResponseListenerType) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.set(hash, listener);\n}\n\nexport function getResponseListener(hash : string) : ?ResponseListenerType {\n const responseListeners = globalStore('responseListeners');\n return responseListeners.get(hash);\n}\n\nexport function deleteResponseListener(hash : string) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.del(hash);\n}\n\nexport function cancelResponseListeners() {\n const responseListeners = globalStore('responseListeners');\n for (const hash of responseListeners.keys()) {\n const listener = responseListeners.get(hash);\n if (listener) {\n listener.cancelled = true;\n }\n responseListeners.del(hash);\n }\n}\n\nexport function markResponseListenerErrored(hash : string) {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n erroredResponseListeners.set(hash, true);\n}\n\nexport function isResponseListenerErrored(hash : string) : boolean {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n return erroredResponseListeners.has(hash);\n}\n\nexport function getRequestListener({ name, win, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard), domain : ?(string | RegExp) |}) : ?RequestListenerType {\n const requestListeners = windowStore('requestListeners');\n\n if (win === WILDCARD) {\n win = null;\n }\n\n if (domain === WILDCARD) {\n domain = null;\n }\n\n if (!name) {\n throw new Error(`Name required to get request listener`);\n }\n\n for (const winQualifier of [ win, getWildcard() ]) {\n if (!winQualifier) {\n continue;\n }\n\n const nameListeners = requestListeners.get(winQualifier);\n\n if (!nameListeners) {\n continue;\n }\n\n const domainListeners = nameListeners[name];\n\n if (!domainListeners) {\n continue;\n }\n\n if (domain && typeof domain === 'string') {\n if (domainListeners[domain]) {\n return domainListeners[domain];\n }\n\n if (domainListeners[__DOMAIN_REGEX__]) {\n for (const { regex, listener } of domainListeners[__DOMAIN_REGEX__]) {\n if (matchDomain(regex, domain)) {\n return listener;\n }\n }\n }\n }\n\n if (domainListeners[WILDCARD]) {\n return domainListeners[WILDCARD];\n }\n }\n}\n\nexport function addRequestListener({ name, win, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard), domain : ?DomainMatcher |}, listener : RequestListenerType) : {| cancel : () => void |} {\n const requestListeners = windowStore('requestListeners');\n\n if (!name || typeof name !== 'string') {\n throw new Error(`Name required to add request listener`);\n }\n\n if (Array.isArray(win)) {\n const listenersCollection = [];\n\n for (const item of win) {\n listenersCollection.push(addRequestListener({ name, domain, win: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n if (Array.isArray(domain)) {\n const listenersCollection = [];\n\n for (const item of domain) {\n listenersCollection.push(addRequestListener({ name, win, domain: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n const existingListener = getRequestListener({ name, win, domain });\n\n if (!win || win === WILDCARD) {\n win = getWildcard();\n }\n\n domain = domain || WILDCARD;\n\n if (existingListener) {\n if (win && domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (win) {\n throw new Error(`Request listener already exists for ${ name } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() }`);\n } else {\n throw new Error(`Request listener already exists for ${ name }`);\n }\n }\n\n const nameListeners = requestListeners.getOrSet(win, () => ({}));\n const domainListeners = getOrSet(nameListeners, name, () => ({}));\n\n const strDomain = domain.toString();\n\n let regexListeners;\n let regexListener;\n\n if (isRegex(domain)) {\n regexListeners = getOrSet(domainListeners, __DOMAIN_REGEX__, () => []);\n regexListener = { regex: domain, listener };\n regexListeners.push(regexListener);\n } else {\n domainListeners[strDomain] = listener;\n }\n\n return {\n cancel() {\n delete domainListeners[strDomain];\n\n if (regexListener) {\n regexListeners.splice(regexListeners.indexOf(regexListener, 1));\n\n if (!regexListeners.length) {\n delete domainListeners[__DOMAIN_REGEX__];\n }\n }\n\n if (!Object.keys(domainListeners).length) {\n delete nameListeners[name];\n }\n\n if (win && !Object.keys(nameListeners).length) {\n requestListeners.del(win);\n }\n }\n };\n}\n","/* @flow */\n\nimport { getUserAgent } from 'cross-domain-utils/src';\n\nexport function needsGlobalMessagingForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|rv:11|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isWindowClosed, matchDomain, stringifyDomainPattern, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, stringifyError, uniqueID } from 'belter/src';\n\nimport { MESSAGE_TYPE, MESSAGE_ACK, MESSAGE_NAME } from '../../conf';\nimport { sendMessage } from '../send';\nimport { getRequestListener, getResponseListener, deleteResponseListener, isResponseListenerErrored } from '../listeners';\nimport type { RequestMessage, AckResponseMessage, ResponseMessage } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nexport const RECEIVE_MESSAGE_TYPES = {\n\n [ MESSAGE_TYPE.REQUEST ](source : CrossDomainWindowType, origin : string, message : RequestMessage, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n\n const options = getRequestListener({ name: message.name, win: source, domain: origin });\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (__DEBUG__) {\n // eslint-disable-next-line no-console\n console.info('receive::req', logName, origin, '\\n\\n', message.data);\n }\n\n function sendAck() : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.ACK,\n hash: message.hash,\n name: message.name\n }, { on, send });\n } catch (err) {\n throw new Error(`Send ack message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n\n function sendResponse(ack : $Values, data : ?Object, error : ?mixed) : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n if (__DEBUG__) {\n if (ack === MESSAGE_ACK.SUCCESS) {\n console.info('respond::res', logName, origin, '\\n\\n', data); // eslint-disable-line no-console\n } else if (ack === MESSAGE_ACK.ERROR) {\n console.error('respond::err', logName, origin, '\\n\\n', error); // eslint-disable-line no-console\n }\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.RESPONSE,\n hash: message.hash,\n name: message.name,\n ack,\n data,\n error\n }, { on, send });\n } catch (err) {\n throw new Error(`Send response message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n \n return ZalgoPromise.all([\n sendAck(),\n\n ZalgoPromise.try(() => {\n\n if (!options) {\n throw new Error(`No handler found for post message: ${ message.name } from ${ origin } in ${ window.location.protocol }//${ window.location.host }${ window.location.pathname }`);\n }\n\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Request origin ${ origin } does not match domain ${ options.domain.toString() }`);\n }\n\n const data = message.data;\n\n return options.handler({ source, origin, data });\n\n }).then(data => {\n return sendResponse(MESSAGE_ACK.SUCCESS, data);\n\n }, error => {\n return sendResponse(MESSAGE_ACK.ERROR, null, error);\n })\n\n ]).then(noop).catch(err => {\n if (options && options.handleError) {\n return options.handleError(err);\n } else {\n throw err;\n }\n });\n },\n\n [ MESSAGE_TYPE.ACK ](source : CrossDomainWindowType, origin : string, message : AckResponseMessage) {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n throw new Error(`No handler found for post message ack for message: ${ message.name } from ${ origin } in ${ window.location.protocol }//${ window.location.host }${ window.location.pathname }`);\n }\n\n try {\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Ack origin ${ origin } does not match domain ${ options.domain.toString() }`);\n }\n \n if (source !== options.win) {\n throw new Error(`Ack source does not match registered window`);\n }\n } catch (err) {\n options.promise.reject(err);\n }\n\n options.ack = true;\n },\n\n [ MESSAGE_TYPE.RESPONSE ](source : CrossDomainWindowType, origin : string, message : ResponseMessage) : void | ZalgoPromise {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n throw new Error(`No handler found for post message response for message: ${ message.name } from ${ origin } in ${ window.location.protocol }//${ window.location.host }${ window.location.pathname }`);\n }\n\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Response origin ${ origin } does not match domain ${ stringifyDomainPattern(options.domain) }`);\n }\n\n if (source !== options.win) {\n throw new Error(`Response source does not match registered window`);\n }\n\n deleteResponseListener(message.hash);\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (message.ack === MESSAGE_ACK.ERROR) {\n if (__DEBUG__) {\n console.error('receive::err', logName, origin, '\\n\\n', message.error); // eslint-disable-line no-console\n }\n\n options.promise.reject(message.error);\n\n } else if (message.ack === MESSAGE_ACK.SUCCESS) {\n if (__DEBUG__) {\n console.info('receive::res', logName, origin, '\\n\\n', message.data); // eslint-disable-line no-console\n }\n\n options.promise.resolve({ source, origin, data: message.data });\n }\n }\n};\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType, getDomain, isSameTopWindow, PROTOCOL } from 'cross-domain-utils/src';\nimport { addEventListener, noop } from 'belter/src';\n\nimport type { Message } from '../types';\nimport { MESSAGE_TYPE } from '../../conf';\nimport { markWindowKnown, needsGlobalMessagingForBrowser } from '../../lib';\nimport { deserializeMessage } from '../../serialize';\nimport { getGlobal, globalStore } from '../../global';\nimport type { OnType, SendType, MessageEvent, CancelableType } from '../../types';\n\nimport { RECEIVE_MESSAGE_TYPES } from './types';\n\nfunction deserializeMessages(message : string, source : CrossDomainWindowType, origin : string, { on, send } : {| on : OnType, send : SendType |}) : ?$ReadOnlyArray {\n let parsedMessage;\n\n try {\n parsedMessage = deserializeMessage(source, origin, message, { on, send });\n } catch (err) {\n return;\n }\n\n if (!parsedMessage) {\n return;\n }\n\n if (typeof parsedMessage !== 'object' || parsedMessage === null) {\n return;\n }\n\n const parseMessages = parsedMessage[__POST_ROBOT__.__GLOBAL_KEY__];\n\n if (!Array.isArray(parseMessages)) {\n return;\n }\n\n return parseMessages;\n}\n\nexport function receiveMessage(event : MessageEvent, { on, send } : {| on : OnType, send : SendType |}) {\n const receivedMessages = globalStore('receivedMessages');\n\n try {\n if (!window || window.closed || !event.source) {\n return;\n }\n } catch (err) {\n return;\n }\n\n let { source, origin, data } = event;\n\n if (__TEST__) {\n // $FlowFixMe\n origin = getDomain(source);\n }\n\n const messages = deserializeMessages(data, source, origin, { on, send });\n\n if (!messages) {\n return;\n }\n\n markWindowKnown(source);\n\n for (const message of messages) {\n if (receivedMessages.has(message.id)) {\n return;\n }\n\n receivedMessages.set(message.id, true);\n\n if (isWindowClosed(source) && !message.fireAndForget) {\n return;\n }\n\n if (message.origin.indexOf(PROTOCOL.FILE) === 0) {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n try {\n if (message.type === MESSAGE_TYPE.REQUEST) {\n RECEIVE_MESSAGE_TYPES[MESSAGE_TYPE.REQUEST](source, origin, message, { on, send });\n } else if (message.type === MESSAGE_TYPE.RESPONSE) {\n RECEIVE_MESSAGE_TYPES[MESSAGE_TYPE.RESPONSE](source, origin, message);\n } else if (message.type === MESSAGE_TYPE.ACK) {\n RECEIVE_MESSAGE_TYPES[MESSAGE_TYPE.ACK](source, origin, message);\n }\n } catch (err) {\n setTimeout(() => {\n throw err;\n }, 0);\n }\n }\n}\n\nexport function setupGlobalReceiveMessage({ on, send } : {| on : OnType, send : SendType |}) {\n const global = getGlobal();\n global.receiveMessage = global.receiveMessage || (message => receiveMessage(message, { on, send }));\n}\n\ntype ListenerEvent = {|\n source : CrossDomainWindowType,\n origin : string,\n data : string,\n sourceElement : CrossDomainWindowType,\n originalEvent? : {| origin : string |}\n|};\n\nexport function messageListener(event : ListenerEvent, { on, send } : {| on : OnType, send : SendType |}) {\n ZalgoPromise.try(() => {\n try {\n noop(event.source);\n } catch (err) {\n return;\n }\n\n const source = event.source || event.sourceElement;\n let origin = event.origin || (event.originalEvent && event.originalEvent.origin);\n const data = event.data;\n\n if (origin === 'null') {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n if (!source) {\n return;\n }\n\n if (!origin) {\n throw new Error(`Post message did not have origin domain`);\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(source, window) === false) {\n return;\n }\n }\n\n receiveMessage({ source, origin, data }, { on, send });\n });\n}\n\nexport function listenForMessages({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore().getOrSet('postMessageListener', () => {\n return addEventListener(window, 'message', event => {\n // $FlowFixMe\n messageListener(event, { on, send });\n });\n });\n}\n\nexport function stopListenForMessages() {\n const listener = globalStore().get('postMessageListener');\n if (listener) {\n listener.cancel();\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\n\nimport { addRequestListener, type RequestListenerType } from '../drivers';\nimport { WILDCARD } from '../conf';\nimport type { ServerOptionsType, HandlerType, CancelableType } from '../types';\n\nconst getDefaultServerOptions = () : ServerOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function on(name : string, options : ServerOptionsType | HandlerType, handler : ?HandlerType) : CancelableType {\n\n if (!name) {\n throw new Error('Expected name');\n }\n\n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n if (!handler) {\n throw new Error('Expected handler');\n }\n\n options = options || {};\n options.name = name;\n options.handler = handler || options.handler;\n\n const win = options.window;\n const domain = options.domain;\n\n const listenerOptions : RequestListenerType = {\n handler: options.handler,\n handleError: options.errorHandler || (err => {\n throw err;\n }),\n window: win,\n domain: domain || WILDCARD,\n name\n };\n\n const requestListener = addRequestListener({ name, win, domain }, listenerOptions);\n\n return {\n cancel() {\n requestListener.cancel();\n }\n };\n}\n\nexport function once(name : string, options? : ServerOptionsType | HandlerType, handler? : HandlerType) : ZalgoPromise<{| source : mixed, origin : string, data : Object |}> {\n \n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n const promise = new ZalgoPromise();\n let listener; // eslint-disable-line prefer-const\n\n options.errorHandler = (err) => {\n listener.cancel();\n promise.reject(err);\n };\n\n listener = on(name, options, event => {\n listener.cancel();\n promise.resolve(event);\n if (handler) {\n return handler(event);\n }\n });\n\n promise.cancel = listener.cancel;\n return promise;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isAncestor, isWindowClosed, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { uniqueID, isRegex, noop, safeInterval, stringify, stringifyError } from 'belter/src';\n\n\nimport { CHILD_WINDOW_TIMEOUT, MESSAGE_TYPE, WILDCARD, MESSAGE_NAME, ACK_TIMEOUT, RES_TIMEOUT, ACK_TIMEOUT_KNOWN, RESPONSE_CYCLE_TIME } from '../conf';\nimport { sendMessage, addResponseListener, deleteResponseListener, markResponseListenerErrored, type ResponseListenerType } from '../drivers';\nimport { awaitWindowHello, sayHello, isWindowKnown } from '../lib';\nimport { windowStore } from '../global';\nimport type { SendType } from '../types';\n\nimport { on } from './on';\n\nfunction validateOptions(name : string, win : CrossDomainWindowType, domain : ?DomainMatcher) {\n if (!name) {\n throw new Error('Expected name');\n }\n\n if (domain) {\n if (typeof domain !== 'string' && !Array.isArray(domain) && !isRegex(domain)) {\n throw new TypeError(`Can not send ${ name }. Expected domain ${ JSON.stringify(domain) } to be a string, array, or regex`);\n }\n }\n\n if (isWindowClosed(win)) {\n throw new Error(`Can not send ${ name }. Target window is closed`);\n }\n}\n\nfunction normalizeDomain(win : CrossDomainWindowType, targetDomain : DomainMatcher, actualDomain : ?string, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (typeof targetDomain === 'string') {\n return targetDomain;\n }\n\n return ZalgoPromise.try(() => {\n return actualDomain || sayHello(win, { send }).then(({ domain }) => domain);\n\n }).then(normalizedDomain => {\n if (!matchDomain(targetDomain, targetDomain)) {\n throw new Error(`Domain ${ stringify(targetDomain) } does not match ${ stringify(targetDomain) }`);\n }\n\n return normalizedDomain;\n });\n });\n}\n\nexport const send : SendType = (win, name, data, options) => {\n options = options || {};\n const domainMatcher = options.domain || WILDCARD;\n const responseTimeout = options.timeout || RES_TIMEOUT;\n const childTimeout = options.timeout || CHILD_WINDOW_TIMEOUT;\n const fireAndForget = options.fireAndForget || false;\n\n // $FlowFixMe\n return ZalgoPromise.try(() => {\n validateOptions(name, win, domainMatcher);\n\n if (isAncestor(window, win)) {\n return awaitWindowHello(win, childTimeout);\n }\n \n }).then(({ domain: actualDomain } = {}) => {\n\n return normalizeDomain(win, domainMatcher, actualDomain, { send });\n }).then(targetDomain => {\n const domain = targetDomain;\n\n const logName = (name === MESSAGE_NAME.METHOD && data && typeof data.name === 'string') ? `${ data.name }()` : name;\n\n if (__DEBUG__) {\n console.info('send::req', logName, domain, '\\n\\n', data); // eslint-disable-line no-console\n }\n\n const promise = new ZalgoPromise();\n const hash = `${ name }_${ uniqueID() }`;\n\n if (!fireAndForget) {\n const responseListener : ResponseListenerType = { name, win, domain, promise };\n addResponseListener(hash, responseListener);\n\n const reqPromises = windowStore('requestPromises').getOrSet(win, () => []);\n reqPromises.push(promise);\n\n promise.catch(() => {\n markResponseListenerErrored(hash);\n deleteResponseListener(hash);\n });\n\n const totalAckTimeout = isWindowKnown(win) ? ACK_TIMEOUT_KNOWN : ACK_TIMEOUT;\n const totalResTimeout = responseTimeout;\n\n let ackTimeout = totalAckTimeout;\n let resTimeout = totalResTimeout;\n \n const interval = safeInterval(() => {\n if (isWindowClosed(win)) {\n return promise.reject(new Error(`Window closed for ${ name } before ${ responseListener.ack ? 'response' : 'ack' }`));\n }\n\n if (responseListener.cancelled) {\n return promise.reject(new Error(`Response listener was cancelled for ${ name }`));\n }\n\n ackTimeout = Math.max(ackTimeout - RESPONSE_CYCLE_TIME, 0);\n if (resTimeout !== -1) {\n resTimeout = Math.max(resTimeout - RESPONSE_CYCLE_TIME, 0);\n }\n\n if (!responseListener.ack && ackTimeout === 0) {\n return promise.reject(new Error(`No ack for postMessage ${ logName } in ${ getDomain() } in ${ totalAckTimeout }ms`));\n\n } else if (resTimeout === 0) {\n return promise.reject(new Error(`No response for postMessage ${ logName } in ${ getDomain() } in ${ totalResTimeout }ms`));\n }\n }, RESPONSE_CYCLE_TIME);\n\n promise.finally(() => {\n interval.cancel();\n reqPromises.splice(reqPromises.indexOf(promise, 1));\n }).catch(noop);\n }\n\n return sendMessage(win, domain, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.REQUEST,\n hash,\n name,\n data,\n fireAndForget\n }, { on, send }).then(() => {\n return fireAndForget ? promise.resolve() : promise;\n }, err => {\n throw new Error(`Send request message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n });\n });\n};\n","/* @flow */\n\nexport const BRIDGE_TIMEOUT = 5000;\nexport const CHILD_WINDOW_TIMEOUT = 5000;\n\nexport const ACK_TIMEOUT = 2000;\nexport const ACK_TIMEOUT_KNOWN = 10000;\nexport const RES_TIMEOUT = __TEST__ ? 2000 : -1;\nexport const RESPONSE_CYCLE_TIME = 500;\n","/* @flow */\n\nimport type { CrossDomainWindowType, DomainMatcher } from 'cross-domain-utils/src';\n\nimport { initHello } from './lib';\nimport { listenForMessages, stopListenForMessages, receiveMessage, setupGlobalReceiveMessage, cancelResponseListeners } from './drivers';\nimport { getGlobal, deleteGlobal } from './global';\nimport { on, send } from './public';\nimport { setupBridge } from './bridge';\nimport { serializeMessage as internalSerializeMessage, deserializeMessage as internalDeserializeMessage, ProxyWindow } from './serialize';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T) : string {\n return internalSerializeMessage(destination, domain, obj, { on, send });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string) : T {\n return internalDeserializeMessage(source, origin, message, { on, send });\n}\n\nexport function createProxyWindow(win? : CrossDomainWindowType) : ProxyWindow {\n return new ProxyWindow({ send, win });\n}\n\nexport function toProxyWindow(win : CrossDomainWindowType | ProxyWindow) : ProxyWindow {\n return ProxyWindow.toProxyWindow(win, { send });\n}\n\nexport function setup() {\n if (!getGlobal().initialized) {\n getGlobal().initialized = true;\n \n setupGlobalReceiveMessage({ on, send });\n listenForMessages({ on, send });\n \n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n setupBridge({ on, send, receiveMessage });\n }\n\n initHello({ on, send });\n }\n}\n\nexport function destroy() {\n cancelResponseListeners();\n stopListenForMessages();\n deleteGlobal();\n}\n","/* @flow */\n\nimport { isSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nexport function getGlobal(win? : CrossDomainWindowType = window) : Object {\n\n if (!isSameDomain(win)) {\n throw new Error(`Can not get global for window on different domain`);\n }\n\n if (!win[__ZOID__.__GLOBAL_KEY__]) {\n win[__ZOID__.__GLOBAL_KEY__] = {};\n }\n\n return win[__ZOID__.__GLOBAL_KEY__];\n}\n\nexport function destroyGlobal() {\n delete window[__ZOID__.__GLOBAL_KEY__];\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\n\nexport type ProxyObject = {|\n get : () => ZalgoPromise\n|};\n\nexport function getProxyObject(obj : T) : ProxyObject {\n return {\n get() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (this.source && this.source !== window) {\n throw new Error(`Can not call get on proxy object from a remote window`);\n }\n \n return obj;\n });\n }\n };\n}\n","/* @flow */\n\nimport { WINDOW_TYPE } from 'cross-domain-utils/src';\n\nexport const ZOID = `zoid`;\n\nexport const POST_MESSAGE = {\n DELEGATE: `${ ZOID }_delegate`,\n ALLOW_DELEGATE: `${ ZOID }_allow_delegate`\n};\n\nexport const PROP_TYPE = {\n STRING: `string`,\n OBJECT: `object`,\n FUNCTION: `function`,\n BOOLEAN: `boolean`,\n NUMBER: `number`,\n ARRAY: `array`\n};\n\nexport const INITIAL_PROPS = {\n RAW: 'raw',\n UID: 'uid'\n};\n\nexport const WINDOW_REFERENCES = {\n OPENER: ('opener' : 'opener'),\n PARENT: ('parent' : 'parent'),\n GLOBAL: ('global' : 'global')\n};\n\nexport const PROP_SERIALIZATION = {\n JSON: ('json' : 'json'),\n DOTIFY: ('dotify' : 'dotify'),\n BASE64: ('base64' : 'base64')\n};\n\nexport const CONTEXT = WINDOW_TYPE;\n\nexport const WILDCARD = '*';\n\nexport const DEFAULT_DIMENSIONS = {\n WIDTH: '300px',\n HEIGHT: '150px'\n};\n\nexport const EVENT = {\n RENDER: 'zoid-render',\n RENDERED: 'zoid-rendered',\n DISPLAY: 'zoid-display',\n ERROR: 'zoid-error',\n CLOSE: 'zoid-close',\n DESTROY: 'zoid-destroy',\n PROPS: 'zoid-props',\n RESIZE: 'zoid-resize',\n FOCUS: 'zoid-focus'\n};\n","/* @flow */\n\nimport { getDomain, isSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport type { PropsDefinitionType, PropsType } from '../component/props';\n\nimport type { ChildHelpers } from './index';\n\n// $FlowFixMe\nexport function normalizeChildProp(propsDef : PropsDefinitionType

, props : PropsType

, key : string, value : ?T, helpers : ChildHelpers

) : ?T {\n if (!propsDef.hasOwnProperty(key)) {\n return value;\n }\n\n const prop = propsDef[key];\n\n if (typeof prop.childDecorate === 'function') {\n const { close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide } = helpers;\n const decoratedValue = prop.childDecorate({ value, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide });\n\n // $FlowFixMe\n return decoratedValue;\n }\n\n return value;\n}\n\n// eslint-disable-next-line max-params\nexport function normalizeChildProps

(parentComponentWindow : CrossDomainWindowType, propsDef : PropsDefinitionType

, props : PropsType

, origin : string, helpers : ChildHelpers

, isUpdate : boolean = false) : (PropsType

) {\n\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sameDomain && (origin !== getDomain(window) || !isSameDomain(parentComponentWindow))) {\n continue;\n }\n\n // $FlowFixMe\n const value = normalizeChildProp(propsDef, props, key, props[key], helpers);\n\n result[key] = value;\n if (prop && prop.alias && !result[prop.alias]) {\n result[prop.alias] = value;\n }\n }\n\n if (!isUpdate) {\n for (const key of Object.keys(propsDef)) {\n if (!props.hasOwnProperty(key)) {\n result[key] = normalizeChildProp(propsDef, props, key, undefined, helpers);\n }\n }\n }\n\n // $FlowFixMe\n return result;\n}\n","/* @flow */\n\nimport { inlineMemoize, stringifyError, base64decode } from 'belter/src';\n\nimport { ZOID } from '../constants';\nimport type { ChildPayload } from '../parent';\n\nfunction parseChildWindowName(windowName : string) : ChildPayload {\n return inlineMemoize(parseChildWindowName, () => {\n if (!windowName) {\n throw new Error(`No window name`);\n }\n \n const [ , zoidcomp, name, encodedPayload ] = windowName.split('__');\n \n if (zoidcomp !== ZOID) {\n throw new Error(`Window not rendered by zoid - got ${ zoidcomp }`);\n }\n \n if (!name) {\n throw new Error(`Expected component name`);\n }\n \n if (!encodedPayload) {\n throw new Error(`Expected encoded payload`);\n }\n \n try {\n return JSON.parse(base64decode(encodedPayload));\n } catch (err) {\n throw new Error(`Can not decode window name payload: ${ encodedPayload }: ${ stringifyError(err) }`);\n }\n }, [ windowName ]);\n}\n\nexport function getChildPayload() : ?ChildPayload {\n try {\n return parseChildWindowName(window.name);\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isSameDomain, matchDomain, getDomain, getOpener,\n getNthParentFromTop, getAncestor, getAllFramesInWindow,\n type CrossDomainWindowType, onCloseWindow } from 'cross-domain-utils/src';\nimport { markWindowKnown, deserializeMessage, type CrossDomainFunctionType } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { extend, waitForDocumentBody, onResize, getElementSafe, assertExists } from 'belter/src';\n\nimport { getGlobal } from '../lib';\nimport { CONTEXT, INITIAL_PROPS, WINDOW_REFERENCES } from '../constants';\nimport type { NormalizedComponentOptionsType } from '../component';\nimport type { PropsType } from '../component/props';\nimport type { WindowRef, PropRef } from '../parent';\nimport type { StringMatcherType } from '../types';\n\nimport { normalizeChildProps } from './props';\nimport { getChildPayload } from './window';\n\nexport type ChildExportsType

= {|\n updateProps : CrossDomainFunctionType<[ PropsType

], void>,\n close : CrossDomainFunctionType<[], void>\n|};\n\nexport type ChildHelpers

= {|\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n onProps : ((PropsType

) => void) => void,\n getParent : () => CrossDomainWindowType,\n getParentDomain : () => string,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise\n|};\n\nfunction getParentComponentWindow(ref : WindowRef) : CrossDomainWindowType {\n const { type } = ref;\n\n if (type === WINDOW_REFERENCES.OPENER) {\n return assertExists('opener', getOpener(window));\n\n } else if (type === WINDOW_REFERENCES.PARENT && typeof ref.distance === 'number') {\n return assertExists('parent', getNthParentFromTop(window, ref.distance));\n\n } else if (type === WINDOW_REFERENCES.GLOBAL && ref.uid && typeof ref.uid === 'string') {\n const { uid } = ref;\n const ancestor = getAncestor(window);\n\n if (!ancestor) {\n throw new Error(`Can not find ancestor window`);\n }\n\n for (const frame of getAllFramesInWindow(ancestor)) {\n if (isSameDomain(frame)) {\n const global = getGlobal(frame);\n\n if (global && global.windows && global.windows[uid]) {\n return global.windows[uid];\n }\n }\n }\n }\n\n throw new Error(`Unable to find ${ type } parent component window`);\n}\n\nfunction checkParentDomain(allowedParentDomains : StringMatcherType, domain : string) {\n if (!matchDomain(allowedParentDomains, domain)) {\n throw new Error(`Can not be rendered by domain: ${ domain }`);\n }\n}\n\nfunction focus() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.focus();\n });\n}\n\nfunction destroy() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.close();\n });\n}\n\nfunction getPropsByRef

(parentComponentWindow : CrossDomainWindowType, domain : string, { type, value, uid } : PropRef) : (PropsType

) {\n let props;\n\n if (type === INITIAL_PROPS.RAW) {\n props = value;\n } else if (type === INITIAL_PROPS.UID) {\n if (!isSameDomain(parentComponentWindow)) {\n throw new Error(`Parent component window is on a different domain - expected ${ getDomain() } - can not retrieve props`);\n }\n\n const global = getGlobal(parentComponentWindow);\n props = assertExists('props', global && global.props[uid]);\n }\n\n if (!props) {\n throw new Error(`Could not find props`);\n }\n\n return deserializeMessage(parentComponentWindow, domain, props);\n}\n\nexport type ChildComponent

= {|\n getProps : () => PropsType

,\n init : () => ZalgoPromise\n|};\n\nexport function childComponent

(options : NormalizedComponentOptionsType

) : ChildComponent

{\n const { propsDef, autoResize, allowedParentDomains } = options;\n\n const onPropHandlers = [];\n const childPayload = getChildPayload();\n let props : PropsType

;\n\n if (!childPayload) {\n throw new Error(`No child payload found`);\n }\n\n if (childPayload.version !== __ZOID__.__VERSION__) {\n throw new Error(`Parent window has zoid version ${ childPayload.version }, child window has version ${ __ZOID__.__VERSION__ }`);\n }\n\n const { parent: parentRef, parentDomain, exports, context, props: propsRef } = childPayload;\n const parentComponentWindow = getParentComponentWindow(parentRef);\n const parent = deserializeMessage(parentComponentWindow, parentDomain, exports);\n\n const { show, hide, close } = parent;\n\n const getParent = () => parentComponentWindow;\n const getParentDomain = () => parentDomain;\n \n const onProps = (handler : Function) => {\n onPropHandlers.push(handler);\n };\n\n const onError = (err : mixed) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n if (parent && parent.onError) {\n return parent.onError(err);\n } else {\n throw err;\n }\n });\n };\n\n const resize = ({ width, height } : {| width : ?number, height : ?number |}) : ZalgoPromise => {\n return parent.resize.fireAndForget({ width, height });\n };\n\n const getHelpers = () : ChildHelpers

=> {\n return {\n show, hide, close, focus, onError, resize,\n onProps, getParent, getParentDomain\n };\n };\n\n const watchForClose = () => {\n window.addEventListener('beforeunload', () => {\n parent.checkClose.fireAndForget();\n });\n\n window.addEventListener('unload', () => {\n parent.checkClose.fireAndForget();\n });\n\n onCloseWindow(parentComponentWindow, () => {\n destroy();\n });\n };\n\n const setProps = (newProps : PropsType

, origin : string, isUpdate : boolean = false) => {\n const helpers = getHelpers();\n const normalizedProps = normalizeChildProps(parentComponentWindow, propsDef, newProps, origin, helpers, isUpdate);\n\n if (props) {\n extend(props, normalizedProps);\n } else {\n props = normalizedProps;\n }\n\n for (const handler of onPropHandlers) {\n handler(props);\n }\n };\n \n const getAutoResize = () : {| width : boolean, height : boolean, element : ?HTMLElement |} => {\n let { width = false, height = false, element = 'body' } = autoResize;\n element = getElementSafe(element);\n return { width, height, element };\n };\n\n const watchForResize = () : ?ZalgoPromise => {\n return waitForDocumentBody().then(() => {\n const { width, height, element } = getAutoResize();\n\n if (!element || (!width && !height) || context === CONTEXT.POPUP) {\n return;\n }\n\n onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height });\n });\n };\n\n const updateProps = (newProps : (PropsType

)) : ZalgoPromise => {\n return ZalgoPromise.try(() => setProps(newProps, parentDomain, true));\n };\n\n const init = () => {\n return ZalgoPromise.try(() => {\n checkParentDomain(allowedParentDomains, parentDomain);\n markWindowKnown(parentComponentWindow);\n watchForClose();\n\n return parent.init({ updateProps, close: destroy });\n \n }).then(() => {\n return watchForResize();\n \n }).catch(err => {\n onError(err);\n });\n };\n\n const getProps = () => {\n if (props) {\n return props;\n }\n\n setProps(getPropsByRef(parentComponentWindow, parentDomain, propsRef), parentDomain);\n return props;\n };\n\n return {\n init,\n getProps\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { dotify, isDefined, extend } from 'belter/src';\n\nimport type { PropsInputType, PropsType, PropsDefinitionType, MixedPropDefinitionType } from '../component/props';\nimport { PROP_SERIALIZATION } from '../constants';\n\nimport type { ParentHelpers } from './index';\n\n/* Normalize Props\n ---------------\n\n Turn props into normalized values, using defaults, function options, etc.\n*/\n\nexport function extendProps

(propsDef : PropsDefinitionType

, props : PropsType

, inputProps : PropsInputType

, helpers : ParentHelpers

, isUpdate : boolean = false) { // eslint-disable-line complexity\n\n // $FlowFixMe\n inputProps = inputProps || {};\n extend(props, inputProps);\n\n const propNames = isUpdate ? [] : [ ...Object.keys(propsDef) ];\n\n for (const key of Object.keys(inputProps)) {\n if (propNames.indexOf(key) === -1) {\n propNames.push(key);\n }\n }\n\n const aliases = [];\n\n const { state, close, focus, event, onError } = helpers;\n\n for (const key of propNames) {\n const propDef = propsDef[key];\n\n // $FlowFixMe\n let value = inputProps[key];\n\n if (!propDef) {\n continue;\n }\n\n const alias = propDef.alias;\n if (alias) {\n if (!isDefined(value) && isDefined(inputProps[alias])) {\n value = inputProps[alias];\n }\n aliases.push(alias);\n }\n\n if (propDef.value) {\n value = propDef.value({ props, state, close, focus, event, onError });\n }\n\n if (!isDefined(value) && propDef.default) {\n value = propDef.default({ props, state, close, focus, event, onError });\n }\n\n if (isDefined(value)) {\n if (propDef.type === 'array' ? !Array.isArray(value) : (typeof value !== propDef.type)) {\n throw new TypeError(`Prop is not of type ${ propDef.type }: ${ key }`);\n }\n }\n \n // $FlowFixMe\n props[key] = value;\n }\n\n for (const alias of aliases) {\n delete props[alias];\n }\n\n // $FlowFixMe\n for (const key of Object.keys(props)) {\n const propDef = propsDef[key];\n const value = props[key];\n\n if (!propDef) {\n continue;\n }\n\n if (__DEBUG__ && isDefined(value) && propDef.validate) {\n propDef.validate({ value, props });\n }\n\n if (isDefined(value) && propDef.decorate) {\n props[key] = propDef.decorate({ value, props, state, close, focus, event, onError });\n }\n }\n\n for (const key of Object.keys(propsDef)) {\n const propDef = propsDef[key];\n // $FlowFixMe\n const propVal = props[key];\n if (propDef.required !== false && !isDefined(propVal)) {\n throw new Error(`Expected prop \"${ key }\" to be defined`);\n }\n }\n}\n\n// $FlowFixMe\nfunction getQueryParam

(prop : MixedPropDefinitionType

, key : string, value : string) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (typeof prop.queryParam === 'function') {\n return prop.queryParam({ value });\n } else if (typeof prop.queryParam === 'string') {\n return prop.queryParam;\n } else {\n return key;\n }\n });\n}\n\n// $FlowFixMe\nfunction getQueryValue

(prop : MixedPropDefinitionType

, key : string, value : string) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (typeof prop.queryValue === 'function' && isDefined(value)) {\n return prop.queryValue({ value });\n } else {\n return value;\n }\n });\n}\n\nexport function propsToQuery

(propsDef : PropsDefinitionType

, props : (PropsType

)) : ZalgoPromise<{ [string] : string }> {\n\n const params = {};\n\n // $FlowFixMe\n const keys = Object.keys(props);\n \n return ZalgoPromise.all(keys.map(key => {\n\n const prop = propsDef[key];\n\n if (!prop) {\n return; // eslint-disable-line array-callback-return\n }\n\n return ZalgoPromise.resolve().then(() => {\n\n const value = props[key];\n\n if (!value) {\n return;\n }\n\n if (!prop.queryParam) {\n return;\n }\n\n return value;\n\n }).then(value => {\n\n if (value === null || typeof value === 'undefined') {\n return;\n }\n\n return ZalgoPromise.all([\n getQueryParam(prop, key, value),\n getQueryValue(prop, key, value)\n ]).then(([ queryParam, queryValue ]) => {\n\n let result;\n\n if (typeof queryValue === 'boolean') {\n result = queryValue.toString();\n } else if (typeof queryValue === 'string') {\n result = queryValue.toString();\n } else if (typeof queryValue === 'object' && queryValue !== null) {\n\n if (prop.serialization === PROP_SERIALIZATION.JSON) {\n result = JSON.stringify(queryValue);\n } else if (prop.serialization === PROP_SERIALIZATION.BASE64) {\n result = btoa(JSON.stringify(queryValue));\n } else if (prop.serialization === PROP_SERIALIZATION.DOTIFY || !prop.serialization) {\n result = dotify(queryValue, key);\n\n for (const dotkey of Object.keys(result)) {\n params[dotkey] = result[dotkey];\n }\n\n return;\n }\n\n } else if (typeof queryValue === 'number') {\n result = queryValue.toString();\n }\n\n params[queryParam] = result;\n });\n });\n\n })).then(() => {\n return params;\n });\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { send, bridge, serializeMessage, ProxyWindow, toProxyWindow, type CrossDomainFunctionType, cleanUpWindow } from 'post-robot/src';\nimport { isSameDomain, matchDomain, getDomainFromUrl, isBlankDomain,\n getDomain, type CrossDomainWindowType,\n getDistanceFromTop, normalizeMockUrl, assertSameDomain, closeWindow, onCloseWindow, isWindowClosed, isSameTopWindow } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { addEventListener, uniqueID, elementReady, writeElementToWindow, eventEmitter, type EventEmitterType,\n noop, onResize, extendUrl, appendChild, cleanup, base64encode, isRegex,\n once, stringifyError, destroyElement, getElementSafe, showElement, hideElement, iframe,\n awaitFrameWindow, popup, normalizeDimension, watchElementForClose, isShadowElement, insertShadowSlot } from 'belter/src';\n\nimport { ZOID, POST_MESSAGE, CONTEXT, EVENT,\n INITIAL_PROPS, WINDOW_REFERENCES } from '../constants';\nimport { getGlobal, getProxyObject, type ProxyObject } from '../lib';\nimport type { PropsInputType, PropsType } from '../component/props';\nimport type { ChildExportsType } from '../child';\nimport type { CssDimensionsType } from '../types';\nimport type { NormalizedComponentOptionsType, AttributesType } from '../component';\n\nimport { propsToQuery, extendProps } from './props';\n\nexport type RenderOptionsType

= {|\n uid : string,\n props : PropsInputType

,\n tag : string,\n context : $Values,\n close : (?string) => ZalgoPromise,\n focus : () => ZalgoPromise,\n doc : Document,\n container? : HTMLElement,\n dimensions : CssDimensionsType,\n state : Object,\n event : EventEmitterType,\n frame : ?HTMLIFrameElement,\n prerenderFrame : ?HTMLIFrameElement\n|};\n\nexport type ParentExportsType

= {|\n init : (ChildExportsType

) => ZalgoPromise,\n close : () => ZalgoPromise,\n checkClose : CrossDomainFunctionType<[], boolean>,\n resize : CrossDomainFunctionType<[{| width? : ?number, height? : ?number |}], void>,\n onError : (mixed) => ZalgoPromise,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise\n|};\n\nexport type PropRef =\n {| type : typeof INITIAL_PROPS.RAW, uid? : string, value? : string |};\n\nexport type WindowRef =\n {| type : typeof WINDOW_REFERENCES.OPENER |} |\n {| type : typeof WINDOW_REFERENCES.PARENT, distance : number |} |\n {| type : typeof WINDOW_REFERENCES.GLOBAL, uid : string |};\n\nexport type ChildPayload = {|\n uid : string,\n tag : string,\n version : string,\n context : $Values,\n parentDomain : string,\n childDomain : string,\n parent : WindowRef,\n props : PropRef,\n exports : string\n|};\n\nexport type StateType = Object;\n\nexport type ParentHelpers

= {|\n state : StateType,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n updateProps : PropsInputType

=> ZalgoPromise,\n event : EventEmitterType,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise\n|};\n\nfunction getDefaultProps

() : PropsType

{\n // $FlowFixMe\n return {};\n}\n\ntype InternalState = {|\n visible : boolean\n|};\n\ntype GetProxyContainer = (container : string | HTMLElement) => ZalgoPromise>;\ntype Show = () => ZalgoPromise;\ntype Hide = () => ZalgoPromise;\ntype Close = () => ZalgoPromise;\ntype OnError = (mixed) => ZalgoPromise;\ntype RenderContainer = (proxyContainer : ProxyObject, {| context : $Values, uid : string, proxyFrame : ?ProxyObject, proxyPrerenderFrame : ?ProxyObject |}) => ZalgoPromise>;\ntype SetProxyWin = (ProxyWindow) => ZalgoPromise;\ntype GetProxyWindow = () => ZalgoPromise;\ntype OpenFrame = (context : $Values, {| windowName : string |}) => ZalgoPromise>;\ntype OpenPrerenderFrame = (context : $Values) => ZalgoPromise>;\ntype Prerender = (proxyPrerenderWin : ProxyWindow, {| context : $Values, uid : string |}) => ZalgoPromise;\ntype Open = (context : $Values, {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) => ZalgoPromise;\ntype OpenPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) => ZalgoPromise;\ntype WatchForUnload = () => ZalgoPromise;\ntype GetInternalState = () => ZalgoPromise;\ntype SetInternalState = (InternalState) => ZalgoPromise;\n\ntype ParentDelegateOverrides

= {|\n props : PropsType

,\n event : EventEmitterType,\n close : Close,\n onError : OnError,\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload,\n getInternalState : GetInternalState,\n setInternalState : SetInternalState\n|};\n\ntype DelegateOverrides = {|\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload\n|};\n\ntype ParentComponent

= {|\n init : () => void,\n render : (CrossDomainWindowType, string | HTMLElement, $Values) => ZalgoPromise,\n setProps : (newProps : PropsInputType

, isUpdate? : boolean) => void,\n destroy : (err? : mixed) => ZalgoPromise,\n getHelpers : () => ParentHelpers

,\n getDelegateOverrides : () => ZalgoPromise\n|};\n\nconst getDefaultOverrides =

() : ParentDelegateOverrides

=> {\n // $FlowFixMe\n return {};\n};\n\nexport function parentComponent

(options : NormalizedComponentOptionsType

, overrides? : ParentDelegateOverrides

= getDefaultOverrides(), parentWin : CrossDomainWindowType = window) : ParentComponent

{\n const { propsDef, containerTemplate, prerenderTemplate, tag, name, attributes, dimensions, autoResize, url, domain: domainMatch, validate } = options;\n\n const initPromise = new ZalgoPromise();\n const handledErrors = [];\n const clean = cleanup();\n const state = {};\n let internalState = {\n visible: true\n };\n const event = overrides.event ? overrides.event : eventEmitter();\n const props = overrides.props ? overrides.props : getDefaultProps();\n\n let currentProxyWin : ?ProxyWindow;\n let currentProxyContainer : ?ProxyObject;\n let childComponent : ?ChildExportsType

;\n\n const onErrorOverride : ?OnError = overrides.onError;\n let getProxyContainerOverride : ?GetProxyContainer = overrides.getProxyContainer;\n let showOverride : ?Show = overrides.show;\n let hideOverride : ?Hide = overrides.hide;\n const closeOverride : ?Close = overrides.close;\n let renderContainerOverride : ?RenderContainer = overrides.renderContainer;\n let getProxyWindowOverride : ?GetProxyWindow = overrides.getProxyWindow;\n let setProxyWinOverride : ?SetProxyWin = overrides.setProxyWin;\n let openFrameOverride : ?OpenFrame = overrides.openFrame;\n let openPrerenderFrameOverride : ?OpenPrerenderFrame = overrides.openPrerenderFrame;\n let prerenderOverride : ?Prerender = overrides.prerender;\n let openOverride : ?Open = overrides.open;\n let openPrerenderOverride : ?OpenPrerender = overrides.openPrerender;\n let watchForUnloadOverride : ?WatchForUnload = overrides.watchForUnload;\n const getInternalStateOverride : ?GetInternalState = overrides.getInternalState;\n const setInternalStateOverride : ?SetInternalState = overrides.setInternalState;\n\n const getPropsForChild = (domain : string | RegExp) : ZalgoPromise> => {\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sendToChild === false) {\n continue;\n }\n\n if (prop && prop.sameDomain && !matchDomain(domain, getDomain(window))) {\n continue;\n }\n \n result[key] = props[key];\n }\n\n // $FlowFixMe\n return ZalgoPromise.hash(result);\n };\n\n const setupEvents = () => {\n event.on(EVENT.RENDER, () => props.onRender());\n event.on(EVENT.DISPLAY, () => props.onDisplay());\n event.on(EVENT.RENDERED, () => props.onRendered());\n event.on(EVENT.CLOSE, () => props.onClose());\n event.on(EVENT.DESTROY, () => props.onDestroy());\n event.on(EVENT.RESIZE, () => props.onResize());\n event.on(EVENT.FOCUS, () => props.onFocus());\n event.on(EVENT.PROPS, (newProps) => props.onProps(newProps));\n event.on(EVENT.ERROR, err => {\n if (props && props.onError) {\n return props.onError(err);\n } else {\n return initPromise.reject(err).then(() => {\n setTimeout(() => {\n throw err;\n }, 1);\n });\n }\n });\n\n clean.register(event.reset);\n };\n\n const getInternalState = () => {\n return ZalgoPromise.try(() => {\n if (getInternalStateOverride) {\n return getInternalStateOverride();\n }\n\n return internalState;\n });\n };\n\n const setInternalState = (newInternalState) => {\n return ZalgoPromise.try(() => {\n if (setInternalStateOverride) {\n return setInternalStateOverride(newInternalState);\n }\n\n internalState = { ...internalState, ...newInternalState };\n return internalState;\n });\n };\n\n const getProxyWindow = () : ZalgoPromise => {\n if (getProxyWindowOverride) {\n return getProxyWindowOverride();\n }\n\n return ZalgoPromise.try(() => {\n const windowProp = props.window;\n\n if (windowProp) {\n const proxyWin = toProxyWindow(windowProp);\n clean.register(() => windowProp.close());\n return proxyWin;\n }\n\n return new ProxyWindow({ send });\n });\n };\n\n const getProxyContainer : GetProxyContainer = (container : string | HTMLElement) : ZalgoPromise> => {\n if (getProxyContainerOverride) {\n return getProxyContainerOverride(container);\n }\n\n return ZalgoPromise.try(() => {\n return elementReady(container);\n }).then(containerElement => {\n if (isShadowElement(containerElement)) {\n containerElement = insertShadowSlot(containerElement);\n }\n\n return getProxyObject(containerElement);\n });\n };\n\n const getPropsRef = (proxyWin : ProxyWindow, childDomain : string, domain : string | RegExp, uid : string) : ZalgoPromise => {\n return getPropsForChild(domain).then(childProps => {\n const value = serializeMessage(proxyWin, domain, childProps);\n\n const propRef = (childDomain === getDomain())\n ? { type: INITIAL_PROPS.UID, uid }\n : { type: INITIAL_PROPS.RAW, value };\n\n if (propRef.type === INITIAL_PROPS.UID) {\n const global = getGlobal(window);\n global.props = global.props || {};\n global.props[uid] = value;\n\n clean.register(() => {\n delete global.props[uid];\n });\n }\n\n return propRef;\n });\n };\n\n const setProxyWin = (proxyWin : ProxyWindow) : ZalgoPromise => {\n if (setProxyWinOverride) {\n return setProxyWinOverride(proxyWin);\n }\n\n return ZalgoPromise.try(() => {\n currentProxyWin = proxyWin;\n });\n };\n\n const show = () : ZalgoPromise => {\n if (showOverride) {\n return showOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: true }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null\n }).then(noop);\n };\n\n const hide = () : ZalgoPromise => {\n if (hideOverride) {\n return hideOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: false }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null\n }).then(noop);\n };\n\n const getUrl = () : string => {\n if (typeof url === 'function') {\n return url({ props });\n }\n\n return url;\n };\n\n const getAttributes = () : AttributesType => {\n if (typeof attributes === 'function') {\n return attributes({ props });\n }\n\n return attributes;\n };\n\n const buildUrl = () : ZalgoPromise => {\n return propsToQuery(propsDef, props).then(query => {\n return extendUrl(normalizeMockUrl(getUrl()), { query });\n });\n };\n\n const getChildDomain = () : string => {\n if (domainMatch && typeof domainMatch === 'string') {\n return domainMatch;\n }\n\n return getDomainFromUrl(getUrl());\n };\n\n const getDomainMatcher = () : string | RegExp => {\n if (domainMatch && isRegex(domainMatch)) {\n return domainMatch;\n }\n\n return getChildDomain();\n };\n\n const openFrame = (context : $Values, { windowName } : {| windowName : string |}) : ZalgoPromise> => {\n if (openFrameOverride) {\n return openFrameOverride(context, { windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n title: name,\n ...getAttributes().iframe\n };\n\n return getProxyObject(iframe({ attributes: attrs }));\n }\n });\n };\n\n const openPrerenderFrame = (context : $Values) : ZalgoPromise> => {\n if (openPrerenderFrameOverride) {\n return openPrerenderFrameOverride(context);\n }\n\n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n // $FlowFixMe\n const attrs = {\n name: `__zoid_prerender_frame__${ name }_${ uniqueID() }__`,\n title: `prerender__${ name }`,\n ...getAttributes().iframe\n };\n return getProxyObject(iframe({\n attributes: attrs\n }));\n }\n });\n };\n \n const openPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) : ZalgoPromise => {\n if (openPrerenderOverride) {\n return openPrerenderOverride(context, proxyWin, proxyPrerenderFrame);\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyPrerenderFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyPrerenderFrame.get().then(prerenderFrame => {\n clean.register(() => destroyElement(prerenderFrame));\n \n return awaitFrameWindow(prerenderFrame).then(prerenderFrameWindow => {\n return assertSameDomain(prerenderFrameWindow);\n }).then(win => {\n return toProxyWindow(win);\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n return proxyWin;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n });\n };\n\n const focus = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n if (currentProxyWin) {\n return ZalgoPromise.all([\n event.trigger(EVENT.FOCUS),\n currentProxyWin.focus()\n ]).then(noop);\n }\n });\n };\n\n const getWindowRef = (target : CrossDomainWindowType, domain : string, uid : string, context : $Values) : WindowRef => {\n \n if (domain === getDomain(window)) {\n const global = getGlobal(window);\n global.windows = global.windows || {};\n global.windows[uid] = window;\n clean.register(() => {\n delete global.windows[uid];\n });\n \n return { type: WINDOW_REFERENCES.GLOBAL, uid };\n }\n\n if (context === CONTEXT.POPUP) {\n return { type: WINDOW_REFERENCES.OPENER };\n }\n\n return { type: WINDOW_REFERENCES.PARENT, distance: getDistanceFromTop(window) };\n };\n\n const runTimeout = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const timeout = props.timeout;\n\n if (timeout) {\n return initPromise.timeout(timeout, new Error(`Loading component timed out after ${ timeout } milliseconds`));\n }\n });\n };\n\n const initChild = (childExports : ChildExportsType

) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n childComponent = childExports;\n initPromise.resolve();\n clean.register(() => childExports.close.fireAndForget().catch(noop));\n });\n };\n\n const resize = ({ width, height } : {| width? : ?number, height? : ?number |}) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n event.trigger(EVENT.RESIZE, { width, height });\n });\n };\n\n const destroy = (err? : mixed) : ZalgoPromise => {\n // eslint-disable-next-line promise/no-promise-in-callback\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.DESTROY);\n }).catch(noop).then(() => {\n return clean.all();\n }).then(() => {\n initPromise.asyncReject(err || new Error('Component destroyed'));\n });\n };\n\n const close = () : ZalgoPromise => {\n if (closeOverride) {\n return closeOverride();\n }\n\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.CLOSE);\n }).then(() => {\n return destroy(new Error(`Window closed`));\n });\n };\n\n const open = (context : $Values, { proxyWin, proxyFrame, windowName } : {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) : ZalgoPromise => {\n if (openOverride) {\n return openOverride(context, { proxyWin, proxyFrame, windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyFrame.get().then(frame => {\n return awaitFrameWindow(frame).then(win => {\n \n const frameWatcher = watchElementForClose(frame, close);\n clean.register(() => frameWatcher.cancel());\n clean.register(() => destroyElement(frame));\n clean.register(() => cleanUpWindow(win));\n \n return win;\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n let { width, height } = dimensions;\n \n width = normalizeDimension(width, window.outerWidth);\n height = normalizeDimension(height, window.outerWidth);\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n width,\n height,\n ...getAttributes().popup\n };\n \n const win = popup('', attrs);\n \n clean.register(() => closeWindow(win));\n clean.register(() => cleanUpWindow(win));\n\n return win;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n\n }).then(win => {\n proxyWin.setWindow(win, { send });\n return proxyWin;\n });\n };\n\n const watchForUnload = () => {\n return ZalgoPromise.try(() => {\n const unloadWindowListener = addEventListener(window, 'unload', once(() => {\n destroy(new Error(`Window navigated away`));\n }));\n \n const closeParentWindowListener = onCloseWindow(parentWin, destroy, 3000);\n clean.register(closeParentWindowListener.cancel);\n clean.register(unloadWindowListener.cancel);\n\n if (watchForUnloadOverride) {\n return watchForUnloadOverride();\n }\n });\n };\n\n const watchForClose = (proxyWin : ProxyWindow) : ZalgoPromise => {\n let cancelled = false;\n\n clean.register(() => {\n cancelled = true;\n });\n\n return ZalgoPromise.delay(2000).then(() => {\n return proxyWin.isClosed();\n }).then(isClosed => {\n if (isClosed) {\n return close();\n } else if (!cancelled) {\n return watchForClose(proxyWin);\n }\n });\n };\n\n const checkWindowClose = (proxyWin : ProxyWindow) : ZalgoPromise => {\n let closed = false;\n \n return proxyWin.isClosed().then(isClosed => {\n if (isClosed) {\n closed = true;\n return close();\n }\n\n return ZalgoPromise.delay(200)\n .then(() => proxyWin.isClosed())\n .then(secondIsClosed => {\n if (secondIsClosed) {\n closed = true;\n return close();\n }\n });\n }).then(() => {\n return closed;\n });\n };\n\n const onError = (err : mixed) : ZalgoPromise => {\n if (onErrorOverride) {\n return onErrorOverride(err);\n }\n\n return ZalgoPromise.try(() => {\n if (handledErrors.indexOf(err) !== -1) {\n return;\n }\n\n handledErrors.push(err);\n initPromise.asyncReject(err);\n\n return event.trigger(EVENT.ERROR, err);\n });\n };\n\n initChild.onError = onError;\n\n const buildParentExports = (win : ProxyWindow) : ParentExportsType

=> {\n const checkClose = () => checkWindowClose(win);\n return { init: initChild, close, checkClose, resize, onError, show, hide };\n };\n\n const buildChildPayload = ({ proxyWin, childDomain, domain, target = window, context, uid } : {| proxyWin : ProxyWindow, childDomain : string, domain : string | RegExp, target : CrossDomainWindowType, context : $Values, uid : string |} = {}) : ZalgoPromise => {\n return getPropsRef(proxyWin, childDomain, domain, uid).then(propsRef => {\n return {\n uid,\n context,\n tag,\n version: __ZOID__.__VERSION__,\n childDomain,\n parentDomain: getDomain(window),\n parent: getWindowRef(target, childDomain, uid, context),\n props: propsRef,\n exports: serializeMessage(proxyWin, domain, buildParentExports(proxyWin))\n };\n });\n };\n\n const buildWindowName = ({ proxyWin, childDomain, domain, target, uid, context } : {| proxyWin : ProxyWindow, childDomain : string, domain : string | RegExp, target : CrossDomainWindowType, context : $Values, uid : string |}) : ZalgoPromise => {\n return buildChildPayload({ proxyWin, childDomain, domain, target, context, uid }).then(childPayload => {\n return `__${ ZOID }__${ name }__${ base64encode(JSON.stringify(childPayload)) }__`;\n });\n };\n\n const renderTemplate = (renderer : (RenderOptionsType

) => ?HTMLElement, { context, uid, container, doc, frame, prerenderFrame } : {| context : $Values, uid : string, container? : HTMLElement, doc : Document, frame? : ?HTMLIFrameElement, prerenderFrame? : ?HTMLIFrameElement |}) : ?HTMLElement => {\n // $FlowFixMe\n return renderer({\n container, context, uid, doc, frame, prerenderFrame,\n focus, close, state, props, tag, dimensions, event\n });\n };\n\n const prerender = (proxyPrerenderWin : ProxyWindow, { context, uid } : {| context : $Values, uid : string |}) : ZalgoPromise => {\n if (prerenderOverride) {\n return prerenderOverride(proxyPrerenderWin, { context, uid });\n }\n \n return ZalgoPromise.try(() => {\n if (!prerenderTemplate) {\n return;\n }\n\n let prerenderWindow = proxyPrerenderWin.getWindow();\n\n if (!prerenderWindow || !isSameDomain(prerenderWindow) || !isBlankDomain(prerenderWindow)) {\n return;\n }\n\n prerenderWindow = assertSameDomain(prerenderWindow);\n \n const doc = prerenderWindow.document;\n const el = renderTemplate(prerenderTemplate, { context, uid, doc });\n\n if (!el) {\n return;\n }\n\n if (el.ownerDocument !== doc) {\n throw new Error(`Expected prerender template to have been created with document from child window`);\n }\n\n writeElementToWindow(prerenderWindow, el);\n\n let { width = false, height = false, element = 'body' } = autoResize;\n element = getElementSafe(element, doc);\n \n if (element && (width || height)) {\n const prerenderResizeListener = onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height, win: prerenderWindow });\n\n event.on(EVENT.RENDERED, prerenderResizeListener.cancel);\n }\n });\n };\n\n const renderContainer : RenderContainer = (proxyContainer : ProxyObject, { proxyFrame, proxyPrerenderFrame, context, uid } :\n {| context : $Values, uid : string, proxyFrame : ?ProxyObject, proxyPrerenderFrame : ?ProxyObject |}) : ZalgoPromise> => {\n\n if (renderContainerOverride) {\n return renderContainerOverride(proxyContainer, { proxyFrame, proxyPrerenderFrame, context, uid });\n }\n\n return ZalgoPromise.hash({\n container: proxyContainer.get(),\n // $FlowFixMe\n frame: proxyFrame ? proxyFrame.get() : null,\n // $FlowFixMe\n prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null,\n internalState: getInternalState()\n }).then(({ container, frame, prerenderFrame, internalState: { visible } }) => {\n const innerContainer = renderTemplate(containerTemplate, { context, uid, container, frame, prerenderFrame, doc: document });\n if (innerContainer) {\n if (!visible) {\n hideElement(innerContainer);\n }\n appendChild(container, innerContainer);\n clean.register(() => destroyElement(innerContainer));\n currentProxyContainer = getProxyObject(innerContainer);\n return currentProxyContainer;\n }\n });\n };\n\n const getBridgeUrl = () : ?string => {\n if (typeof options.bridgeUrl === 'function') {\n return options.bridgeUrl({ props });\n }\n\n return options.bridgeUrl;\n };\n\n const openBridge = (proxyWin : ProxyWindow, domain : string, context : $Values) : ?ZalgoPromise => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n return ZalgoPromise.try(() => {\n return proxyWin.awaitWindow();\n \n }).then(win => {\n if (!bridge || !bridge.needsBridge({ win, domain }) || bridge.hasBridge(domain, domain)) {\n return;\n }\n\n const bridgeUrl = getBridgeUrl();\n\n if (!bridgeUrl) {\n throw new Error(`Bridge needed to render ${ context }`);\n }\n\n const bridgeDomain = getDomainFromUrl(bridgeUrl);\n bridge.linkUrl(win, domain);\n return bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain);\n });\n }\n };\n\n const getHelpers = () : ParentHelpers

=> {\n return {\n state, event, close, focus, resize,\n // eslint-disable-next-line no-use-before-define\n onError, updateProps, show, hide\n };\n };\n\n const setProps = (newProps : PropsInputType

, isUpdate? : boolean = false) => {\n if (__DEBUG__ && validate) {\n validate({ props: newProps });\n }\n\n const helpers = getHelpers();\n extendProps(propsDef, props, newProps, helpers, isUpdate);\n };\n\n const updateProps = (newProps : PropsInputType

) : ZalgoPromise => {\n setProps(newProps, true);\n\n return initPromise.then(() => {\n const child = childComponent;\n const proxyWin = currentProxyWin;\n \n if (!child || !proxyWin) {\n return;\n }\n\n return getPropsForChild(getDomainMatcher()).then(childProps => {\n return child.updateProps(childProps).catch(err => {\n return checkWindowClose(proxyWin).then(closed => {\n if (!closed) {\n throw err;\n }\n });\n });\n });\n });\n };\n\n const delegate = (context : $Values, target : CrossDomainWindowType) : ZalgoPromise => {\n const delegateProps = {};\n for (const propName of Object.keys(props)) {\n const propDef = propsDef[propName];\n if (propDef && propDef.allowDelegate) {\n delegateProps[propName] = props[propName];\n }\n }\n\n const childOverridesPromise = send(target, `${ POST_MESSAGE.DELEGATE }_${ name }`, {\n overrides: { props: delegateProps, event, close, onError, getInternalState, setInternalState }\n }).then(({ data: { parent } }) => {\n clean.register(() => {\n if (!isWindowClosed(target)) {\n return parent.destroy();\n }\n });\n return parent.getDelegateOverrides();\n\n }).catch(err => {\n throw new Error(`Unable to delegate rendering. Possibly the component is not loaded in the target window.\\n\\n${ stringifyError(err) }`);\n });\n\n getProxyContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyContainer(...args));\n renderContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.renderContainer(...args));\n showOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.show(...args));\n hideOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.hide(...args));\n watchForUnloadOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.watchForUnload(...args));\n\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n getProxyWindowOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyWindow(...args));\n openFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openFrame(...args));\n openPrerenderFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerenderFrame(...args));\n prerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.prerender(...args));\n openOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.open(...args));\n openPrerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerender(...args));\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n setProxyWinOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.setProxyWin(...args));\n }\n\n return childOverridesPromise;\n };\n\n const getDelegateOverrides = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n return {\n getProxyContainer, show, hide, renderContainer, getProxyWindow, watchForUnload,\n openFrame, openPrerenderFrame, prerender, open, openPrerender, setProxyWin\n };\n });\n };\n\n const checkAllowRender = (target : CrossDomainWindowType, domain : string | RegExp, container : string | HTMLElement) => {\n if (target === window) {\n return;\n }\n\n if (!isSameTopWindow(window, target)) {\n throw new Error(`Can only renderTo an adjacent frame`);\n }\n\n const origin = getDomain();\n\n if (!matchDomain(domain, origin) && !isSameDomain(target)) {\n throw new Error(`Can not render remotely to ${ domain.toString() } - can only render to ${ origin }`);\n }\n\n if (container && typeof container !== 'string') {\n throw new Error(`Container passed to renderTo must be a string selector, got ${ typeof container } }`);\n }\n };\n\n const init = () => {\n setupEvents();\n };\n\n const render = (target : CrossDomainWindowType, container : string | HTMLElement, context : $Values) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const uid = `${ ZOID }-${ tag }-${ uniqueID() }`;\n const domain = getDomainMatcher();\n const childDomain = getChildDomain();\n \n checkAllowRender(target, domain, container);\n\n const delegatePromise = ZalgoPromise.try(() => {\n if (target !== window) {\n return delegate(context, target);\n }\n });\n\n const windowProp = props.window;\n\n const watchForUnloadPromise = watchForUnload();\n \n const buildUrlPromise = buildUrl();\n const onRenderPromise = event.trigger(EVENT.RENDER);\n\n const getProxyContainerPromise = getProxyContainer(container);\n const getProxyWindowPromise = getProxyWindow();\n\n const buildWindowNamePromise = getProxyWindowPromise.then(proxyWin => {\n return buildWindowName({ proxyWin, childDomain, domain, target, context, uid });\n });\n\n const openFramePromise = buildWindowNamePromise.then(windowName => openFrame(context, { windowName }));\n const openPrerenderFramePromise = openPrerenderFrame(context);\n\n const renderContainerPromise = ZalgoPromise.hash({ proxyContainer: getProxyContainerPromise, proxyFrame: openFramePromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyContainer, proxyFrame, proxyPrerenderFrame }) => {\n return renderContainer(proxyContainer, { context, uid, proxyFrame, proxyPrerenderFrame });\n }).then(proxyContainer => {\n return proxyContainer;\n });\n\n const openPromise = ZalgoPromise.hash({ windowName: buildWindowNamePromise, proxyFrame: openFramePromise, proxyWin: getProxyWindowPromise }).then(({ windowName, proxyWin, proxyFrame }) => {\n return windowProp\n ? proxyWin\n : open(context, { windowName, proxyWin, proxyFrame });\n });\n\n const openPrerenderPromise = ZalgoPromise.hash({ proxyWin: openPromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyWin, proxyPrerenderFrame }) => {\n return openPrerender(context, proxyWin, proxyPrerenderFrame);\n });\n\n const setStatePromise = openPromise.then(proxyWin => {\n currentProxyWin = proxyWin;\n return setProxyWin(proxyWin);\n });\n \n const prerenderPromise = ZalgoPromise.hash({ proxyPrerenderWin: openPrerenderPromise, state: setStatePromise }).then(({ proxyPrerenderWin }) => {\n return prerender(proxyPrerenderWin, { context, uid });\n });\n\n const setWindowNamePromise = ZalgoPromise.hash({ proxyWin: openPromise, windowName: buildWindowNamePromise }).then(({ proxyWin, windowName }) => {\n if (windowProp) {\n return proxyWin.setName(windowName);\n }\n });\n\n const loadUrlPromise = ZalgoPromise.hash({ proxyWin: openPromise, builtUrl: buildUrlPromise, windowName: setWindowNamePromise, prerender: prerenderPromise }).then(({ proxyWin, builtUrl }) => {\n return proxyWin.setLocation(builtUrl);\n });\n\n const watchForClosePromise = openPromise.then(proxyWin => {\n watchForClose(proxyWin);\n });\n\n const onDisplayPromise = ZalgoPromise.hash({ container: renderContainerPromise, prerender: prerenderPromise }).then(() => {\n return event.trigger(EVENT.DISPLAY);\n });\n\n const openBridgePromise = openPromise.then(proxyWin => {\n return openBridge(proxyWin, childDomain, context);\n });\n\n const runTimeoutPromise = loadUrlPromise.then(() => {\n return runTimeout();\n });\n\n const onRenderedPromise = initPromise.then(() => {\n return event.trigger(EVENT.RENDERED);\n });\n\n return ZalgoPromise.hash({\n initPromise, buildUrlPromise, onRenderPromise, getProxyContainerPromise, openFramePromise, openPrerenderFramePromise, renderContainerPromise, openPromise,\n openPrerenderPromise, setStatePromise, prerenderPromise, loadUrlPromise, buildWindowNamePromise, setWindowNamePromise, watchForClosePromise, onDisplayPromise,\n openBridgePromise, runTimeoutPromise, onRenderedPromise, delegatePromise, watchForUnloadPromise\n });\n \n }).catch(err => {\n return ZalgoPromise.all([\n onError(err),\n destroy(err)\n ]).then(() => {\n throw err;\n }, () => {\n throw err;\n });\n }).then(noop);\n };\n\n return {\n init,\n render,\n destroy,\n setProps,\n getHelpers,\n getDelegateOverrides\n };\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindowClosed } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { windowStore } from './global';\n\nexport function cleanUpWindow(win : CrossDomainWindowType) {\n const requestPromises = windowStore('requestPromises');\n for (const promise of requestPromises.get(win, [])) {\n promise.reject(new Error(`Window ${ isWindowClosed(win) ? 'closed' : 'cleaned up' } before response`)).catch(noop);\n }\n}\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { destroyElement, toCSS } from 'belter/src';\n\nimport { type RenderOptionsType } from '../../parent/parent';\nimport { EVENT } from '../../constants';\n\nconst CLASS = {\n VISIBLE: 'zoid-visible',\n INVISIBLE: 'zoid-invisible'\n};\n\nexport function defaultContainerTemplate

({ uid, frame, prerenderFrame, doc, props, event, dimensions : { width, height } } : RenderOptionsType

) : ?HTMLElement {\n if (__ZOID__.__DEFAULT_CONTAINER__) {\n if (!frame || !prerenderFrame) {\n return;\n }\n\n const div = doc.createElement('div');\n div.setAttribute('id', uid);\n const style = doc.createElement('style');\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n style.appendChild(doc.createTextNode(`\n #${ uid } {\n display: inline-block;\n position: relative;\n width: ${ width };\n height: ${ height };\n }\n\n #${ uid } > 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 #${ uid } > iframe.${ CLASS.INVISIBLE } {\n opacity: 0;\n }\n\n #${ uid } > iframe.${ CLASS.VISIBLE } {\n opacity: 1;\n }\n `));\n\n div.appendChild(frame);\n div.appendChild(prerenderFrame);\n div.appendChild(style);\n\n prerenderFrame.classList.add(CLASS.VISIBLE);\n frame.classList.add(CLASS.INVISIBLE);\n \n event.on(EVENT.RENDERED, () => {\n prerenderFrame.classList.remove(CLASS.VISIBLE);\n prerenderFrame.classList.add(CLASS.INVISIBLE);\n \n frame.classList.remove(CLASS.INVISIBLE);\n frame.classList.add(CLASS.VISIBLE);\n \n setTimeout(() => {\n destroyElement(prerenderFrame);\n }, 1);\n });\n\n event.on(EVENT.RESIZE, ({ width: newWidth, height: newHeight }) => {\n if (typeof newWidth === 'number') {\n div.style.width = toCSS(newWidth);\n }\n \n if (typeof newHeight === 'number') {\n div.style.height = toCSS(newHeight);\n }\n });\n\n return div;\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { once, noop, type EventEmitterType } from 'belter/src';\nimport { isWindow, type CrossDomainWindowType, isWindowClosed, isSameDomain } from 'cross-domain-utils/src';\nimport { ProxyWindow, toProxyWindow } from 'post-robot/src';\n\nimport { PROP_SERIALIZATION } from '../constants';\n\nexport type EventHandlerType = (T) => void | ZalgoPromise;\n\nexport type timeoutPropType = number;\nexport type windowPropType = CrossDomainWindowType | ProxyWindow;\nexport type cspNoncePropType = string;\nexport type closePropType = () => ZalgoPromise;\nexport type focusPropType = () => ZalgoPromise;\nexport type showPropType = () => ZalgoPromise;\nexport type hidePropType = () => ZalgoPromise;\nexport type resizePropType = ({| width : ?number, height : ?number |}) => ZalgoPromise;\nexport type getParentPropType = () => CrossDomainWindowType;\nexport type getParentDomainPropType = () => string;\n\nexport type onDisplayPropType = EventHandlerType;\nexport type onRenderedPropType = EventHandlerType;\nexport type onRenderPropType = EventHandlerType;\nexport type onClosePropType = EventHandlerType;\nexport type onDestroyPropType = EventHandlerType;\nexport type onResizePropType = EventHandlerType;\nexport type onFocusPropType = EventHandlerType;\nexport type onErrorPropType = EventHandlerType;\nexport type onPropsPropType

= ((PropsType

) => void) => void; // eslint-disable-line no-use-before-define\n\n// eslint-disable-next-line flowtype/require-exact-type\nexport type PropsInputType

= {\n timeout? : timeoutPropType,\n window? : windowPropType,\n cspNonce? : cspNoncePropType,\n\n onDisplay? : onDisplayPropType,\n onRendered? : onRenderedPropType,\n onRender? : onRenderPropType,\n onClose? : onClosePropType,\n onDestroy? : onDestroyPropType,\n onResize? : onResizePropType,\n onFocus? : onFocusPropType,\n onError? : onErrorPropType,\n onProps? : onPropsPropType

\n} & P;\n\n// eslint-disable-next-line flowtype/require-exact-type\nexport type PropsType

= {\n timeout? : timeoutPropType,\n window? : ?windowPropType,\n close? : ?closePropType,\n focus? : ?focusPropType,\n resize? : ?resizePropType,\n cspNonce? : ?cspNoncePropType,\n\n onDisplay : onDisplayPropType,\n onRendered : onRenderedPropType,\n onRender : onRenderPropType,\n onClose : onClosePropType,\n onDestroy : onDestroyPropType,\n onResize : onResizePropType,\n onFocus : onFocusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

\n} & P;\n\ntype PropDefinitionType = {|\n type : S,\n alias? : string,\n value? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n event : EventEmitterType\n |}) => ?T,\n default? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n event : EventEmitterType\n |}) => ?T,\n decorate? : ({|\n value : T,\n props : PropsType

,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n event : EventEmitterType\n |}) => T,\n childDecorate? : ({|\n value : ?T,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n onProps : ((PropsType

) => void) => void,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n getParentDomain : () => string,\n getParent : () => CrossDomainWindowType,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise\n |}) => ?T,\n required? : boolean,\n queryParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n queryValue? : ({| value : T |}) => (ZalgoPromise | string),\n sendToChild? : boolean,\n allowDelegate? : boolean,\n validate? : ({| value : T, props : PropsInputType

|}) => void,\n sameDomain? : boolean,\n serialization? : $Values\n|};\n\nexport type BooleanPropDefinitionType = PropDefinitionType;\nexport type StringPropDefinitionType = PropDefinitionType;\nexport type NumberPropDefinitionType = PropDefinitionType;\nexport type FunctionPropDefinitionType = PropDefinitionType;\nexport type ArrayPropDefinitionType | $ReadOnlyArray<*>, P> = PropDefinitionType; // eslint-disable-line flowtype/no-mutable-array\nexport type ObjectPropDefinitionType = PropDefinitionType;\n\nexport type MixedPropDefinitionType

= BooleanPropDefinitionType<*, P> | StringPropDefinitionType<*, P> | NumberPropDefinitionType<*, P> | FunctionPropDefinitionType<*, P> | ObjectPropDefinitionType<*, P> | ArrayPropDefinitionType<*, P>;\n\nexport type UserPropsDefinitionType

= {\n [string] : MixedPropDefinitionType

\n};\n\nexport type BuiltInPropsDefinitionType

= {|\n timeout : NumberPropDefinitionType,\n window : ObjectPropDefinitionType,\n close : FunctionPropDefinitionType,\n focus : FunctionPropDefinitionType,\n resize : FunctionPropDefinitionType,\n cspNonce : StringPropDefinitionType,\n getParent : FunctionPropDefinitionType,\n getParentDomain : FunctionPropDefinitionType,\n hide : FunctionPropDefinitionType,\n show : FunctionPropDefinitionType,\n\n onDisplay : FunctionPropDefinitionType,\n onRendered : FunctionPropDefinitionType,\n onRender : FunctionPropDefinitionType,\n onClose : FunctionPropDefinitionType,\n onDestroy : FunctionPropDefinitionType,\n onResize : FunctionPropDefinitionType,\n onFocus : FunctionPropDefinitionType,\n onError : FunctionPropDefinitionType,\n onProps : FunctionPropDefinitionType, P>\n|};\n\nexport type PropsDefinitionType

= {|\n ...BuiltInPropsDefinitionType

,\n [ string ] : MixedPropDefinitionType

\n|};\n\nconst defaultNoop = () => noop;\nconst decorateOnce = ({ value }) => once(value);\n\nexport function getBuiltInProps

() : BuiltInPropsDefinitionType

{\n return {\n window: {\n type: 'object',\n sendToChild: false,\n required: false,\n allowDelegate: true,\n validate: ({ value }) => {\n if (!isWindow(value) && !ProxyWindow.isProxyWindow(value)) {\n throw new Error(`Expected Window or ProxyWindow`);\n }\n\n if (isWindow(value)) {\n // $FlowFixMe\n if (isWindowClosed(value)) {\n throw new Error(`Window is closed`);\n }\n\n // $FlowFixMe\n if (!isSameDomain(value)) {\n throw new Error(`Window is not same domain`);\n }\n }\n },\n decorate: ({ value }) => {\n return toProxyWindow(value);\n }\n },\n\n timeout: {\n type: 'number',\n required: false,\n sendToChild: false\n },\n\n close: {\n type: 'function',\n required: false,\n sendToChild: false,\n childDecorate: ({ close }) => close\n },\n\n focus: {\n type: 'function',\n required: false,\n sendToChild: false,\n childDecorate: ({ focus }) => focus\n },\n\n resize: {\n type: 'function',\n required: false,\n sendToChild: false,\n childDecorate: ({ resize }) => resize\n },\n\n cspNonce: {\n type: 'string',\n required: false\n },\n\n getParent: {\n type: 'function',\n required: false,\n sendToChild: false,\n childDecorate: ({ getParent }) => getParent\n },\n\n getParentDomain: {\n type: 'function',\n required: false,\n sendToChild: false,\n childDecorate: ({ getParentDomain }) => getParentDomain\n },\n\n show: {\n type: 'function',\n required: false,\n sendToChild: false,\n childDecorate: ({ show }) => show\n },\n\n hide: {\n type: 'function',\n required: false,\n sendToChild: false,\n childDecorate: ({ hide }) => hide\n },\n\n onDisplay: {\n type: 'function',\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRendered: {\n type: 'function',\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRender: {\n type: 'function',\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onClose: {\n type: 'function',\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onDestroy: {\n type: 'function',\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onResize: {\n type: 'function',\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n onFocus: {\n type: 'function',\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n onError: {\n type: 'function',\n required: false,\n sendToChild: false,\n childDecorate: ({ onError }) => onError\n },\n\n onProps: {\n type: 'function',\n required: false,\n sendToChild: false,\n default: defaultNoop,\n childDecorate: ({ onProps }) => onProps\n }\n };\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { setup as setupPostRobot, on, send, bridge, toProxyWindow, destroy as destroyPostRobot } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindow, getDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, isElement, cleanup, memoize, identity } from 'belter/src';\n\nimport { getChildPayload, childComponent, type ChildComponent } from '../child';\nimport { type RenderOptionsType, type ParentHelpers, parentComponent } from '../parent/parent';\nimport { CONTEXT, POST_MESSAGE, WILDCARD, DEFAULT_DIMENSIONS } from '../constants';\nimport { react, angular, vue, angular2 } from '../drivers';\nimport { getGlobal, destroyGlobal } from '../lib';\nimport type { CssDimensionsType, StringMatcherType } from '../types';\n\nimport { validateOptions } from './validate';\nimport { defaultContainerTemplate, defaultPrerenderTemplate } from './templates';\nimport { getBuiltInProps, type UserPropsDefinitionType, type PropsDefinitionType, type PropsInputType, type PropsType } from './props';\n\ntype LoggerPayload = { [string] : ?string | ?boolean };\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype Logger = {\n info : (event : string, payload? : LoggerPayload) => any // eslint-disable-line flowtype/no-weak-types\n};\n\n/* Component\n ---------\n\n This is the spec for the component. The idea is, when I call zoid.create(), it will create a new instance\n of Component with the blueprint needed to set up ParentComponents and ChildComponents.\n\n This is the one portion of code which is required by -- and shared to -- both the parent and child windows, and\n contains all of the configuration needed for them to set themselves up.\n*/\n\nexport type ComponentOptionsType

= {|\n\n tag : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain? : string | RegExp,\n bridgeUrl? : string,\n\n props? : UserPropsDefinitionType

,\n\n dimensions? : CssDimensionsType,\n autoResize? : {| width? : boolean, height? : boolean, element? : string |},\n\n allowedParentDomains? : StringMatcherType,\n\n attributes? : {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n |},\n\n eligible? : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext? : $Values,\n\n containerTemplate? : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate? : (RenderOptionsType

) => ?HTMLElement,\n\n validate? : ({| props : PropsInputType

|}) => void,\n\n logger? : Logger\n|};\n\nexport type AttributesType = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\ntype AutoResizeType = {|\n width? : boolean,\n height? : boolean,\n element? : string\n|};\n\nexport type NormalizedComponentOptionsType

= {|\n tag : string,\n name : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain : ?(string | RegExp),\n bridgeUrl : ?string,\n\n propsDef : PropsDefinitionType

,\n dimensions : CssDimensionsType,\n autoResize : AutoResizeType,\n\n allowedParentDomains : StringMatcherType,\n\n attributes : AttributesType | ({| props : PropsType

|}) => AttributesType,\n\n eligible : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext : $Values,\n\n containerTemplate : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate : ?(RenderOptionsType

) => ?HTMLElement,\n\n validate : ?({| props : PropsInputType

|}) => void,\n logger : Logger\n|};\n\nexport type ZoidComponentInstance

= {|\n ...ParentHelpers

,\n isEligible : () => boolean,\n clone : () => ZoidComponentInstance

,\n render : (container? : string | HTMLElement, context? : $Values) => ZalgoPromise,\n renderTo : (target : CrossDomainWindowType, container? : string, context? : $Values) => ZalgoPromise\n|};\n\n// eslint-disable-next-line flowtype/require-exact-type\nexport type ZoidComponent

= {\n (PropsInputType

) : ZoidComponentInstance

,\n driver : (string, mixed) => mixed,\n isChild : () => boolean,\n xprops? : PropsType

,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise\n};\n\nconst getDefaultAttributes = () : AttributesType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultAutoResize = () : AutoResizeType => {\n // $FlowFixMe\n return {};\n};\n\nfunction normalizeOptions

(options : ComponentOptionsType

) : NormalizedComponentOptionsType

{\n let {\n tag,\n url,\n domain,\n bridgeUrl,\n props: propsDef = {},\n dimensions = {},\n autoResize = getDefaultAutoResize(),\n allowedParentDomains = WILDCARD,\n attributes = getDefaultAttributes(),\n defaultContext = CONTEXT.IFRAME,\n containerTemplate = (__ZOID__.__DEFAULT_CONTAINER__ ? defaultContainerTemplate : null),\n prerenderTemplate = (__ZOID__.__DEFAULT_PRERENDER__ ? defaultPrerenderTemplate : null),\n validate,\n eligible = () => ({ eligible: true }),\n logger = { info: noop }\n } = options;\n\n const name = tag.replace(/-/g, '_');\n const { width = DEFAULT_DIMENSIONS.WIDTH, height = DEFAULT_DIMENSIONS.HEIGHT } = dimensions;\n\n // $FlowFixMe\n propsDef = { ...getBuiltInProps(), ...propsDef };\n\n if (!containerTemplate) {\n throw new Error(`Container template required`);\n }\n\n return {\n name,\n tag,\n url,\n domain,\n bridgeUrl,\n propsDef,\n dimensions: { width, height },\n autoResize,\n allowedParentDomains,\n attributes,\n defaultContext,\n containerTemplate,\n prerenderTemplate,\n validate,\n logger,\n eligible\n };\n}\n\nlet clean = cleanup();\n\nexport type Component

= {|\n init : (PropsInputType

) => ZoidComponentInstance

,\n instances : $ReadOnlyArray>,\n driver : (string, mixed) => mixed,\n isChild : () => boolean,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n registerChild : () => ?ChildComponent

\n|};\n\nexport function component

(opts : ComponentOptionsType

) : Component

{\n if (__DEBUG__) {\n validateOptions(opts);\n }\n\n const options = normalizeOptions(opts);\n\n const {\n name,\n tag,\n defaultContext,\n propsDef,\n eligible\n } = options;\n\n const global = getGlobal();\n const driverCache = {};\n const instances = [];\n\n const isChild = () : boolean => {\n const payload = getChildPayload();\n return Boolean(payload && payload.tag === tag && payload.childDomain === getDomain());\n };\n\n const registerChild = memoize(() : ?ChildComponent

=> {\n if (isChild()) {\n if (window.xprops) {\n delete global.components[tag];\n throw new Error(`Can not register ${ name } as child - child already registered`);\n }\n\n const child = childComponent(options);\n child.init();\n return child;\n }\n });\n\n const listenForDelegate = () => {\n on(`${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`, () => {\n return true;\n });\n\n on(`${ POST_MESSAGE.DELEGATE }_${ name }`, ({ source, data: { overrides } }) => {\n return {\n parent: parentComponent(options, overrides, source)\n };\n });\n };\n\n const canRenderTo = (win : CrossDomainWindowType) : ZalgoPromise => {\n return send(win, `${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`).then(({ data }) => {\n return data;\n }).catch(() => {\n return false;\n });\n };\n\n const getDefaultContainer = (context : $Values, container? : string | HTMLElement) : string | HTMLElement => {\n if (container) {\n if (typeof container !== 'string' && !isElement(container)) {\n throw new TypeError(`Expected string or element selector to be passed`);\n }\n\n return container;\n }\n\n if (context === CONTEXT.POPUP) {\n return 'body';\n }\n\n throw new Error(`Expected element to be passed to render iframe`);\n };\n\n const getDefaultContext = (props : PropsInputType

, context : ?$Values) : ZalgoPromise<$Values> => {\n return ZalgoPromise.try(() => {\n if (props.window) {\n return toProxyWindow(props.window).getType();\n }\n\n if (context) {\n if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) {\n throw new Error(`Unrecognized context: ${ context }`);\n }\n\n return context;\n }\n\n return defaultContext;\n });\n };\n\n const getDefaultInputProps = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const init = (props : PropsInputType

) : ZoidComponentInstance

=> {\n // eslint-disable-next-line prefer-const\n let instance;\n props = props || getDefaultInputProps();\n\n const { eligible: eligibility, reason } = eligible({ props });\n const isEligible = () => eligibility;\n\n const onDestroy = props.onDestroy;\n props.onDestroy = (...args) => {\n if (instance && eligibility) {\n instances.splice(instances.indexOf(instance), 1);\n }\n\n if (onDestroy) {\n return onDestroy(...args);\n }\n };\n\n const parent = parentComponent(options);\n parent.init();\n\n if (eligibility) {\n parent.setProps(props);\n } else {\n if (props.onDestroy) {\n props.onDestroy();\n }\n }\n\n clean.register(() => {\n parent.destroy(new Error(`zoid destroyed all components`));\n });\n\n const render = (target, container, context) => {\n return ZalgoPromise.try(() => {\n if (!eligibility) {\n return parent.destroy().then(() => {\n throw new Error(reason || `${ name } component is not eligible`);\n });\n }\n\n if (!isWindow(target)) {\n throw new Error(`Must pass window to renderTo`);\n }\n\n return getDefaultContext(props, context);\n\n }).then(finalContext => {\n container = getDefaultContainer(finalContext, container);\n return parent.render(target, container, finalContext);\n\n }).catch(err => {\n return parent.destroy(err).then(() => {\n throw err;\n });\n });\n };\n\n const clone = ({ decorate = identity } = {}) => {\n return init(decorate(props));\n };\n\n instance = {\n ...parent.getHelpers(),\n isEligible,\n clone,\n render: (container, context) => render(window, container, context),\n renderTo: (target, container, context) => render(target, container, context)\n };\n\n if (eligibility) {\n instances.push(instance);\n }\n\n return instance;\n };\n\n const driver = (driverName : string, dep : mixed) : mixed => {\n if (__ZOID__.__FRAMEWORK_SUPPORT__) {\n const drivers = { react, angular, vue, angular2 };\n\n if (!drivers[driverName]) {\n throw new Error(`Could not find driver for framework: ${ driverName }`);\n }\n\n if (!driverCache[driverName]) {\n driverCache[driverName] = drivers[driverName].register(tag, propsDef, init, dep);\n }\n\n return driverCache[driverName];\n } else {\n throw new Error(`Driver support not enabled`);\n }\n };\n\n registerChild();\n listenForDelegate();\n\n global.components = global.components || {};\n if (global.components[tag]) {\n throw new Error(`Can not register multiple components with the same tag: ${ tag }`);\n }\n global.components[tag] = true;\n\n return {\n init,\n instances,\n driver,\n isChild,\n canRenderTo,\n registerChild\n };\n}\n\nexport type ComponentDriverType = {|\n register : (string, PropsDefinitionType

, (PropsInputType

) => ZoidComponentInstance

, L) => D\n|};\n\nexport function create

(options : ComponentOptionsType

) : ZoidComponent

{\n setupPostRobot();\n\n const comp = component(options);\n\n const init = (props) => comp.init(props);\n init.driver = (name, dep) => comp.driver(name, dep);\n init.isChild = () => comp.isChild();\n init.canRenderTo = (win) => comp.canRenderTo(win);\n init.instances = comp.instances;\n\n const child = comp.registerChild();\n if (child) {\n window.xprops = init.xprops = child.getProps();\n }\n\n return init;\n}\n\nexport function destroyAll() : ZalgoPromise {\n if (bridge) {\n bridge.destroyBridges();\n }\n\n const destroyPromise = clean.all();\n clean = cleanup();\n return destroyPromise;\n}\n\nexport const destroyComponents = destroyAll;\n\nexport function destroy() {\n destroyAll();\n destroyGlobal();\n destroyPostRobot();\n}\n"],"sourceRoot":""}