-
Notifications
You must be signed in to change notification settings - Fork 0
/
zoid.min.js.map
1 lines (1 loc) · 493 KB
/
zoid.min.js.map
1
{"version":3,"sources":["webpack://zoid/webpack/universalModuleDefinition","webpack://zoid/webpack/bootstrap","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","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/@babel/runtime/helpers/esm/getPrototypeOf.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/construct.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/isNativeFunction.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.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/belter/src/constants.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/serializers/undefined.js","webpack://zoid/./node_modules/universal-serialize/src/deserialize.js","webpack://zoid/./node_modules/post-robot/src/bridge/common.js","webpack://zoid/./node_modules/post-robot/src/bridge/parent.js","webpack://zoid/./node_modules/post-robot/src/bridge/setup.js","webpack://zoid/./node_modules/post-robot/src/bridge/bridge.js","webpack://zoid/./node_modules/post-robot/src/bridge/child.js","webpack://zoid/./node_modules/post-robot/src/serialize/window.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/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/lib/compat.js","webpack://zoid/./node_modules/post-robot/src/public/send.js","webpack://zoid/./node_modules/post-robot/src/index.js","webpack://zoid/./node_modules/post-robot/src/conf/config.js","webpack://zoid/./node_modules/post-robot/src/setup.js","webpack://zoid/./node_modules/post-robot/src/clean.js","webpack://zoid/./node_modules/@krakenjs/cross-domain-utils/src/util.js","webpack://zoid/./node_modules/@krakenjs/cross-domain-utils/src/utils.js","webpack://zoid/./node_modules/@krakenjs/cross-domain-utils/src/constants.js","webpack://zoid/./src/lib/global.js","webpack://zoid/./src/lib/serialize.js","webpack://zoid/./src/constants.js","webpack://zoid/./src/lib/window.js","webpack://zoid/./src/child/props.js","webpack://zoid/./src/child/child.js","webpack://zoid/./src/component/props.js","webpack://zoid/./src/parent/props.js","webpack://zoid/./src/parent/parent.js","webpack://zoid/./src/component/templates/container.js","webpack://zoid/./src/component/templates/component.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","_setPrototypeOf","setPrototypeOf","__proto__","_inheritsLoose","subClass","superClass","prototype","constructor","_extends","assign","target","arguments","length","source","apply","isPromise","item","Promise","window","Window","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","promiseResult","catch","undefined","finally","onFinally","try","timeout","time","clearTimeout","toPromise","TypeError","lazy","all","promises","count","results","slice","prom","hash","awaitPromises","map","items","method","onPossiblyUnhandledException","cancel","splice","context","args","delay","flush","isRegex","IE_WIN_ACCESS_ERROR","getActualProtocol","win","location","protocol","getProtocol","mockDomain","split","isAboutProtocol","getParent","parent","getOpener","opener","canReadFromWindow","getActualDomain","PROTOCOL","host","getDomain","domain","isSameDomain","desc","getOwnPropertyDescriptor","isMockProtocol","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","getUserAgent","navigator","mockUserAgent","userAgent","getFrameByName","winFrames","childFrame","isOpener","getAncestor","anyMatch","collection1","collection2","item1","isSameTopWindow","win1","win2","top1","top2","allFrames1","allFrames2","opener1","opener2","matchDomain","pattern","origin","Array","isArray","Boolean","match","JSON","stringify","some","subpattern","getDomainFromUrl","url","join","isWindow","obj","__cross_domain_utils_window_check__","getFrameForWindow","frameElement","document","querySelectorAll","closeWindow","isIframe","parentElement","removeChild","close","objectIDs","CrossDomainSafeWeakMap","weakmap","keys","values","Math","random","WeakMap","freeze","testWeakMap","testKey","set","hasNativeWeakMap","_cleanupClosedWindows","delete","isSafeToReadWrite","entry","writable","index","has","getOrSet","_getPrototypeOf","getPrototypeOf","_isNativeReflectConstruct","Reflect","construct","sham","Proxy","Date","e","_construct","Parent","Class","isNativeReflectConstruct","a","instance","Function","_wrapNativeSuper","_cache","Map","Wrapper","configurable","isElement","element","passed","Element","nodeType","style","_","getFunctionName","fn","__name__","displayName","setFunctionName","base64encode","str","btoa","encodeURIComponent","replace","p1","String","fromCharCode","parseInt","Buffer","from","uniqueID","chars","charAt","floor","toISOString","toLowerCase","serializeArgs","subkey","val","uid","getObjectID","getEmptyObject","memoizeGlobalIndex","memoizeGlobalIndexValidFrom","memoize","options","simpleCache","thisCache","thisNamespace","cacheTime","memoizeIndex","memoizedFunction","cache","cacheKey","cacheResult","now","reset","memoizePromise","memoizedPromiseFunction","noop","once","called","stringifyError","level","newErr","extend","identity","safeInterval","loop","arrayFrom","isDefined","cleanup","cleanErr","tasks","cleaned","cleaner","register","task","shift","assertExists","thing","clear","ExtendableError","captureStackTrace","ReferenceError","getBody","body","isDocumentReady","readyState","isDocumentInteractive","urlEncode","parseQuery","queryString","logic","__inline_memoize_cache__","params","pair","decodeURIComponent","inlineMemoize","extendQuery","originalQuery","props","filter","appendChild","container","getElementSafe","id","querySelector","elementReady","el","interval","setInterval","clearInterval","awaitFrameLoadPromises","PopupOpenError","awaitFrameLoad","addEventListener","cleanIframes","linkFrameWindow","awaitFrameWindow","loadedFrame","iframe","tag","styleText","createElement","class","className","setAttribute","attributes","styleSheet","cssText","createTextNode","html","innerHTML","allowTransparency","backgroundColor","border","isIE","hasAttribute","getElement","event","removeEventListener","showElement","setProperty","hideElement","destroyElement","isElementClosed","onResize","width","height","currentWidth","offsetWidth","currentHeight","offsetHeight","canceled","observer","check","getClientRects","isElementVisible","newWidth","newHeight","ResizeObserver","observe","MutationObserver","childList","subtree","characterData","disconnect","isShadowElement","currentScript","getCurrentScript","getStackTrace","stackDetails","exec","scriptLocation","getElementsByTagName","reverse","script","src","inferCurrentScript","currentUID","isPerc","test","toNum","toPx","toCSS","normalizeDimension","dim","max","getGlobal","globalKey","__POST_ROBOT__","getAttribute","ATTRIBUTES","hashedString","total","charCodeAt","abs","strHashStr","dataset","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","awaitWindowHello","getHelloPromise","markWindowKnown","isSerializedType","__type__","determineType","serializeType","type","__val__","SERIALIZER","code","toJSON","defaultSerializers","DESERIALIZER","RegExp","defaultDeserializers","needsBridgeForBrowser","needsBridgeForWin","needsBridgeForDomain","needsBridge","getBridgeName","BRIDGE_NAME_PREFIX","isBridge","documentBodyReady","registerRemoteWindow","findRemoteWindow","remoteWinPromise","registerRemoteSendMessage","sendMessage","remoteWin","remoteDomain","fireAndForget","rejectRemoteSendMessage","linkWindow","popupWindowsByName","popupWindowsByWin","winName","details","setupBridge","windowOpen","on","receiveMessage","open","last","normalizeMockUrl","bridgePromise","bridge","getWindowDetails","listenForOpenTunnel","openTunnelToParent","canary","tunnelWindows","parentWindow","cleanTunnelWindows","addTunnelWindow","tunnelWindow","setupOpenTunnelToParent","openTunnelToOpener","cleanupProxyWindows","idToProxyWindow","shouldClean","getSerializedWindow","winPromise","windowNamePromise","windowTypePromise","getName","getType","focus","isClosed","setLocation","href","opts","form","display","input","submit","submitForm","setName","sameDomain","ProxyWindow","serializedWindow","isProxyWindow","actualWindow","actualWindowPromise","getID","setWindow","isPopup","isPopupPromise","getNamePromise","reopenPromise","focusPromise","getWindow","awaitWindow","matchWindow","proxyInstanceID","knownWindowInstanceID","unwrap","serialize","toProxyWindow","deserialize","addMethod","methodStore","proxyWindowMethods","lookupMethod","serializeFunction","destination","meth","methodSource","arg","__id__","serializeMessage","serializers","serializer","serializePromise","deserializeMessage","deserializers","parse","deserializer","serializedPromise","deserializePromise","serializedFunction","getDeserializedFunction","crossDomainFunctionWrapper","__origin__","__source__","deserializeFunction","SEND_MESSAGE_STRATEGIES","domainBuffer","buffer","serializedMessage","strategies","errors","strategyName","getResponseListener","deleteResponseListener","isResponseListenerErrored","getRequestListener","requestListeners","winQualifier","nameListeners","domainListeners","listener","regex","handleRequest","logName","sendResponse","ack","pathname","handleError","handleAck","handleResponse","receivedMessages","messages","parsedMessage","parseMessages","deserializeMessages","requestListener","addRequestListener","winCandidate","requestListenerPromise","actualWin","listenersCollection","existingListener","strDomain","winNameDomainRegexListeners","winNameDomainRegexListener","winNameListeners","winNameDomainListeners","errorHandler","postMessage","messagingChild","messagingParent","sendBridgeMessage","foreignGlobal","winOrProxyWin","domainMatcher","responseTimeout","childTimeout","validateOptions","actualParent","isAncestor","targetDomain","actualDomain","normalizedDomain","normalizeDomain","responseListener","addResponseListener","reqPromises","markResponseListenerErrored","totalAckTimeout","isWindowKnown","totalResTimeout","ackTimeout","resTimeout","cancelled","cleanUpWindow","openBridge","bridges","bridgeFrames","openBridgeFrame","linkUrl","hasBridge","destroyBridges","getDistanceFromTop","distance","onCloseWindow","callback","maxtime","Infinity","tryGlobal","getProxyObject","basicSerialize","getUIDRefStore","references","crossDomainSerialize","metaData","sender","receiver","passByReference","basic","proxyWin","internalSerializeMessage","reference","getRawRef","serializedData","cleanReference","ref","crossDomainDeserialize","atob","base64decode","basicDeserialize","getRefValue","internalDeserializeMessage","PROP_TYPE","STRING","OBJECT","FUNCTION","BOOLEAN","NUMBER","ARRAY","PROP_SERIALIZATION","DOTIFY","BASE64","CONTEXT","IFRAME","POPUP","EVENT","RENDER","RENDERED","DISPLAY","ERROR","CLOSE","DESTROY","PROPS","RESIZE","FOCUS","buildChildWindowName","serializedPayload","parseWindowName","windowName","zoidcomp","serializedInitialPayload","parseInitialParentPayload","windowRef","getNthParent","ancestor","windows","findChildFrameByName","namedFrame","findFrameByName","getWindowByRef","payload","getInitialParentPayload","getWindowRef","targetWindow","currentWindow","normalizeChildProp","propsDef","helpers","prop","childDecorate","onProps","resize","getParentDomain","show","hide","export","getSiblings","destroy","defaultNoop","decorateOnce","eachProp","serializeProps","propDef","getParam","queryParam","bodyParam","getValue","queryValue","bodyValue","finalParam","finalValue","serialization","dotify","prefix","newobj","every","dotkey","mapProps","parentComponent","triggered","emitter","currentProxyWin","currentProxyContainer","childComponent","currentChildDomain","currentContainer","overrides","parentWin","containerTemplate","prerenderTemplate","dimensions","autoResize","domainMatch","xports","initPromise","handledErrors","clean","state","inputProps","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","getDimensions","resolveInitPromise","rejectInitPromise","getPropsForChild","initialChildDomain","sendToChild","newInternalState","windowProp","setState","getUrl","getAttributes","getInitialChildDomain","title","proxyPrerenderFrame","prerenderFrame","prerenderFrameWindow","actualComponentWindow","initChild","childDomain","childExports","proxyFrame","outerWidth","closeOnUnload","left","round","screenX","screen","outerHeight","screenY","status","toolbar","menubar","resizable","scrollbars","popup","unloadWindowListener","closeParentWindowListener","checkWindowClose","secondIsClosed","exportsPromise","xport","actualExports","renderTemplate","renderer","proxyPrerenderWin","prerenderWindow","isBlankDomain","tagName","children","writeElementToWindow","prerenderResizeListener","proxyContainer","rerender","innerContainer","containerWatcher","sacrificialFrame","sacrificialFrameWin","mutationObservers","elementClosed","mutationElement","mutationObserver","frameWin","watchElementForClose","removeError","getHelpers","updateProps","setProps","newInputProps","existingProps","valueDetermined","alias","default","required","decorate","getDerivedValue","extendProps","newProps","childProps","containerElement","insertShadowSlot","shadowHost","shadowRoot","getShadowRoot","getShadowHost","slotName","slot","slotProvider","init","onRender","onDisplay","onRendered","onClose","onDestroy","onFocus","render","childDomainMatch","checkAllowRender","delegatePromise","delegateProps","propName","allowDelegate","childOverridesPromise","POST_MESSAGE","parentComp","getDelegateOverrides","childOverrides","delegate","watchForUnloadPromise","buildBodyPromise","onRenderPromise","getProxyContainerPromise","getProxyWindowPromise","finalSetPropsPromise","buildUrlPromise","query","originalUrl","originalHash","hashString","extendUrl","buildWindowNamePromise","version","__ZOID__","checkClose","buildInitialChildPayload","childPayload","buildSerializedChildPayload","openFramePromise","openPrerenderFramePromise","renderContainerPromise","openPromise","openPrerenderPromise","setStatePromise","prerenderPromise","setWindowNamePromise","getMethodPromise","loadUrlPromise","windowUrl","watchForClosePromise","watchForClose","onDisplayPromise","openBridgePromise","bridgeUrl","bridgeDomain","runTimeoutPromise","onRenderedPromise","getProps","getExports","defaultContainerTemplate","div","cspNonce","classList","add","remove","defaultPrerenderTemplate","spinner","cleanInstances","cleanZoid","component","allowDelegateListener","delegateListener","allowedParentDomains","defaultContext","validate","eligible","logger","info","xportsDefinition","valuePromise","normalizeOptions","instances","isChild","isChildComponentWindow","registerChild","xprops","components","onPropHandlers","parentComponentWindow","parentDomain","parentExports","initialProps","parentExport","parentResize","parentInit","anyParent","currentParent","winParent","isUpdate","normalizedProps","normalizeChildProps","componentName","updateChildWindowNameWithRef","checkParentDomain","ZOID","eligibility","reason","clone","getDefaultContext","finalContext","getDefaultContainer","newInstance","renderTo","childComponents","childName","Child","childInputProps","parentProps","getChildren","isEligible","driver","driverName","dep","canRenderTo","initialized","sourceElement","originalEvent","messageListener","listenForMessages","initHello","comp","destroyComponents","destroyPromise","destroyAll","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,C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1B0d,IACAA,GAAO4J,iBAGX,IAAM6X,EAAiBjE,GAAel4B,IAAIhD,GAE1C,OADAk7B,GAAiB/pB,KACVguB,EAGJ,IAAMC,GAAaF,GAEnB,SAAStS,GAAQ5sB,GAIpB,OAHAo/B,YXriBOx/B,OAAM,gBbWV,WAAmC,IACtC,IAAMy/B,EAAoBhmB,GAAY,qBADA,MAEnBgmB,EAAkBz0B,OAFC,eAEO,CAAxC,IAAMtH,EAAI,KACLmgB,EAAW4b,EAAkB7hC,IAAI8F,GACnCmgB,IACAA,EAASqD,WAAY,GAEzBuY,EAAkB3lB,IAAIpW,IQZ1Bg8B,INoHM7b,EAAWpK,KAAc7b,IAAI,yBAE/BimB,EAAS7f,gBlCvINhE,OAAM,uBwDmjBNu7B,GAAUn4B,IAAIhD,GhBniBlB,INqHGyjB","file":"zoid.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 _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\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 const toString = ({}).toString;\n\n if (toString) {\n const 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<mixed>) => void> = [];\n\nexport function dispatchPossiblyUnhandledError<T>(err : mixed, promise : ZalgoPromise<T>) {\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<mixed>) => 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<*>>) : ZalgoPromise<void> { // eslint-disable-line no-undef\n const promise = flushPromise = flushPromise || new Zalgo();\n flushActive();\n return promise;\n}\n","/* @flow */\n\nimport { isPromise } from './utils';\nimport { onPossiblyUnhandledException, dispatchPossiblyUnhandledError } from './exceptions';\nimport { startActive, endActive, awaitActive } from './flush';\n\nexport class ZalgoPromise<R : mixed> {\n\n resolved : boolean\n rejected : boolean\n errorHandled : boolean\n value : R\n error : mixed\n // eslint-disable-next-line flowtype/no-mutable-array\n handlers : Array<{|\n promise : ZalgoPromise<*>,\n onSuccess : void | (result : R) => mixed,\n onError : void | (error : mixed) => mixed\n |}>\n dispatching : boolean\n stack : string\n\n constructor(handler : ?(resolve : (result : R) => void, reject : (error : mixed) => void) => void) {\n\n this.resolved = false;\n this.rejected = false;\n this.errorHandled = false;\n\n this.handlers = [];\n\n if (handler) {\n\n let result;\n let error;\n let resolved = false;\n let rejected = false;\n let isAsync = false;\n\n startActive();\n\n try {\n handler(res => {\n if (isAsync) {\n this.resolve(res);\n } else {\n resolved = true;\n result = res;\n }\n\n }, err => {\n if (isAsync) {\n this.reject(err);\n } else {\n rejected = true;\n error = err;\n }\n });\n\n } catch (err) {\n endActive();\n this.reject(err);\n return;\n }\n\n endActive();\n\n isAsync = true;\n\n if (resolved) {\n // $FlowFixMe\n this.resolve(result);\n } else if (rejected) {\n this.reject(error);\n }\n }\n\n if (__DEBUG__) {\n try {\n throw new Error(`ZalgoPromise`);\n } catch (err) {\n this.stack = err.stack;\n }\n }\n }\n\n resolve(result : R) : ZalgoPromise<R> {\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<R> {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(error)) {\n throw new Error('Can not reject promise with another promise');\n }\n\n if (!error) {\n // $FlowFixMe\n const err = (error && typeof error.toString === 'function' ? error.toString() : Object.prototype.toString.call(error));\n error = new Error(`Expected reject to be called with Error, got ${ err }`);\n }\n\n this.rejected = true;\n this.error = error;\n\n if (!this.errorHandled) {\n setTimeout(() => {\n if (!this.errorHandled) {\n dispatchPossiblyUnhandledError(error, this);\n }\n }, 1);\n }\n\n this.dispatch();\n\n return this;\n }\n\n asyncReject(error : mixed) : ZalgoPromise<R> {\n this.errorHandled = true;\n this.reject(error);\n return this;\n }\n \n dispatch() {\n\n const { dispatching, resolved, rejected, handlers } = this;\n\n if (dispatching) {\n return;\n }\n\n if (!resolved && !rejected) {\n return;\n }\n\n this.dispatching = true;\n startActive();\n\n const chain = <T>(firstPromise : ZalgoPromise<T>, secondPromise : ZalgoPromise<T>) => {\n return firstPromise.then(res => {\n secondPromise.resolve(res);\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < handlers.length; i++) {\n\n const { onSuccess, onError, promise } = handlers[i];\n\n let result;\n\n if (resolved) {\n\n try {\n result = onSuccess ? onSuccess(this.value) : this.value;\n } catch (err) {\n promise.reject(err);\n continue;\n }\n\n } else if (rejected) {\n\n if (!onError) {\n promise.reject(this.error);\n continue;\n }\n\n try {\n result = onError(this.error);\n } catch (err) {\n promise.reject(err);\n continue;\n }\n }\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n const promiseResult : ZalgoPromise<*> = result;\n\n if (promiseResult.resolved) {\n promise.resolve(promiseResult.value);\n } else {\n promise.reject(promiseResult.error);\n }\n\n promiseResult.errorHandled = true;\n\n } else if (isPromise(result)) {\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n if (result.resolved) {\n promise.resolve(result.value);\n } else {\n promise.reject(result.error);\n }\n\n } else {\n // $FlowFixMe\n chain(result, promise);\n }\n\n } else {\n\n promise.resolve(result);\n }\n }\n\n handlers.length = 0;\n this.dispatching = false;\n endActive();\n }\n\n then<X, Y>(onSuccess : void | (result : R) => (ZalgoPromise<X> | Y), onError : void | (error : mixed) => (ZalgoPromise<X> | Y)) : ZalgoPromise<X | Y> {\n\n if (onSuccess && typeof onSuccess !== 'function' && !onSuccess.call) {\n throw new Error('Promise.then expected a function for success handler');\n }\n\n if (onError && typeof onError !== 'function' && !onError.call) {\n throw new Error('Promise.then expected a function for error handler');\n }\n\n const promise = new ZalgoPromise();\n\n this.handlers.push({\n promise,\n onSuccess,\n onError\n });\n\n this.errorHandled = true;\n\n this.dispatch();\n\n return promise;\n }\n\n catch<X, Y>(onError : (error : mixed) => ZalgoPromise<X> | Y) : ZalgoPromise<X | Y> {\n // $FlowFixMe incompatible-call\n const resultPromise : ZalgoPromise<X | Y> = this.then(undefined, onError);\n return resultPromise;\n }\n\n finally(onFinally : () => mixed) : ZalgoPromise<R> {\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<R> {\n\n if (this.resolved || this.rejected) {\n return this;\n }\n\n const timeout = setTimeout(() => {\n\n if (this.resolved || this.rejected) {\n return;\n }\n\n this.reject(err || new Error(`Promise timed out after ${ time }ms`));\n\n }, time);\n\n return this.then(result => {\n clearTimeout(timeout);\n return result;\n });\n }\n\n // $FlowFixMe\n toPromise() : Promise<R> {\n // $FlowFixMe\n if (typeof Promise === 'undefined') {\n throw new TypeError(`Could not find Promise`);\n }\n // $FlowFixMe\n return Promise.resolve(this); // eslint-disable-line compat/compat\n }\n\n lazy() : ZalgoPromise<R> {\n this.errorHandled = true;\n return this;\n }\n\n static resolve<X, Y>(value : ZalgoPromise<X> | Y) : ZalgoPromise<X | Y> {\n\n if (value instanceof ZalgoPromise) {\n // $FlowFixMe incompatible-type-arg\n const result : ZalgoPromise<X | Y> = value;\n return result;\n }\n\n if (isPromise(value)) {\n // $FlowFixMe\n return new ZalgoPromise((resolve, reject) => value.then(resolve, reject));\n }\n\n return new ZalgoPromise().resolve(value);\n }\n\n static reject(error : mixed) : ZalgoPromise<R> {\n return new ZalgoPromise().reject(error);\n }\n\n static asyncReject(error : mixed) : ZalgoPromise<R> {\n return new ZalgoPromise().asyncReject(error);\n }\n\n static all<X : $ReadOnlyArray<mixed>>(promises : X) : ZalgoPromise<$TupleMap<X, <Y>(ZalgoPromise<Y> | Y) => Y>> { // eslint-disable-line no-undef\n\n const promise = new ZalgoPromise();\n let count = promises.length;\n // eslint-disable-next-line no-undef\n const results = ([] : $TupleMap<X, <Y>(ZalgoPromise<Y> | Y) => Y>).slice();\n\n if (!count) {\n promise.resolve(results);\n return promise;\n }\n\n const chain = <T>(i : number, firstPromise : ZalgoPromise<T>, secondPromise : ZalgoPromise<T>) => {\n return firstPromise.then(res => {\n results[i] = res;\n count -= 1;\n if (count === 0) {\n promise.resolve(results);\n }\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < promises.length; i++) {\n const prom = promises[i];\n\n if (prom instanceof ZalgoPromise) {\n if (prom.resolved) {\n results[i] = prom.value;\n count -= 1;\n continue;\n }\n } else if (!isPromise(prom)) {\n results[i] = prom;\n count -= 1;\n continue;\n }\n\n chain(i, ZalgoPromise.resolve(prom), promise);\n }\n\n if (count === 0) {\n promise.resolve(results);\n }\n\n return promise;\n }\n\n static hash<O : Object>(promises : O) : ZalgoPromise<$ObjMap<O, <Y>(ZalgoPromise<Y> | Y) => Y>> { // eslint-disable-line no-undef\n const result = {};\n const awaitPromises = [];\n\n for (const key in promises) {\n if (promises.hasOwnProperty(key)) {\n const value = promises[key];\n\n if (isPromise(value)) {\n awaitPromises.push(value.then(res => {\n result[key] = res;\n }));\n } else {\n result[key] = value;\n }\n }\n }\n \n return ZalgoPromise.all(awaitPromises).then(() => result);\n }\n\n static map<T, X>(items : $ReadOnlyArray<T>, method : (T) => (ZalgoPromise<X> | X)) : ZalgoPromise<$ReadOnlyArray<X>> {\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<X, Y, C : mixed, A : $ReadOnlyArray<mixed>>(method : (...args : $ReadOnlyArray<mixed>) => (ZalgoPromise<X> | Y), context? : C, args? : A) : ZalgoPromise<X | Y> {\n\n if (method && typeof method !== 'function' && !method.call) {\n throw new Error('Promise.try expected a function');\n }\n\n let result : ZalgoPromise<X> | Y;\n\n startActive();\n \n try {\n result = method.apply(context, args || []);\n } catch (err) {\n endActive();\n return ZalgoPromise.reject(err);\n }\n\n endActive();\n\n // $FlowFixMe incompatible-call\n const resultPromise = ZalgoPromise.resolve(result);\n\n return resultPromise;\n }\n\n static delay(delay : number) : ZalgoPromise<void> {\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<void> {\n return awaitActive(ZalgoPromise);\n }\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray<mixed>) {\n // pass\n}\n","/* @flow */\n\nexport const PROTOCOL = {\n MOCK: ('mock:' : 'mock:'),\n FILE: ('file:' : 'file:'),\n ABOUT: ('about:' : 'about:')\n};\n\nexport const WILDCARD = '*';\n\nexport const WINDOW_TYPE = {\n IFRAME: ('iframe' : 'iframe'),\n POPUP: ('popup' : 'popup')\n};\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray<CrossDomainWindowType> {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray<CrossDomainWindowType> {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray<CrossDomainWindowType> {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray<CrossDomainWindowType> {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray<CrossDomainWindowType> {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf<T>(collection : $ReadOnlyArray<T>, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray<CrossDomainWindowType> {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport function safeIndexOf<T>(collection : $ReadOnlyArray<T>, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray<mixed>) {\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<K : Object, V : mixed> {\n\n name : string\n weakmap : ?WeakMap<K, V>\n // eslint-disable-next-line flowtype/no-mutable-array\n keys : Array<K>\n // eslint-disable-next-line flowtype/no-mutable-array\n values : Array<V>\n\n constructor() {\n // eslint-disable-next-line no-bitwise\n this.name = `__weakmap_${ Math.random() * 1e9 >>> 0 }__`;\n\n if (hasNativeWeakMap()) {\n try {\n this.weakmap = new WeakMap();\n } catch (err) {\n // pass\n }\n }\n\n this.keys = [];\n this.values = [];\n }\n\n _cleanupClosedWindows() {\n\n const weakmap = this.weakmap;\n const keys = this.keys;\n\n for (let i = 0; i < keys.length; i++) {\n const value = keys[i];\n\n if (isWindow(value) && isWindowClosed(value)) {\n\n if (weakmap) {\n try {\n weakmap.delete(value);\n } catch (err) {\n // pass\n }\n }\n\n keys.splice(i, 1);\n this.values.splice(i, 1);\n\n i -= 1;\n }\n }\n }\n\n isSafeToReadWrite(key : K) : boolean {\n\n if (isWindow(key)) {\n return false;\n }\n\n try {\n noop(key && key.self);\n noop(key && key[this.name]);\n } catch (err) {\n return false;\n }\n\n return true;\n }\n\n set(key : K, value : V) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.set(key, value);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const name = this.name;\n const entry = key[name];\n\n if (entry && entry[0] === key) {\n entry[1] = value;\n } else {\n Object.defineProperty(key, name, {\n value: [ key, value ],\n writable: true\n });\n }\n\n return;\n\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const values = this.values;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n keys.push(key);\n values.push(value);\n } else {\n values[index] = value;\n }\n }\n\n get(key : K) : V | void {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return weakmap.get(key);\n }\n \n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return entry[1];\n }\n\n return;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n return;\n }\n\n return this.values[index];\n }\n\n delete(key : K) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.delete(key);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n entry[0] = entry[1] = undefined;\n }\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index !== -1) {\n keys.splice(index, 1);\n this.values.splice(index, 1);\n }\n }\n\n has(key : K) : boolean {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return true;\n }\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return true;\n }\n\n return false;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const index = safeIndexOf(this.keys, key);\n return index !== -1;\n }\n\n getOrSet(key : K, getter : () => V) : V {\n if (this.has(key)) {\n // $FlowFixMe\n return this.get(key);\n }\n\n const value = getter();\n this.set(key, value);\n return value;\n }\n}\n","\n/* @flow */\n/* eslint max-lines: 0 */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport type { CancelableType } from './types';\n\nexport function isElement(element : mixed) : boolean {\n let passed = false;\n\n try {\n if (element instanceof window.Element) {\n passed = true;\n } else if (element !== null && typeof element === 'object' && element.nodeType === 1 && typeof element.style === 'object' && typeof element.ownerDocument === 'object') {\n passed = true;\n }\n } catch (_) {\n // we don't have an element\n }\n\n return passed;\n}\n\nexport function getFunctionName <T : Function>(fn : T) : string {\n return fn.name || fn.__name__ || fn.displayName || 'anonymous';\n}\n\nexport function setFunctionName <T : Function>(fn : T, name : string) : T {\n try {\n delete fn.name;\n fn.name = name;\n } catch (err) {\n // pass\n }\n\n fn.__name__ = fn.displayName = name;\n return fn;\n}\n\nexport function base64encode(str : string) : string {\n if (typeof btoa === 'function') {\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (m, p1) => {\n return String.fromCharCode(parseInt(p1, 16));\n })).replace(/[=]/g, '');\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf8').toString('base64').replace(/[=]/g, '');\n }\n\n throw new Error(`Can not find window.btoa or Buffer`);\n}\n\nexport function base64decode(str : string) : string {\n if (typeof atob === 'function') {\n // $FlowFixMe[method-unbinding]\n return decodeURIComponent(Array.prototype.map.call(atob(str), c => {\n // eslint-disable-next-line prefer-template\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(''));\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64').toString('utf8');\n }\n\n throw new Error(`Can not find window.atob or Buffer`);\n}\n\nexport function uniqueID() : string {\n\n const chars = '0123456789abcdef';\n\n const randomID = 'xxxxxxxxxx'.replace(/./g, () => {\n return chars.charAt(Math.floor(Math.random() * chars.length));\n });\n\n const timeID = base64encode(\n new Date().toISOString().slice(11, 19).replace('T', '.')\n ).replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n\n return `uid_${ randomID }_${ timeID }`;\n}\n\nexport function getGlobal() : Object {\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (typeof __GLOBAL__ !== 'undefined') {\n return __GLOBAL__;\n }\n throw new Error(`No global found`);\n}\n\nlet objectIDs;\n\nexport function getObjectID(obj : Object) : string {\n\n objectIDs = objectIDs || new WeakMap();\n\n if (obj === null || obj === undefined || (typeof obj !== 'object' && typeof obj !== 'function')) {\n throw new Error(`Invalid object`);\n }\n\n let uid = objectIDs.get(obj);\n\n if (!uid) {\n uid = `${ typeof obj }:${ uniqueID() }`;\n objectIDs.set(obj, uid);\n }\n\n return uid;\n}\n\nfunction serializeArgs<T>(args : $ReadOnlyArray<T>) : string {\n try {\n // $FlowFixMe[method-unbinding]\n return JSON.stringify(Array.prototype.slice.call(args), (subkey, val) => {\n\n // Treat each distinct function as unique for purposes of memoization\n // e.g. even if someFunction.stringify() is the same, we may use a different memoize cache\n // if the actual function is different.\n if (typeof val === 'function') {\n return `memoize[${ getObjectID(val) }]`;\n }\n\n // By default JSON.stringify(domElement) returns '{}'. This ensures that stays true even for non-standard\n // elements (e.g. React-rendered dom elements) with custom properties\n if (isElement(val)) {\n return {};\n }\n\n return val;\n });\n } catch (err) {\n throw new Error(`Arguments not serializable -- can not be used to memoize`);\n }\n}\n\nexport function getEmptyObject() : {||} {\n // $FlowFixMe\n return {};\n}\n\ntype MemoizeOptions = {|\n name? : string,\n time? : number,\n thisNamespace? : boolean\n|};\n\nconst getDefaultMemoizeOptions = () : MemoizeOptions => {\n // $FlowFixMe\n return {};\n};\n\nexport type Memoized<F> = F & {| reset : () => void |};\n\nlet memoizeGlobalIndex = 0;\nlet memoizeGlobalIndexValidFrom = 0;\n\nexport function memoize<F : Function>(method : F, options? : MemoizeOptions = getDefaultMemoizeOptions()) : Memoized<F> {\n const { thisNamespace = false, time: cacheTime } = options;\n\n let simpleCache;\n let thisCache;\n\n let memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n\n const memoizedFunction = function memoizedFunction(...args) : mixed {\n if (memoizeIndex < memoizeGlobalIndexValidFrom) {\n simpleCache = null;\n thisCache = null;\n memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n }\n\n let cache;\n\n if (thisNamespace) {\n thisCache = thisCache || new WeakMap();\n cache = thisCache.getOrSet(this, getEmptyObject);\n } else {\n cache = simpleCache = simpleCache || {};\n }\n\n let cacheKey;\n\n try {\n cacheKey = serializeArgs(args);\n } catch {\n return method.apply(this, arguments);\n }\n\n let cacheResult = cache[cacheKey];\n\n if (cacheResult && cacheTime && (Date.now() - cacheResult.time) < cacheTime) {\n delete cache[cacheKey];\n cacheResult = null;\n }\n\n if (cacheResult) {\n return cacheResult.value;\n }\n\n const time = Date.now();\n const value = method.apply(this, arguments);\n\n cache[cacheKey] = { time, value };\n\n return value;\n };\n\n memoizedFunction.reset = () => {\n simpleCache = null;\n thisCache = null;\n };\n\n // $FlowFixMe\n const result : F = memoizedFunction;\n\n return setFunctionName(result, `${ options.name || getFunctionName(method) }::memoized`);\n}\n\nmemoize.clear = () => {\n memoizeGlobalIndexValidFrom = memoizeGlobalIndex;\n};\n\nexport function promiseIdentity<T : mixed>(item : ZalgoPromise<T> | T) : ZalgoPromise<T> {\n // $FlowFixMe\n return ZalgoPromise.resolve(item);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function memoizePromise<R>(method : (...args : $ReadOnlyArray<any>) => ZalgoPromise<R>) : ((...args : $ReadOnlyArray<any>) => ZalgoPromise<R>) {\n let cache = {};\n\n // eslint-disable-next-line flowtype/no-weak-types\n function memoizedPromiseFunction(...args : $ReadOnlyArray<any>) : ZalgoPromise<R> {\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<R>(method : (...args : $ReadOnlyArray<any>) => R, options : PromisifyOptions = getDefaultPromisifyOptions()) : ((...args : $ReadOnlyArray<any>) => ZalgoPromise<R>) {\n function promisifiedFunction() : ZalgoPromise<R> {\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<R>(method : (...args : $ReadOnlyArray<any>) => R, logic : (...args : $ReadOnlyArray<any>) => R, args : $ReadOnlyArray<any> = []) : 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<mixed>) {\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<T: mixed>(obj : Object, key : string) : ZalgoPromise<T> {\n return new ZalgoPromise(resolve => {\n\n let value = obj[key];\n\n if (value) {\n return resolve(value);\n }\n\n delete obj[key];\n\n Object.defineProperty(obj, key, {\n\n configurable: true,\n\n set(item) {\n value = item;\n\n if (value) {\n resolve(value);\n }\n },\n\n get() : T {\n return value;\n }\n });\n });\n}\n\nexport function stringifyError(err : mixed, level : number = 1) : string {\n\n if (level >= 3) {\n return 'stringifyError stack overflow';\n }\n\n try {\n if (!err) {\n // $FlowFixMe[method-unbinding]\n return `<unknown error: ${ Object.prototype.toString.call(err) }>`;\n }\n\n if (typeof err === 'string') {\n return err;\n }\n\n if (err instanceof Error) {\n const stack = err && err.stack;\n const message = err && err.message;\n\n if (stack && message) {\n if (stack.indexOf(message) !== -1) {\n return stack;\n } else {\n return `${ message }\\n${ stack }`;\n }\n } else if (stack) {\n return stack;\n } else if (message) {\n return message;\n }\n }\n\n if (err && err.toString && typeof err.toString === 'function') {\n // $FlowFixMe\n return err.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(err);\n\n } catch (newErr) {\n return `Error while stringifying error: ${ stringifyError(newErr, level + 1) }`;\n }\n}\n\nexport function stringifyErrorMessage(err : mixed) : string {\n\n // $FlowFixMe[method-unbinding]\n const defaultMessage = `<unknown error: ${ Object.prototype.toString.call(err) }>`;\n\n if (!err) {\n return defaultMessage;\n }\n\n if (err instanceof Error) {\n return err.message || defaultMessage;\n }\n\n if (typeof err.message === 'string') {\n return err.message || defaultMessage;\n }\n\n return defaultMessage;\n}\n\nexport function stringify(item : mixed) : string {\n if (typeof item === 'string') {\n return item;\n }\n\n if (item && item.toString && typeof item.toString === 'function') {\n // $FlowFixMe\n return item.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item);\n}\n\nexport function domainMatches(hostname : string, domain : string) : boolean {\n hostname = hostname.split('://')[1];\n const index = hostname.indexOf(domain);\n return (index !== -1 && hostname.slice(index) === domain);\n}\n\nexport function patchMethod(obj : Object, name : string, handler : Function) {\n const original = obj[name];\n\n obj[name] = function patchedMethod() : mixed {\n return handler({\n context: this,\n // $FlowFixMe[method-unbinding]\n args: Array.prototype.slice.call(arguments),\n original,\n callOriginal: () => original.apply(this, arguments)\n });\n };\n}\n\nexport function extend<T : Object | Function>(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<T>(obj : { [string] : T }) : $ReadOnlyArray<T> {\n if (Object.values) {\n // $FlowFixMe\n return Object.values(obj);\n }\n\n const result : Array<T> = [];\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n // $FlowFixMe[escaped-generic]\n result.push(obj[key]);\n }\n }\n\n // $FlowFixMe\n return result;\n}\n\n// eslint-disable-next-line no-undef\nexport const memoizedValues : <T>({ [string] : T }) => $ReadOnlyArray<T> = memoize(values);\n\nexport function perc(pixels : number, percentage : number) : number {\n return Math.round((pixels * percentage) / 100);\n}\n\nexport function min(...args : $ReadOnlyArray<number>) : number {\n return Math.min(...args);\n}\n\nexport function max(...args : $ReadOnlyArray<number>) : number {\n return Math.max(...args);\n}\n\nexport function roundUp(num : number, nearest : number) : number {\n const remainder = num % nearest;\n return remainder\n ? (num - remainder) + nearest\n : num;\n}\n\nexport function regexMap<T>(str : string, regexp : RegExp, handler : () => T) : $ReadOnlyArray<T> {\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<T, R>(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 <T>(item : T) : T {\n return item;\n}\n\nexport function regexTokenize(text : string, regexp : RegExp) : $ReadOnlyArray<string> {\n const result = [];\n text.replace(regexp, token => {\n result.push(token);\n return '';\n });\n return result;\n}\n\nexport function promiseDebounce<T>(method : () => ZalgoPromise<T> | T, delay : number = 50) : () => ZalgoPromise<T> {\n\n let promise;\n let timeout;\n\n const promiseDebounced = function() : ZalgoPromise<T> {\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<mixed>) => ZalgoPromise<void>,\n triggerOnce : (eventName : string, ...args : $ReadOnlyArray<mixed>) => ZalgoPromise<void>,\n reset : () => void\n|};\n\nexport function eventEmitter() : EventEmitterType {\n const triggered = {};\n let handlers = {};\n\n const emitter = {\n\n on(eventName : string, handler : Function) : CancelableType {\n const handlerList = handlers[eventName] = handlers[eventName] || [];\n\n handlerList.push(handler);\n\n let cancelled = false;\n\n return {\n cancel() {\n if (!cancelled) {\n cancelled = true;\n handlerList.splice(handlerList.indexOf(handler), 1);\n }\n\n }\n };\n },\n\n once(eventName : string, handler : Function) : CancelableType {\n\n const listener = emitter.on(eventName, () => {\n listener.cancel();\n handler();\n });\n\n return listener;\n },\n\n trigger(eventName : string, ...args : $ReadOnlyArray<mixed>) : ZalgoPromise<void> {\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<mixed>) : ZalgoPromise<void> {\n\n if (triggered[eventName]) {\n return ZalgoPromise.resolve();\n }\n\n triggered[eventName] = true;\n return emitter.trigger(eventName, ...args);\n },\n\n reset() {\n handlers = {};\n }\n };\n\n return emitter;\n}\n\nexport function camelToDasherize(string : string) : string {\n return string.replace(/([A-Z])/g, (g) => {\n return `-${ g.toLowerCase() }`;\n });\n}\n\nexport function dasherizeToCamel(string : string) : string {\n return string.replace(/-([a-z])/g, (g) => {\n return g[1].toUpperCase();\n });\n}\n\nexport function capitalizeFirstLetter(string : string) : string {\n return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();\n}\n\nexport function get(item : Object, path : string, def : mixed) : mixed {\n\n if (!path) {\n return def;\n }\n\n const pathParts = path.split('.');\n\n // Loop through each section of our key path\n\n for (let i = 0; i < pathParts.length; i++) {\n\n // If we have an object, we can get the key\n if (typeof item === 'object' && item !== null) {\n item = item[pathParts[i]];\n\n // Otherwise, we should return the default (undefined if not provided)\n } else {\n return def;\n }\n }\n\n // If our final result is undefined, we should return the default\n\n return item === undefined ? def : item;\n}\n\nexport function safeTimeout(method : Function, time : number) {\n\n const interval = safeInterval(() => {\n time -= 100;\n if (time <= 0) {\n interval.cancel();\n method();\n }\n }, 100);\n}\n\nexport function defineLazyProp<T>(obj : Object | $ReadOnlyArray<mixed>, 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<T>(item : Iterable<T>) : $ReadOnlyArray<T> { // eslint-disable-line no-undef\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(item);\n}\n\nexport function isObject(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null);\n}\n\nexport function isObjectObject(obj : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return isObject(obj) && Object.prototype.toString.call(obj) === '[object Object]';\n}\n\nexport function isPlainObject(obj : mixed) : boolean {\n if (!isObjectObject(obj)) {\n return false;\n }\n\n // $FlowFixMe\n const constructor = obj.constructor;\n\n if (typeof constructor !== 'function') {\n return false;\n }\n\n const prototype = constructor.prototype;\n\n if (!isObjectObject(prototype)) {\n return false;\n }\n\n if (!prototype.hasOwnProperty('isPrototypeOf')) {\n return false;\n }\n\n return true;\n}\n\nexport function replaceObject<T : $ReadOnlyArray<mixed> | 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<mixed> = [];\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<string>,\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<RegexResultType> {\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<void> {\n return ZalgoPromise.try(method).then(() => cycle(method));\n}\n\nexport function debounce<T>(method : (...args : $ReadOnlyArray<mixed>) => T, time : number = 100) : (...args : $ReadOnlyArray<mixed>) => void {\n\n let timeout;\n\n const debounceWrapper = function() {\n clearTimeout(timeout);\n\n timeout = setTimeout(() => {\n return method.apply(this, arguments);\n }, time);\n };\n\n return setFunctionName(debounceWrapper, `${ getFunctionName(method) }::debounced`);\n}\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\ntype FunctionProxy<T : Function> = (method : T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoize : FunctionProxy<*> = <R : mixed>(method : (arg : any) => R) : ((...args : $ReadOnlyArray<any>) => 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<R : mixed, T : (...args : $ReadOnlyArray<mixed>) => ZalgoPromise<R>> = (T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoizePromise : FunctionPromiseProxy<*, *> = <R : mixed>(method : (arg : any) => ZalgoPromise<R>) : ((...args : $ReadOnlyArray<any>) => ZalgoPromise<R>) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoizedPromise(arg : any) : ZalgoPromise<R> {\n return weakmap.getOrSet(arg, () =>\n method.call(this, arg).finally(() => {\n weakmap.delete(arg);\n }));\n };\n};\n\nexport function getOrSet<O : Object, T : mixed>(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 : <T : mixed>(string, T) => T, // eslint-disable-line no-undef\n register : (Function) => {| cancel : () => void |},\n all : (err? : mixed) => ZalgoPromise<void>\n|};\n\nexport function cleanup(obj : Object) : CleanupType {\n\n const tasks = [];\n let cleaned = false;\n let cleanErr;\n\n const cleaner = {\n set<T : mixed>(name : string, item : T) : T {\n if (!cleaned) {\n obj[name] = item;\n cleaner.register(() => {\n delete obj[name];\n });\n }\n return item;\n },\n\n register(method : Function) : {| cancel : () => void |} {\n const task = once(() => method(cleanErr));\n\n if (cleaned) {\n method(cleanErr);\n } else {\n tasks.push(task);\n }\n\n return {\n cancel: () => {\n const index = tasks.indexOf(task);\n if (index !== -1) {\n tasks.splice(index, 1);\n }\n }\n };\n },\n\n all(err? : mixed) : ZalgoPromise<void> {\n cleanErr = err;\n\n const results = [];\n cleaned = true;\n\n while (tasks.length) {\n const task = tasks.shift();\n results.push(task());\n }\n\n return ZalgoPromise.all(results).then(noop);\n }\n };\n\n return cleaner;\n}\n\nexport function tryCatch<T>(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<X, T : Array<X>>(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<T>(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<string>) : $ReadOnlyArray<string> {\n const result = {};\n for (const item of arr) {\n result[item] = true;\n }\n return Object.keys(result);\n}\n\nexport const constHas = <X : (string | boolean | number), T : { [string] : X }>(constant : T, value : X) : boolean => {\n return memoizedValues(constant).indexOf(value) !== -1;\n};\n\nexport function dedupeErrors<T>(handler : (mixed) => T) : (mixed) => (T | void) {\n const seenErrors = [];\n const seenStringifiedErrors = {};\n\n return (err) => {\n if (seenErrors.indexOf(err) !== -1) {\n return;\n }\n\n seenErrors.push(err);\n\n const stringifiedError = stringifyError(err);\n if (seenStringifiedErrors[stringifiedError]) {\n return;\n }\n\n seenStringifiedErrors[stringifiedError] = true;\n return handler(err);\n };\n}\n\nexport class ExtendableError extends Error {\n constructor(message : string) {\n super(message);\n // eslint-disable-next-line unicorn/custom-error-definition\n this.name = this.constructor.name;\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error(message)).stack;\n }\n }\n}\n","/* @flow */\n\nexport function hasNativeWeakMap() : boolean {\n\n if (typeof WeakMap === 'undefined') {\n return false;\n }\n\n if (typeof Object.freeze === 'undefined') {\n return false;\n }\n\n try {\n\n const testWeakMap = new WeakMap();\n const testKey = {};\n const testValue = '__testvalue__';\n\n Object.freeze(testKey);\n\n testWeakMap.set(testKey, testValue);\n\n if (testWeakMap.get(testKey) === testValue) {\n return true;\n }\n\n return false;\n\n } catch (err) {\n\n return false;\n }\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeReflectConstruct from \"@babel/runtime/helpers/esm/isNativeReflectConstruct\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}","import getPrototypeOf from \"@babel/runtime/helpers/esm/getPrototypeOf\";\nimport setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeFunction from \"@babel/runtime/helpers/esm/isNativeFunction\";\nimport construct from \"@babel/runtime/helpers/esm/construct\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","/* @flow */\n/* eslint max-lines: off */\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { linkFrameWindow, isWindowClosed, assertSameDomain,\n type SameDomainWindowType, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport { isElement, inlineMemoize, memoize, noop, stringify, capitalizeFirstLetter,\n once, extend, safeInterval, uniqueID, arrayFrom, ExtendableError, strHashStr } from './util';\nimport { isDevice } from './device';\nimport { KEY_CODES, ATTRIBUTES, UID_HASH_LENGTH } from './constants';\nimport type { CancelableType } from './types';\n\ntype ElementRefType = string | HTMLElement;\n\nexport function getBody() : HTMLBodyElement {\n // eslint-disable-next-line compat/compat\n const body = document.body;\n\n if (!body) {\n throw new Error(`Body element not found`);\n }\n\n return body;\n}\n\nexport function isDocumentReady() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'complete');\n}\n\nexport function isDocumentInteractive() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'interactive');\n}\n\nexport function urlEncode(str : string) : string {\n return encodeURIComponent(str);\n}\n\nexport function waitForWindowReady() : ZalgoPromise<void> {\n return inlineMemoize(waitForWindowReady, () : ZalgoPromise<void> => {\n return new ZalgoPromise(resolve => {\n if (isDocumentReady()) {\n resolve();\n }\n\n window.addEventListener('load', () => resolve());\n });\n });\n}\n\ntype WaitForDocumentReady = () => ZalgoPromise<void>;\n\nexport const waitForDocumentReady : WaitForDocumentReady = memoize(() => {\n return new ZalgoPromise(resolve => {\n\n if (isDocumentReady() || isDocumentInteractive()) {\n return resolve();\n }\n\n const interval = setInterval(() => {\n if (isDocumentReady() || isDocumentInteractive()) {\n clearInterval(interval);\n return resolve();\n }\n }, 10);\n });\n});\n\nexport function waitForDocumentBody() : ZalgoPromise<HTMLBodyElement> {\n return ZalgoPromise.try(() => {\n if (document.body) {\n return document.body;\n }\n\n return waitForDocumentReady().then(() => {\n if (document.body) {\n return document.body;\n }\n\n throw new Error('Document ready but document.body not present');\n });\n });\n}\n\nexport function parseQuery(queryString : string) : Object {\n return inlineMemoize(parseQuery, () : Object => {\n const params = {};\n\n if (!queryString) {\n return params;\n }\n\n if (queryString.indexOf('=') === -1) {\n return params;\n }\n\n for (let pair of queryString.split('&')) {\n pair = pair.split('=');\n\n if (pair[0] && pair[1]) {\n params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n }\n\n return params;\n }, [ queryString ]);\n}\n\n\nexport function getQueryParam(name : string) : string {\n return parseQuery(window.location.search.slice(1))[name];\n}\n\nexport function urlWillRedirectPage(url : string) : boolean {\n\n if (url.indexOf('#') === -1) {\n return true;\n }\n\n if (url.indexOf('#') === 0) {\n return false;\n }\n\n if (url.split('#')[0] === window.location.href.split('#')[0]) {\n return false;\n }\n\n return true;\n}\n\nexport type Query = {\n [ string ] : boolean | string\n};\n\nexport function formatQuery(obj : Query = {}) : string {\n\n return Object.keys(obj).filter(key => {\n return typeof obj[key] === 'string' || typeof obj[key] === 'boolean';\n }).map(key => {\n const val = obj[key];\n\n if (typeof val !== 'string' && typeof val !== 'boolean') {\n throw new TypeError(`Invalid type for query`);\n }\n\n return `${ urlEncode(key) }=${ urlEncode(val.toString()) }`;\n }).join('&');\n}\n\nexport function extendQuery(originalQuery : string, props : Query = {}) : string {\n\n if (!props || !Object.keys(props).length) {\n return originalQuery;\n }\n\n return formatQuery({\n ...parseQuery(originalQuery),\n ...props\n });\n}\n\nexport function extendUrl(url : string, options : {| query? : Query, hash? : Query |}) : string {\n\n const query = options.query || {};\n const hash = options.hash || {};\n\n let originalUrl;\n let originalQuery;\n let originalHash;\n\n [ originalUrl, originalHash ] = url.split('#');\n [ originalUrl, originalQuery ] = originalUrl.split('?');\n\n const queryString = extendQuery(originalQuery, query);\n const hashString = extendQuery(originalHash, hash);\n\n if (queryString) {\n originalUrl = `${ originalUrl }?${ queryString }`;\n }\n\n if (hashString) {\n originalUrl = `${ originalUrl }#${ hashString }`;\n }\n\n return originalUrl;\n}\n\nexport function redirect(url : string, win : CrossDomainWindowType = window) : ZalgoPromise<void> {\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<?number> {\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 .replace(/\\//g, '/');\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined') && window.location !== undefined;\n}\n\nexport function querySelectorAll(selector : string, doc : HTMLElement = window.document) : $ReadOnlyArray<HTMLElement> {\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(doc.querySelectorAll(selector));\n}\n\nexport function onClick(element : HTMLElement, handler : (Event) => void) {\n element.addEventListener('touchstart', noop);\n element.addEventListener('click', handler);\n element.addEventListener('keypress', (event : Event) => {\n // $FlowFixMe\n if (event.keyCode === KEY_CODES.ENTER || event.keyCode === KEY_CODES.SPACE) {\n return handler(event);\n }\n });\n}\n\nexport function getScript({ host = window.location.host, path, reverse = false } : {| host? : string, path : string, reverse? : boolean |}) : ?HTMLScriptElement {\n return inlineMemoize(getScript, () : ?HTMLScriptElement => {\n\n const url = `${ host }${ path }`;\n // $FlowFixMe[method-unbinding]\n const scripts = Array.prototype.slice.call(document.getElementsByTagName('script'));\n\n if (reverse) {\n scripts.reverse();\n }\n\n for (const script of scripts) {\n if (!script.src) {\n continue;\n }\n\n const src = script.src.replace(/^https?:\\/\\//, '').split('?')[0];\n\n if (src === url) {\n return script;\n }\n }\n }, [ path ]);\n}\n\nexport function isLocalStorageEnabled() : boolean {\n return inlineMemoize(isLocalStorageEnabled, () => {\n try {\n if (typeof window === 'undefined') {\n return false;\n }\n\n if (window.localStorage) {\n const value = Math.random().toString();\n window.localStorage.setItem('__test__localStorage__', value);\n const result = window.localStorage.getItem('__test__localStorage__');\n window.localStorage.removeItem('__test__localStorage__');\n if (value === result) {\n return true;\n }\n }\n } catch (err) {\n // pass\n }\n return false;\n });\n}\n\nexport function getBrowserLocales() : $ReadOnlyArray<{| country? : string, lang : string |}> {\n const nav = window.navigator;\n\n const locales = nav.languages\n ? [ ...nav.languages ]\n : [];\n\n if (nav.language) {\n locales.push(nav.language);\n }\n\n if (nav.userLanguage) {\n locales.push(nav.userLanguage);\n }\n\n return locales.map(locale => {\n\n if (locale && locale.match(/^[a-z]{2}[-_][A-Z]{2}$/)) {\n const [ lang, country ] = locale.split(/[-_]/);\n return { country, lang };\n }\n\n if (locale && locale.match(/^[a-z]{2}$/)) {\n return { lang: locale };\n }\n\n return null;\n\n }).filter(Boolean);\n}\n\n\nexport function appendChild(container : HTMLElement, child : HTMLElement | Text) {\n container.appendChild(child);\n}\n\nexport function getElementSafe(id : ElementRefType, doc : Document | HTMLElement = document) : ?HTMLElement {\n\n if (isElement(id)) {\n // $FlowFixMe\n return id;\n }\n\n if (typeof id === 'string') {\n return doc.querySelector(id);\n }\n}\n\nexport function getElement(id : ElementRefType, doc : Document | HTMLElement = document) : HTMLElement {\n\n const element = getElementSafe(id, doc);\n\n if (element) {\n return element;\n }\n\n throw new Error(`Can not find element: ${ stringify(id) }`);\n}\n\nexport function elementReady(id : ElementRefType) : ZalgoPromise<HTMLElement> {\n return new ZalgoPromise((resolve, reject) => {\n\n const name = stringify(id);\n let el = getElementSafe(id);\n\n if (el) {\n return resolve(el);\n }\n\n if (isDocumentReady()) {\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n\n const interval = setInterval(() => {\n\n el = getElementSafe(id);\n\n if (el) {\n resolve(el);\n clearInterval(interval);\n return;\n }\n\n if (isDocumentReady()) {\n clearInterval(interval);\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n }, 10);\n });\n}\n\n// eslint-disable-next-line unicorn/custom-error-definition\nexport class PopupOpenError extends ExtendableError {}\n\ntype PopupOptions = {|\n name? : string,\n width? : number,\n height? : number,\n top? : number,\n left? : number,\n status? : 0 | 1,\n resizable? : 0 | 1,\n toolbar? : 0 | 1,\n menubar? : 0 | 1,\n scrollbars? : 0 | 1,\n closeOnUnload? : 0 | 1\n|};\n\nexport function popup(url : string, options? : PopupOptions) : CrossDomainWindowType {\n\n // $FlowFixMe\n options = options || {};\n\n const { closeOnUnload = 1, name = '', width, height } = options;\n\n let top = 0;\n let left = 0;\n\n if (width) {\n if (window.outerWidth) {\n left = Math.round((window.outerWidth - width) / 2) + window.screenX;\n } else if (window.screen.width) {\n left = Math.round((window.screen.width - width) / 2);\n }\n }\n\n if (height) {\n if (window.outerHeight) {\n top = Math.round((window.outerHeight - height) / 2) + window.screenY;\n } else if (window.screen.height) {\n top = Math.round((window.screen.height - height) / 2);\n }\n }\n\n delete options.closeOnUnload;\n delete options.name;\n\n if (width && height) {\n // $FlowFixMe\n options = {\n top,\n left,\n width,\n height,\n status: 1,\n toolbar: 0,\n menubar: 0,\n resizable: 1,\n scrollbars: 1,\n ...options\n };\n }\n\n // eslint-disable-next-line array-callback-return\n const params = Object.keys(options).map(key => {\n // $FlowFixMe\n if (options[key] !== null && options[key] !== undefined) {\n return `${ key }=${ stringify(options[key]) }`;\n }\n }).filter(Boolean).join(',');\n\n let win;\n\n try {\n win = window.open(url, name, params);\n } catch (err) {\n throw new PopupOpenError(`Can not open popup window - ${ err.stack || err.message }`);\n }\n\n if (isWindowClosed(win)) {\n const err = new PopupOpenError(`Can not open popup window - blocked`);\n throw err;\n }\n\n if (closeOnUnload) {\n window.addEventListener('unload', () => win.close());\n }\n\n return win;\n}\n\n\nexport function writeToWindow(win : SameDomainWindowType, html : string) {\n try {\n win.document.open();\n win.document.write(html);\n win.document.close();\n } catch (err) {\n try {\n win.location = `javascript: document.open(); document.write(${ JSON.stringify(html) }); document.close();`;\n } catch (err2) {\n // pass\n }\n }\n}\n\nexport function writeElementToWindow(win : SameDomainWindowType, el : HTMLElement) {\n\n const tag = el.tagName.toLowerCase();\n\n if (tag !== 'html') {\n throw new Error(`Expected element to be html, got ${ tag }`);\n }\n\n const documentElement = win.document.documentElement;\n\n for (const child of arrayFrom(documentElement.children)) {\n documentElement.removeChild(child);\n }\n\n for (const child of arrayFrom(el.children)) {\n documentElement.appendChild(child);\n }\n}\n\nexport function setStyle(el : HTMLElement, styleText : string, doc : Document = window.document) {\n // $FlowFixMe\n if (el.styleSheet) {\n // $FlowFixMe\n el.styleSheet.cssText = styleText;\n } else {\n el.appendChild(doc.createTextNode(styleText));\n }\n}\n\nexport type ElementOptionsType = {|\n style? : { [ string ] : string },\n id? : string,\n class? : ?$ReadOnlyArray<string>,\n attributes? : { [ string ] : string },\n styleSheet? : ?string,\n html? : ?string\n|};\n\nlet awaitFrameLoadPromises : WeakMap<HTMLIFrameElement, ZalgoPromise<HTMLIFrameElement>>;\n\nexport function awaitFrameLoad(frame : HTMLIFrameElement) : ZalgoPromise<HTMLIFrameElement> {\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<CrossDomainWindowType> {\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<string>,\n attributes? : StringMap,\n styleSheet? : ?string,\n html? : ?string,\n url? : ?string\n|};\n\nconst getDefaultIframeOptions = () : IframeElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultStringMap = () : StringMap => {\n // $FlowFixMe\n return {};\n};\n\nexport function iframe(options : IframeElementOptionsType = getDefaultIframeOptions(), container : ?HTMLElement) : HTMLIFrameElement {\n\n const attributes = options.attributes || getDefaultStringMap();\n const style = options.style || getDefaultStringMap();\n\n // $FlowFixMe\n const newAttributes = {\n allowTransparency: 'true',\n ...attributes\n };\n\n // $FlowFixMe\n const newStyle = {\n backgroundColor: 'transparent',\n border: 'none',\n ...style\n };\n\n const frame = createElement('iframe', {\n attributes: newAttributes,\n style: newStyle,\n html: options.html,\n class: options.class\n });\n\n const isIE = window.navigator.userAgent.match(/MSIE|Edge/i);\n\n if (!frame.hasAttribute('id')) {\n frame.setAttribute('id', uniqueID());\n }\n\n // $FlowFixMe\n awaitFrameLoad(frame);\n\n if (container) {\n const el = getElement(container);\n el.appendChild(frame);\n }\n\n if (options.url || isIE) {\n frame.setAttribute('src', options.url || 'about:blank');\n }\n\n // $FlowFixMe\n return frame;\n}\n\nexport function addEventListener(obj : HTMLElement, event : string, handler : (event : Event) => void) : CancelableType {\n obj.addEventListener(event, handler);\n return {\n cancel() {\n obj.removeEventListener(event, handler);\n }\n };\n}\n\nexport function bindEvents(element : HTMLElement, eventNames : $ReadOnlyArray<string>, 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<void> {\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<void> {\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<void> {\n return animate(element, name, clean).then(() => {\n hideElement(element);\n });\n}\n\nexport function addClass(element : HTMLElement, name : string) {\n element.classList.add(name);\n}\n\nexport function removeClass(element : HTMLElement, name : string) {\n element.classList.remove(name);\n}\n\nexport function isElementClosed(el : HTMLElement) : boolean {\n if (!el || !el.parentNode || !el.ownerDocument || !el.ownerDocument.documentElement || !el.ownerDocument.documentElement.contains(el)) {\n return true;\n }\n return false;\n}\n\nexport function watchElementForClose(element : HTMLElement, handler : () => mixed) : CancelableType {\n handler = once(handler);\n\n let cancelled = false;\n const mutationObservers = [];\n // eslint-disable-next-line prefer-const\n let interval;\n // eslint-disable-next-line prefer-const\n let sacrificialFrame;\n let sacrificialFrameWin;\n\n const cancel = () => {\n cancelled = true;\n for (const observer of mutationObservers) {\n observer.disconnect();\n }\n if (interval) {\n interval.cancel();\n }\n if (sacrificialFrameWin) {\n // eslint-disable-next-line no-use-before-define\n sacrificialFrameWin.removeEventListener('unload', elementClosed);\n }\n if (sacrificialFrame) {\n destroyElement(sacrificialFrame);\n }\n };\n\n const elementClosed = () => {\n if (!cancelled) {\n handler();\n cancel();\n }\n };\n\n if (isElementClosed(element)) {\n elementClosed();\n return { cancel };\n }\n\n // Strategy 1: Mutation observer\n\n if (window.MutationObserver) {\n let mutationElement = element.parentElement;\n while (mutationElement) {\n const mutationObserver = new window.MutationObserver(() => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n });\n\n mutationObserver.observe(mutationElement, { childList: true });\n mutationObservers.push(mutationObserver);\n mutationElement = mutationElement.parentElement;\n }\n }\n\n // Strategy 2: Sacrificial iframe\n\n sacrificialFrame = document.createElement('iframe');\n sacrificialFrame.setAttribute('name', `__detect_close_${ uniqueID() }__`);\n sacrificialFrame.style.display = 'none';\n awaitFrameWindow(sacrificialFrame).then(frameWin => {\n sacrificialFrameWin = assertSameDomain(frameWin);\n sacrificialFrameWin.addEventListener('unload', elementClosed);\n });\n element.appendChild(sacrificialFrame);\n\n // Strategy 3: Poller\n\n const check = () => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n };\n interval = safeInterval(check, 1000);\n\n return { cancel };\n}\n\nexport function fixScripts(el : HTMLElement, doc : Document = window.document) {\n for (const script of querySelectorAll('script', el)) {\n const parentNode = script.parentNode;\n\n if (!parentNode) {\n continue;\n }\n\n const newScript = doc.createElement('script');\n newScript.text = script.textContent;\n parentNode.replaceChild(newScript, script);\n }\n}\n\ntype OnResizeOptions = {|\n width? : boolean,\n height? : boolean,\n interval? : number,\n win? : SameDomainWindowType\n|};\n\nexport function onResize(el : HTMLElement, handler : ({| width : number, height : number |}) => void, { width = true, height = true, interval = 100, win = window } : OnResizeOptions = {}) : {| cancel : () => void |} {\n let currentWidth = el.offsetWidth;\n let currentHeight = el.offsetHeight;\n let canceled = false;\n\n handler({ width: currentWidth, height: currentHeight });\n\n const check = () => {\n if (canceled || !isElementVisible(el)) {\n return;\n }\n\n const newWidth = el.offsetWidth;\n const newHeight = el.offsetHeight;\n\n if ((width && newWidth !== currentWidth) || (height && newHeight !== currentHeight)) {\n handler({ width: newWidth, height: newHeight });\n }\n\n currentWidth = newWidth;\n currentHeight = newHeight;\n };\n\n let observer;\n let timeout;\n\n win.addEventListener('resize', check);\n\n if (typeof win.ResizeObserver !== 'undefined') {\n observer = new win.ResizeObserver(check);\n observer.observe(el);\n timeout = safeInterval(check, interval * 10);\n\n } else if (typeof win.MutationObserver !== 'undefined') {\n observer = new win.MutationObserver(check);\n observer.observe(el, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: false\n });\n timeout = safeInterval(check, interval * 10);\n } else {\n timeout = safeInterval(check, interval);\n }\n\n return {\n cancel: () => {\n canceled = true;\n observer.disconnect();\n window.removeEventListener('resize', check);\n timeout.cancel();\n }\n };\n}\n\nexport function getResourceLoadTime(url : string) : ?number {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n if (typeof performance.getEntries !== 'function') {\n return;\n }\n\n const entries = performance.getEntries();\n\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n\n if (entry && entry.name && entry.name.indexOf(url) === 0 && typeof entry.duration === 'number') {\n return Math.floor(entry.duration);\n }\n }\n}\n\nexport function isShadowElement(element : Node) : boolean {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n return element.toString() === '[object ShadowRoot]';\n}\n\nexport function getShadowRoot(element : Node) : ?Node {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n if (isShadowElement(element)) {\n return element;\n }\n}\n\nexport function getShadowHost(element : Node) : ?HTMLElement {\n const shadowRoot = getShadowRoot(element);\n\n // $FlowFixMe\n if (shadowRoot && shadowRoot.host) {\n // $FlowFixMe\n return shadowRoot.host;\n }\n}\n\n\nexport function insertShadowSlot(element : HTMLElement) : HTMLElement {\n const shadowHost = getShadowHost(element);\n\n if (!shadowHost) {\n throw new Error(`Element is not in shadow dom`);\n }\n\n const slotName = `shadow-slot-${ uniqueID() }`;\n const slot = document.createElement('slot');\n slot.setAttribute('name', slotName);\n element.appendChild(slot);\n\n const slotProvider = document.createElement('div');\n slotProvider.setAttribute('slot', slotName);\n shadowHost.appendChild(slotProvider);\n\n if (isShadowElement(shadowHost)) {\n return insertShadowSlot(slotProvider);\n }\n\n return slotProvider;\n}\n\nexport function preventClickFocus(el : HTMLElement) {\n const onFocus = (event : Event) => {\n el.removeEventListener('focus', onFocus);\n event.preventDefault();\n el.blur();\n return false;\n };\n\n el.addEventListener('mousedown', () => {\n el.addEventListener('focus', onFocus);\n setTimeout(() => {\n el.removeEventListener('focus', onFocus);\n }, 1);\n });\n}\n\nexport function getStackTrace() : string {\n try {\n throw new Error('_');\n }\n catch (err) {\n return err.stack || '';\n }\n}\n\nfunction inferCurrentScript() : ?HTMLScriptElement {\n try {\n const stack = getStackTrace();\n const stackDetails = (/.*at [^(]*\\((.*):(.+):(.+)\\)$/ig).exec(stack);\n const scriptLocation = stackDetails && stackDetails[1];\n\n if (!scriptLocation) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n for (const script of Array.prototype.slice.call(document.getElementsByTagName('script')).reverse()) {\n if (script.src && script.src === scriptLocation) {\n return script;\n }\n }\n\n } catch (err) {\n // pass\n }\n}\n\n// eslint-disable-next-line compat/compat\nlet currentScript = typeof document !== 'undefined' ? document.currentScript : null;\n\ntype GetCurrentScript = () => HTMLScriptElement;\n\nexport const getCurrentScript : GetCurrentScript = memoize(() => {\n if (currentScript) {\n return currentScript;\n }\n\n currentScript = inferCurrentScript();\n\n if (currentScript) {\n return currentScript;\n }\n\n throw new Error('Can not determine current script');\n});\n\nconst currentUID = uniqueID();\n\ntype GetCurrentScriptUID = () => string;\n\nexport const getCurrentScriptUID : GetCurrentScriptUID = memoize(() => {\n let script;\n\n try {\n script = getCurrentScript();\n } catch (err) {\n return currentUID;\n }\n\n let uid = script.getAttribute(ATTRIBUTES.UID);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n uid = script.getAttribute(`${ ATTRIBUTES.UID }-auto`);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n if (script.src) {\n\n const { src, dataset } = script;\n const stringToHash = JSON.stringify({ src, dataset });\n const hashedString = strHashStr(stringToHash);\n const hashResult = hashedString.slice(hashedString.length - UID_HASH_LENGTH);\n\n uid = `uid_${ hashResult }`;\n } else {\n uid = uniqueID();\n }\n\n script.setAttribute(`${ ATTRIBUTES.UID }-auto`, uid);\n\n return uid;\n});\n\ntype SubmitFormOptions = {|\n url : string,\n target : string,\n body? : {| [string] : string | boolean |},\n method? : string\n|};\n\nexport function submitForm({ url, target, body, method = 'post' } : SubmitFormOptions) {\n const form = document.createElement('form');\n form.setAttribute('target', target);\n form.setAttribute('method', method);\n form.setAttribute('action', url);\n form.style.display = 'none';\n\n if (body) {\n for (const key of Object.keys(body)) {\n const input = document.createElement('input');\n input.setAttribute('name', key);\n input.setAttribute('value', body[key]?.toString());\n form.appendChild(input);\n }\n }\n\n getBody().appendChild(form);\n form.submit();\n getBody().removeChild(form);\n}\n","/* @flow */\n\nexport function isPerc(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+%$/).test(str);\n}\n\nexport function isPx(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+px$/).test(str);\n}\n\nexport function toNum(val : string | number) : number {\n\n if (typeof val === 'number') {\n return val;\n }\n\n const match = val.match(/^([0-9]+)(px|%)$/);\n\n if (!match) {\n throw new Error(`Could not match css value from ${ val }`);\n }\n\n return parseInt(match[1], 10);\n}\n\nexport function toPx(val : number | string) : string {\n return `${ toNum(val) }px`;\n}\n\nexport function toCSS(val : number | string) : string {\n\n if (typeof val === 'number') {\n return toPx(val);\n }\n\n return isPerc(val) ? val : toPx(val);\n}\n\nexport function percOf(num : number, perc : string) : number {\n return parseInt(num * toNum(perc) / 100, 10);\n}\n\nexport function normalizeDimension(dim : string | number, max : number) : number {\n if (typeof dim === 'number') {\n return dim;\n } else if (isPerc(dim)) {\n return percOf(max, dim);\n } else if (isPx(dim)) {\n return toNum(dim);\n } else {\n throw new Error(`Can not normalize dimension: ${ dim }`);\n }\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type SameDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\nimport { getOrSet, getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__POST_ROBOT__.__SCRIPT_NAMESPACE__) {\n return `${ __POST_ROBOT__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __POST_ROBOT__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : SameDomainWindowType = window) : Object {\n const globalKey = getGlobalKey();\n\n if (win !== window) {\n return win[globalKey];\n }\n const global : Object = win[globalKey] = win[globalKey] || {};\n return global;\n}\n\nexport function deleteGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n\ntype ObjectGetter = () => Object;\nconst getObj : ObjectGetter = () => ({});\n\ntype GetOrSet<T> = ((string, () => T) => T) & ((string, () => void) => void);\n\ntype GlobalStore<T> = {|\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<T>,\n reset : () => void,\n keys : () => $ReadOnlyArray<string>\n|};\n\nexport function globalStore<T : mixed>(key? : string = 'store', defStore? : ObjectGetter = getObj) : GlobalStore<T> {\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<T> = {|\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<T>(key? : string = 'store', defStore? : ObjectGetter = getObj) : WindowStore<T> {\n return globalStore('windowStore').getOrSet(key, () => {\n const winStore = new WeakMap();\n\n const getStore = (win : CrossDomainWindowType | WildCard) : ObjectGetter => {\n return winStore.getOrSet(win, defStore);\n };\n \n return {\n has: (win) => {\n const store = getStore(win);\n return store.hasOwnProperty(key);\n },\n get: (win, defVal) => {\n const store = getStore(win);\n // $FlowFixMe\n return store.hasOwnProperty(key) ? store[key] : defVal;\n },\n set: (win, val) => {\n const store = getStore(win);\n store[key] = val;\n return val;\n },\n del: (win) => {\n const store = getStore(win);\n delete store[key];\n },\n getOrSet: (win, getter) => {\n const store = getStore(win);\n return getOrSet(store, key, getter);\n }\n };\n });\n}\n","/* @flow */\n\nexport const KEY_CODES = {\n ENTER: 13,\n SPACE: 32\n};\n\nexport const ATTRIBUTES = {\n UID: 'data-uid'\n};\n\nexport const UID_HASH_LENGTH = 30;\n","/* @flow */\n\nimport { getAncestor, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { windowStore, globalStore, getGlobal } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nfunction getInstanceID() : string {\n return globalStore('instance').getOrSet('instanceID', uniqueID);\n}\n\nfunction getHelloPromise(win : CrossDomainWindowType) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n return helloPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nfunction resolveHelloPromise(win : CrossDomainWindowType, { domain }) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n const existingPromise = helloPromises.get(win);\n if (existingPromise) {\n existingPromise.resolve({ domain });\n }\n const newPromise = ZalgoPromise.resolve({ domain });\n helloPromises.set(win, newPromise);\n return newPromise;\n}\n\nfunction listenForHello({ on } : {| on : OnType |}) : CancelableType {\n return on(MESSAGE_NAME.HELLO, { domain: WILDCARD }, ({ source, origin }) => {\n resolveHelloPromise(source, { domain: origin });\n return { instanceID: getInstanceID() };\n });\n}\n\nexport function sayHello(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise<{| win : CrossDomainWindowType, domain : string, instanceID : string |}> {\n return send(win, MESSAGE_NAME.HELLO, { instanceID: getInstanceID() }, { domain: WILDCARD, timeout: -1 })\n .then(({ origin, data: { instanceID } }) => {\n resolveHelloPromise(win, { domain: origin });\n return { win, domain: origin, instanceID };\n });\n}\n\nexport function getWindowInstanceID(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise<string> {\n return windowStore('windowInstanceIDPromises').getOrSet(win, () => {\n return sayHello(win, { send }).then(({ instanceID }) => instanceID);\n });\n}\n\nexport function initHello({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('helloListener', () => {\n const listener = listenForHello({ on });\n\n const parent = getAncestor();\n if (parent) {\n sayHello(parent, { send }).catch(err => {\n // $FlowFixMe\n if (__TEST__ && getGlobal(parent)) {\n throw err;\n }\n });\n }\n\n return listener;\n });\n}\n\nexport function awaitWindowHello(win : CrossDomainWindowType, timeout : number = 5000, name : string = 'Window') : ZalgoPromise<{| domain : string |}> {\n let promise = getHelloPromise(win);\n\n if (timeout !== -1) {\n promise = promise.timeout(timeout, new Error(`${ name } did not load after ${ timeout }ms`));\n }\n\n return promise;\n}\n","/* @flow */\n\nexport const MESSAGE_TYPE = {\n REQUEST: ('postrobot_message_request' : 'postrobot_message_request'),\n RESPONSE: ('postrobot_message_response' : 'postrobot_message_response'),\n ACK: ('postrobot_message_ack' : 'postrobot_message_ack')\n};\n\nexport const MESSAGE_ACK = {\n SUCCESS: ('success' : 'success'),\n ERROR: ('error' : 'error')\n};\n\nexport const MESSAGE_NAME = {\n METHOD: ('postrobot_method' : 'postrobot_method'),\n HELLO: ('postrobot_hello' : 'postrobot_hello'),\n OPEN_TUNNEL: ('postrobot_open_tunnel' : 'postrobot_open_tunnel')\n};\n\nexport const SEND_STRATEGY = {\n POST_MESSAGE: ('postrobot_post_message' : 'postrobot_post_message'),\n BRIDGE: ('postrobot_bridge' : 'postrobot_bridge'),\n GLOBAL: ('postrobot_global' : 'postrobot_global')\n};\n\nexport const BRIDGE_NAME_PREFIX = '__postrobot_bridge__';\nexport const POSTROBOT_PROXY = '__postrobot_proxy__';\n\nexport const WILDCARD = '*';\n\nexport const SERIALIZATION_TYPE = {\n CROSS_DOMAIN_ZALGO_PROMISE: ('cross_domain_zalgo_promise' : 'cross_domain_zalgo_promise'),\n CROSS_DOMAIN_FUNCTION: ('cross_domain_function' : 'cross_domain_function'),\n CROSS_DOMAIN_WINDOW: ('cross_domain_window' : 'cross_domain_window')\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { windowStore } from '../global';\n\nexport function markWindowKnown(win : CrossDomainWindowType) {\n const knownWindows = windowStore('knownWindows');\n knownWindows.set(win, true);\n}\n\nexport function isWindowKnown(win : CrossDomainWindowType) : boolean {\n const knownWindows = windowStore('knownWindows');\n return knownWindows.get(win, false);\n}\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { CustomSerializedType } from './types';\n\nexport function isSerializedType(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null && typeof item.__type__ === 'string');\n}\n\nexport function determineType(val : mixed) : $Values<typeof TYPE> | void {\n if (typeof val === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n if (val === null) {\n return TYPE.NULL;\n }\n\n if (Array.isArray(val)) {\n return TYPE.ARRAY;\n }\n\n if (typeof val === 'function') {\n return TYPE.FUNCTION;\n }\n\n if (typeof val === 'object') {\n\n if (val instanceof Error) {\n return TYPE.ERROR;\n }\n\n if (typeof val.then === 'function') {\n return TYPE.PROMISE;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object RegExp]') {\n return TYPE.REGEX;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object Date]') {\n return TYPE.DATE;\n }\n\n return TYPE.OBJECT;\n }\n\n if (typeof val === 'string') {\n return TYPE.STRING;\n }\n\n if (typeof val === 'number') {\n return TYPE.NUMBER;\n }\n\n if (typeof val === 'boolean') {\n return TYPE.BOOLEAN;\n }\n}\n\nexport function serializeType<T : string, V : mixed>(type : T, val : V) : CustomSerializedType<T, V> {\n return {\n __type__: type,\n __val__: val\n };\n}\n","/* @flow */\n\nexport const TYPE = {\n FUNCTION: ('function' : 'function'),\n ERROR: ('error' : 'error'),\n PROMISE: ('promise' : 'promise'),\n REGEX: ('regex' : 'regex'),\n DATE: ('date' : 'date'),\n ARRAY: ('array' : 'array'),\n OBJECT: ('object' : 'object'),\n STRING: ('string' : 'string'),\n NUMBER: ('number' : 'number'),\n BOOLEAN: ('boolean' : 'boolean'),\n NULL: ('null' : 'null'),\n UNDEFINED: ('undefined' : 'undefined')\n};\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { Thenable, CustomSerializedType, NativeSerializedType } from './types';\nimport { determineType, isSerializedType } from './common';\nimport {\n serializeFunction,\n serializeError, type SerializedError,\n serializePromise,\n serializeRegex, type SerializedRegex,\n serializeDate, type SerializedDate,\n serializeArray,\n serializeObject,\n serializeString,\n serializeNumber,\n serializeBoolean,\n serializeNull,\n serializeUndefined\n} from './serializers';\n\ntype NativeSerializer<V : mixed, S : mixed, T : $Values<typeof TYPE>> = (value : V, key : string) => NativeSerializedType<T, S>;\ntype CustomSerializer<V : mixed, S : mixed, T : string> = (value : V, key : string) => CustomSerializedType<T, S>;\ntype PrimitiveSerializer<V : mixed, S : mixed> = (value : V, key : string) => S;\ntype CustomOrPrimitiveSerializer<V : mixed, T : string> = CustomSerializer<V, *, T> | PrimitiveSerializer<V, *>;\ntype NativeOrCustomOrPrimitiveSerializer<V : mixed, S : mixed, T : string> = NativeSerializer<V, S, T> | CustomOrPrimitiveSerializer<V, T>;\n\ntype Serializers = {|\n function? : CustomOrPrimitiveSerializer<Function, typeof TYPE.FUNCTION>,\n error? : NativeOrCustomOrPrimitiveSerializer<Error, SerializedError, typeof TYPE.ERROR>,\n promise? : CustomOrPrimitiveSerializer<Thenable, typeof TYPE.PROMISE>,\n regex? : NativeOrCustomOrPrimitiveSerializer<RegExp, SerializedRegex, typeof TYPE.REGEX>,\n date? : NativeOrCustomOrPrimitiveSerializer<Date, SerializedDate, typeof TYPE.DATE>,\n array? : CustomOrPrimitiveSerializer<$ReadOnlyArray<mixed>, typeof TYPE.ARRAY>,\n object? : CustomOrPrimitiveSerializer<Object, typeof TYPE.OBJECT>,\n string? : CustomOrPrimitiveSerializer<string, typeof TYPE.STRING>,\n number? : CustomOrPrimitiveSerializer<number, typeof TYPE.NUMBER>,\n boolean? : CustomOrPrimitiveSerializer<boolean, typeof TYPE.BOOLEAN>,\n null? : CustomOrPrimitiveSerializer<null, typeof TYPE.NULL>,\n undefined? : CustomOrPrimitiveSerializer<void, typeof TYPE.UNDEFINED>\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 [ TYPE.UNDEFINED ]: serializeUndefined\n};\n\n// $FlowFixMe\nconst defaultSerializers : Serializers = {};\n\nexport function serialize<T : mixed>(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<typeof TYPE.ERROR, SerializedError> {\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\nimport type { Thenable } from '../types';\n\nexport type SerializedPromise = void;\n\nexport function serializePromise() : SerializedPromise {\n // pass\n}\n\nexport function deserializePromise() : Thenable {\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<typeof TYPE.REGEX, SerializedRegex> {\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<typeof TYPE.DATE, SerializedDate> {\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<T : mixed = mixed> = $ReadOnlyArray<T>;\n\nexport function serializeArray<T : mixed>(val : $ReadOnlyArray<T>) : SerializedArray<T> {\n return val;\n}\n\nexport function deserializeArray<T : mixed>(val : SerializedArray<T>) : $ReadOnlyArray<T> {\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 { NativeSerializedType } from '../types';\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\n\nexport type SerializedUndefined = void;\n\nexport function serializeUndefined(val : void) : NativeSerializedType<typeof TYPE.UNDEFINED, SerializedUndefined> {\n return serializeType(TYPE.UNDEFINED, val);\n}\n\nexport function deserializeUndefined() : void {\n // pass\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 deserializeUndefined\n} from './serializers';\n\ntype Deserializer<V : mixed, S : mixed> = (serializedValue : S, key : string) => V;\ntype PrimitiveDeserializer<V, S = V> = (serializedValue : S, key : string) => V;\n\ntype Deserializers = {\n function? : Deserializer<Function, *>,\n error? : Deserializer<Error, SerializedError>,\n promise? : Deserializer<Thenable, *>,\n regex? : Deserializer<RegExp, SerializedRegex>,\n date? : Deserializer<Date, SerializedDate>,\n array? : PrimitiveDeserializer<$ReadOnlyArray<mixed>>,\n object? : PrimitiveDeserializer<Object>,\n string? : PrimitiveDeserializer<string>,\n number? : PrimitiveDeserializer<number>,\n boolean? : PrimitiveDeserializer<boolean>,\n null? : PrimitiveDeserializer<null>,\n [string] : Deserializer<mixed, *>,\n undefined? : PrimitiveDeserializer<void>\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 [ TYPE.UNDEFINED ]: deserializeUndefined\n};\n\n// $FlowFixMe\nconst defaultDeserializers : Deserializers = {};\n\nexport function deserialize<T : mixed | null | void>(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 { 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 : ZalgoPromise<HTMLBodyElement> = 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<void> {\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 { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, getFrameByName, isWindowClosed, getDomainFromUrl, normalizeMockUrl, type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { BRIDGE_TIMEOUT, MESSAGE_NAME } from '../conf';\nimport { awaitWindowHello } from '../lib';\nimport { windowStore, globalStore } from '../global';\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { getBridgeName, documentBodyReady, registerRemoteSendMessage, registerRemoteWindow } from './common';\n\ntype WinDetails = {|\n win : CrossDomainWindowType,\n domain? : ?string,\n name? : ?string\n|};\n\nexport function listenForOpenTunnel({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) {\n const popupWindowsByName = globalStore('popupWindowsByName');\n\n on(MESSAGE_NAME.OPEN_TUNNEL, ({ source, origin, data }) => {\n const bridgePromise = globalStore('bridges').get(origin);\n\n if (!bridgePromise) {\n throw new Error(`Can not find bridge promise for domain ${ origin }`);\n }\n\n return bridgePromise.then(bridge => {\n if (source !== bridge) {\n throw new Error(`Message source does not matched registered bridge for domain ${ origin }`);\n }\n\n if (!data.name) {\n throw new Error(`Register window expected to be passed window name`);\n }\n\n if (!data.sendMessage) {\n throw new Error(`Register window expected to be passed sendMessage method`);\n }\n\n if (!popupWindowsByName.has(data.name)) {\n throw new Error(`Window with name ${ data.name } does not exist, or was not opened by this window`);\n }\n\n const getWindowDetails = () : WinDetails => {\n const winDetails = popupWindowsByName.get(data.name);\n // $FlowFixMe\n return winDetails;\n };\n\n if (!getWindowDetails().domain) {\n throw new Error(`We do not have a registered domain for window ${ data.name }`);\n }\n\n if (getWindowDetails().domain !== origin) {\n throw new Error(`Message origin ${ origin } does not matched registered window origin ${ getWindowDetails().domain || 'unknown' }`);\n }\n\n registerRemoteSendMessage(getWindowDetails().win, origin, data.sendMessage);\n\n return {\n sendMessage(message) {\n\n if (!window || window.closed) {\n return;\n }\n\n if (!getWindowDetails()) {\n return;\n }\n\n const domain = getWindowDetails().domain;\n\n if (!domain) {\n return;\n }\n\n try {\n receiveMessage({\n data: message,\n origin: domain,\n source: getWindowDetails().win\n }, { on, send });\n } catch (err) {\n ZalgoPromise.reject(err);\n }\n }\n };\n });\n });\n}\n\nfunction openBridgeFrame(name : string, url : string) : HTMLIFrameElement {\n\n const iframe = document.createElement(`iframe`);\n\n iframe.setAttribute(`name`, name);\n iframe.setAttribute(`id`, name);\n\n iframe.setAttribute(`style`, `display: none; margin: 0; padding: 0; border: 0px none; overflow: hidden;`);\n iframe.setAttribute(`frameborder`, `0`);\n iframe.setAttribute(`border`, `0`);\n iframe.setAttribute(`scrolling`, `no`);\n iframe.setAttribute(`allowTransparency`, `true`);\n\n iframe.setAttribute(`tabindex`, `-1`);\n iframe.setAttribute(`hidden`, `true`);\n iframe.setAttribute(`title`, ``);\n iframe.setAttribute(`role`, `presentation`);\n\n iframe.src = url;\n\n return iframe;\n}\n\nexport function hasBridge(url : string, domain : string) : boolean {\n const bridges = globalStore('bridges');\n return bridges.has(domain || getDomainFromUrl(url));\n}\n\nexport function openBridge(url : string, domain : string) : ZalgoPromise<CrossDomainWindowType> {\n const bridges = globalStore('bridges');\n const bridgeFrames = globalStore('bridgeFrames');\n \n domain = domain || getDomainFromUrl(url);\n \n return bridges.getOrSet(domain, () => ZalgoPromise.try(() => {\n\n if (getDomain() === domain) {\n throw new Error(`Can not open bridge on the same domain as current domain: ${ domain }`);\n }\n\n const name = getBridgeName(domain);\n const frame = getFrameByName(window, name);\n\n if (frame) {\n throw new Error(`Frame with name ${ name } already exists on page`);\n }\n\n const iframe = openBridgeFrame(name, url);\n bridgeFrames.set(domain, iframe);\n\n return documentBodyReady.then(body => {\n\n body.appendChild(iframe);\n const bridge = iframe.contentWindow;\n\n return new ZalgoPromise((resolve, reject) => {\n\n iframe.addEventListener('load', resolve);\n iframe.addEventListener('error', reject);\n\n }).then(() => {\n\n return awaitWindowHello(bridge, BRIDGE_TIMEOUT, `Bridge ${ url }`);\n\n }).then(() => {\n\n return bridge;\n });\n });\n }));\n}\n\nexport function linkWindow({ win, name, domain } : WinDetails) : WinDetails {\n const popupWindowsByName = globalStore('popupWindowsByName');\n const popupWindowsByWin = windowStore('popupWindowsByWin');\n\n for (const winName of popupWindowsByName.keys()) {\n const details = popupWindowsByName.get(winName);\n if (!details || isWindowClosed(details.win)) {\n popupWindowsByName.del(winName);\n }\n }\n\n if (isWindowClosed(win)) {\n return { win, name, domain };\n }\n\n const details = popupWindowsByWin.getOrSet(win, () : WinDetails => {\n if (!name) {\n return { win };\n }\n \n // $FlowFixMe\n return popupWindowsByName.getOrSet(name, () : WinDetails => {\n return { win, name };\n });\n });\n\n if (details.win && details.win !== win) {\n throw new Error(`Different window already linked for window: ${ name || 'undefined' }`);\n }\n\n if (name) {\n details.name = name;\n popupWindowsByName.set(name, details);\n }\n\n if (domain) {\n details.domain = domain;\n registerRemoteWindow(win);\n }\n\n popupWindowsByWin.set(win, details);\n \n return details;\n}\n\nexport function linkUrl(win : CrossDomainWindowType, url : string) {\n linkWindow({ win, domain: getDomainFromUrl(url) });\n}\n\nexport function listenForWindowOpen() {\n const windowOpen = window.open;\n\n window.open = function windowOpenWrapper(url : string, name : string, options : string, last : mixed) : mixed {\n const win = windowOpen.call(this, normalizeMockUrl(url), name, options, last);\n \n if (!win) {\n return win;\n }\n \n linkWindow({ win, name, domain: url ? getDomainFromUrl(url) : null });\n \n return win;\n };\n}\n\nexport function destroyBridges() {\n const bridges = globalStore('bridges');\n const bridgeFrames = globalStore('bridgeFrames');\n\n for (const domain of bridgeFrames.keys()) {\n const frame = bridgeFrames.get(domain);\n if (frame && frame.parentNode) {\n frame.parentNode.removeChild(frame);\n }\n }\n bridgeFrames.reset();\n bridges.reset();\n}\n","/* @flow */\n\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { listenForWindowOpen, listenForOpenTunnel } from './parent';\nimport { setupOpenTunnelToParent } from './bridge';\nimport { openTunnelToOpener } from './child';\n\nexport function setupBridge({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) {\n listenForWindowOpen();\n listenForOpenTunnel({ on, send, receiveMessage });\n setupOpenTunnelToParent({ send });\n openTunnelToOpener({ on, send, receiveMessage });\n}\n","/* @flow */\n\nimport { type ZalgoPromise } from 'zalgo-promise/src';\nimport { getParent, isWindowClosed, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { getGlobal, globalStore } from '../global';\nimport type { SendType, ResponseMessageEvent } from '../types';\n\nfunction cleanTunnelWindows() {\n const tunnelWindows = globalStore('tunnelWindows');\n\n for (const key of tunnelWindows.keys()) {\n const tunnelWindow = tunnelWindows[key];\n\n try {\n noop(tunnelWindow.source);\n } catch (err) {\n tunnelWindows.del(key);\n continue;\n }\n\n if (isWindowClosed(tunnelWindow.source)) {\n tunnelWindows.del(key);\n }\n }\n}\n\ntype TunnelWindowDataType = {|\n name : string,\n source : CrossDomainWindowType,\n canary : () => void,\n sendMessage : (message : string) => void\n|};\n\nfunction addTunnelWindow({ name, source, canary, sendMessage } : TunnelWindowDataType) : string {\n cleanTunnelWindows();\n const id = uniqueID();\n const tunnelWindows = globalStore('tunnelWindows');\n tunnelWindows.set(id, { name, source, canary, sendMessage });\n return id;\n}\n\nexport function setupOpenTunnelToParent({ send } : {| send : SendType |}) {\n getGlobal(window).openTunnelToParent = function openTunnelToParent({ name, source, canary, sendMessage } : TunnelWindowDataType) : ZalgoPromise<ResponseMessageEvent> {\n\n const tunnelWindows = globalStore('tunnelWindows');\n const parentWindow = getParent(window);\n \n if (!parentWindow) {\n throw new Error(`No parent window found to open tunnel to`);\n }\n \n const id = addTunnelWindow({ name, source, canary, sendMessage });\n \n return send(parentWindow, MESSAGE_NAME.OPEN_TUNNEL, {\n \n name,\n \n sendMessage() {\n \n const tunnelWindow = tunnelWindows.get(id);\n \n try {\n // IE gets antsy if you try to even reference a closed window\n noop(tunnelWindow && tunnelWindow.source);\n } catch (err) {\n tunnelWindows.del(id);\n return;\n }\n \n if (!tunnelWindow || !tunnelWindow.source || isWindowClosed(tunnelWindow.source)) {\n return;\n }\n \n try {\n tunnelWindow.canary();\n } catch (err) {\n return;\n }\n \n // $FlowFixMe[object-this-reference]\n tunnelWindow.sendMessage.apply(this, arguments);\n }\n \n }, { domain: WILDCARD });\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isSameDomain, getOpener, getDomain, getFrameByName, assertSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { getGlobal, windowStore } from '../global';\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { needsBridge, registerRemoteWindow, rejectRemoteSendMessage, registerRemoteSendMessage, getBridgeName } from './common';\n\nfunction awaitRemoteBridgeForWindow (win : CrossDomainWindowType) : ZalgoPromise<?CrossDomainWindowType> {\n return windowStore('remoteBridgeAwaiters').getOrSet(win, () => {\n return ZalgoPromise.try(() => {\n const frame = getFrameByName(win, getBridgeName(getDomain()));\n\n if (!frame) {\n return;\n }\n\n if (isSameDomain(frame) && getGlobal(assertSameDomain(frame))) {\n return frame;\n }\n\n return new ZalgoPromise(resolve => {\n\n let interval;\n let timeout; // eslint-disable-line prefer-const\n\n interval = setInterval(() => { // eslint-disable-line prefer-const\n if (frame && isSameDomain(frame) && getGlobal(assertSameDomain(frame))) {\n clearInterval(interval);\n clearTimeout(timeout);\n return resolve(frame);\n }\n }, 100);\n\n timeout = setTimeout(() => {\n clearInterval(interval);\n return resolve();\n }, 2000);\n });\n });\n });\n}\n\nexport function openTunnelToOpener({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n const opener = getOpener(window);\n \n if (!opener || !needsBridge({ win: opener })) {\n return;\n }\n\n registerRemoteWindow(opener);\n\n return awaitRemoteBridgeForWindow(opener).then(bridge => {\n\n if (!bridge) {\n return rejectRemoteSendMessage(opener, new Error(`Can not register with opener: no bridge found in opener`));\n }\n\n if (!window.name) {\n return rejectRemoteSendMessage(opener, new Error(`Can not register with opener: window does not have a name`));\n }\n\n return getGlobal(assertSameDomain(bridge)).openTunnelToParent({\n\n name: window.name,\n\n source: window,\n\n canary() {\n // pass\n },\n\n sendMessage(message) {\n\n try {\n noop(window);\n } catch (err) {\n return;\n }\n\n if (!window || window.closed) {\n return;\n }\n\n try {\n receiveMessage({\n data: message,\n // $FlowFixMe[object-this-reference]\n origin: this.origin,\n // $FlowFixMe[object-this-reference]\n source: this.source\n }, { on, send });\n } catch (err) {\n ZalgoPromise.reject(err);\n }\n }\n\n }).then(({ source, origin, data }) => {\n\n if (source !== opener) {\n throw new Error(`Source does not match opener`);\n }\n\n registerRemoteSendMessage(source, origin, data.sendMessage);\n\n }).catch(err => {\n\n rejectRemoteSendMessage(opener, err);\n throw err;\n });\n });\n });\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, submitForm } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE, METHOD } 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 SetLocationOptions = {|\n method? : $Values<typeof METHOD>,\n body? : {|\n [string] : string | boolean\n |}\n|};\n\ntype SerializedWindowType = {|\n id : string,\n getType : () => ZalgoPromise<$Values<typeof WINDOW_TYPE>>,\n close : () => ZalgoPromise<void>,\n focus : () => ZalgoPromise<void>,\n isClosed : () => ZalgoPromise<boolean>,\n setLocation : (url : string, opts? : SetLocationOptions) => ZalgoPromise<void>,\n getName : () => ZalgoPromise<?string>,\n setName : (string) => ZalgoPromise<void>,\n getInstanceID : () => ZalgoPromise<string>\n|};\n\nfunction getSerializedWindow(winPromise : ZalgoPromise<CrossDomainWindowType>, { 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 const 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\n const getDefaultSetLocationOptions = () => {\n // $FlowFixMe\n return {};\n };\n\n const setLocation = (href : string, opts? : SetLocationOptions = getDefaultSetLocationOptions()) => winPromise.then(win => {\n const domain = `${ window.location.protocol }//${ window.location.host }`;\n const { method = METHOD.GET, body } = opts;\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 (method === METHOD.POST) {\n return getName().then(name => {\n if (!name) {\n throw new Error(`Can not post to window without target name`);\n }\n\n submitForm({\n url: href,\n target: name,\n method,\n body\n });\n });\n } else if (method === METHOD.GET) {\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 } else {\n throw new Error(`Unsupported method: ${ method }`);\n }\n });\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,\n focus: () => winPromise.then(win => {\n win.focus();\n }),\n isClosed: () => winPromise.then(win => {\n return isWindowClosed(win);\n }),\n setLocation,\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<CrossDomainWindowType>\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<typeof WINDOW_TYPE>> {\n return this.serializedWindow.getType();\n }\n\n isPopup() : ZalgoPromise<boolean> {\n return this.getType().then(type => {\n return type === WINDOW_TYPE.POPUP;\n });\n }\n\n setLocation(href : string, opts? : SetLocationOptions) : ZalgoPromise<ProxyWindow> {\n return this.serializedWindow.setLocation(href, opts).then(() => this);\n }\n\n getName() : ZalgoPromise<?string> {\n return this.serializedWindow.getName();\n }\n\n setName(name : string) : ZalgoPromise<ProxyWindow> {\n return this.serializedWindow.setName(name).then(() => this);\n }\n\n close() : ZalgoPromise<ProxyWindow> {\n return this.serializedWindow.close().then(() => this);\n }\n\n focus() : ZalgoPromise<ProxyWindow> {\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, 'noopener');\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<boolean> {\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<CrossDomainWindowType> {\n return this.actualWindowPromise;\n }\n\n matchWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise<boolean> {\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<string> {\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<typeof SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW, SerializedWindowType>;\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 { 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<mixed> = []) : 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<typeof SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION, {|\n id : string,\n name : string\n|}>;\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype SerializableFunction<T> = {\n () : ZalgoPromise<T> | T,\n __id__? : string,\n __name__? : string\n};\n\nexport function serializeFunction<T>(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : SerializableFunction<T>, 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<T>(source : CrossDomainWindowType | ProxyWindow, origin : string, { id, name } : {| id : string, name : string |}, { send } : {| send : SendType |}) : (...args : $ReadOnlyArray<mixed>) => ZalgoPromise<T> {\n const getDeserializedFunction = (opts? : Object = {}) => {\n function crossDomainFunctionWrapper<X : mixed>() : ZalgoPromise<X> {\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 // $FlowFixMe[method-unbinding]\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<T : mixed>(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<T : mixed>(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<typeof SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE, {|\n then : SerializedFunction\n|}>;\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<T>(source : CrossDomainWindowType | ProxyWindow, origin : string, { then } : {| then : Function |}) : ZalgoPromise<T> {\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\ntype SendStrategies = {|\n [$Values<typeof SEND_STRATEGY>] : (CrossDomainWindowType, string, string) => void\n|};\n\nexport const SEND_MESSAGE_STRATEGIES : SendStrategies = {};\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, getGlobalKey } 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<Message>) : PackedMessages {\n return {\n [ getGlobalKey() ]: messages\n };\n}\n\nexport function sendMessage(win : CrossDomainWindowType, domain : string, message : Message, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise<void> {\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, noop } from 'belter/src';\n\nimport { getWildcard, type WildCard, globalStore, windowStore } from '../global';\nimport { WILDCARD } from '../conf';\nimport { ProxyWindow } from '../serialize/window';\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<mixed>),\n handleError : (err : mixed) => void\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\n// eslint-disable-next-line complexity\nexport function addRequestListener({ name, win: winCandidate, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard | ProxyWindow), 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 // $FlowFixMe\n if (winCandidate && winCandidate !== WILDCARD && ProxyWindow.isProxyWindow(winCandidate)) {\n // $FlowFixMe\n const proxyWin : ProxyWindow = winCandidate;\n\n const requestListenerPromise = proxyWin.awaitWindow().then(actualWin => {\n return addRequestListener({ name, win: actualWin, domain }, listener);\n });\n\n return {\n cancel: () => {\n requestListenerPromise.then(requestListener => requestListener.cancel(), noop);\n }\n };\n }\n\n // $FlowFixMe\n let win : ?(CrossDomainWindowType | WildCard) = winCandidate;\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 const strDomain = domain.toString();\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 winNameListeners = requestListeners.getOrSet(win, () => ({}));\n const winNameDomainListeners = getOrSet(winNameListeners, name, () => ({}));\n\n let winNameDomainRegexListeners;\n let winNameDomainRegexListener;\n\n if (isRegex(domain)) {\n winNameDomainRegexListeners = getOrSet(winNameDomainListeners, __DOMAIN_REGEX__, () => []);\n winNameDomainRegexListener = { regex: domain, listener };\n winNameDomainRegexListeners.push(winNameDomainRegexListener);\n } else {\n winNameDomainListeners[strDomain] = listener;\n }\n\n return {\n cancel() {\n delete winNameDomainListeners[strDomain];\n\n if (winNameDomainRegexListener) {\n winNameDomainRegexListeners.splice(winNameDomainRegexListeners.indexOf(winNameDomainRegexListener, 1));\n\n if (!winNameDomainRegexListeners.length) {\n delete winNameDomainListeners[__DOMAIN_REGEX__];\n }\n }\n\n if (!Object.keys(winNameDomainListeners).length) {\n delete winNameListeners[name];\n }\n\n if (win && !Object.keys(winNameListeners).length) {\n requestListeners.del(win);\n }\n }\n };\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 function handleRequest(source : CrossDomainWindowType, origin : string, message : RequestMessage, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise<void> {\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<void> {\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<typeof MESSAGE_ACK>, data : ?Object, error : ?mixed) : ZalgoPromise<void> {\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 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\nexport function handleAck(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\nexport function handleResponse(source : CrossDomainWindowType, origin : string, message : ResponseMessage) : void | ZalgoPromise<void> {\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","/* @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, getGlobalKey } from '../../global';\nimport type { OnType, SendType, MessageEvent, CancelableType } from '../../types';\n\nimport { handleRequest, handleResponse, handleAck } from './types';\n\nfunction deserializeMessages(message : string, source : CrossDomainWindowType, origin : string, { on, send } : {| on : OnType, send : SendType |}) : ?$ReadOnlyArray<Message> {\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[getGlobalKey()];\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 if (isWindowClosed(source)) {\n return;\n }\n\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 handleRequest(source, origin, message, { on, send });\n } else if (message.type === MESSAGE_TYPE.RESPONSE) {\n handleResponse(source, origin, message);\n } else if (message.type === MESSAGE_TYPE.ACK) {\n handleAck(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 } 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 const winOrProxyWin = options.window;\n const domain = options.domain || WILDCARD;\n\n const successHandler = handler || options.handler;\n const errorHandler = options.errorHandler || (err => {\n throw err;\n });\n\n const requestListener = addRequestListener({ name, win: winOrProxyWin, domain }, {\n handler: successHandler,\n handleError: errorHandler\n });\n\n return {\n cancel() {\n requestListener.cancel();\n }\n };\n}\n\ntype CancelableZalgoPromise<T> = ZalgoPromise<T> & {|\n cancel : () => void\n|};\n\nexport function once(name : string, options? : ServerOptionsType | HandlerType, handler? : HandlerType) : CancelableZalgoPromise<{| 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 // $FlowFixMe\n promise.cancel = listener.cancel;\n\n // $FlowFixMe\n return promise;\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 { 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 { ProxyWindow } from '../serialize/window';\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<string> {\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 = (winOrProxyWin, 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 return ProxyWindow.toProxyWindow(winOrProxyWin, { send }).awaitWindow().then(win => {\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};\n","/* @flow */\n\nimport { setup } from './setup';\nimport { setupBridge, openBridge, linkWindow, linkUrl, isBridge, needsBridge, needsBridgeForBrowser, hasBridge,\n needsBridgeForWin, needsBridgeForDomain, destroyBridges } from './bridge';\n\nexport { ZalgoPromise as Promise } from 'zalgo-promise/src';\n\nexport * from './types';\nexport { ProxyWindow } from './serialize';\nexport { setup, destroy, serializeMessage, deserializeMessage, createProxyWindow, toProxyWindow } from './setup';\nexport { on, once, send } from './public';\nexport { markWindowKnown } from './lib';\nexport { cleanUpWindow } from './clean';\n\n// $FlowFixMe\nexport let bridge;\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n bridge = { setupBridge, openBridge, linkWindow, linkUrl, isBridge, needsBridge,\n needsBridgeForBrowser, hasBridge, needsBridgeForWin, needsBridgeForDomain, destroyBridges };\n}\n\nif (__POST_ROBOT__.__AUTO_SETUP__) {\n setup();\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 : number = __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<T>(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T) : string {\n return internalSerializeMessage(destination, domain, obj, { on, send });\n}\n\nexport function deserializeMessage<T : mixed>(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 { 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\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray<mixed>) {\n // pass\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray<CrossDomainWindowType> {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray<CrossDomainWindowType> {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray<CrossDomainWindowType> {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray<CrossDomainWindowType> {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray<CrossDomainWindowType> {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf<T>(collection : $ReadOnlyArray<T>, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray<CrossDomainWindowType> {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport 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\nimport { isSameDomain, type CrossDomainWindowType } from '@krakenjs/cross-domain-utils/src';\nimport { getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__ZOID__.__SCRIPT_NAMESPACE__) {\n return `${ __ZOID__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __ZOID__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal<T>(win : CrossDomainWindowType) : T {\n const globalKey = getGlobalKey();\n\n if (!isSameDomain(win)) {\n throw new Error(`Can not get global for window on different domain`);\n }\n\n if (!win[globalKey]) {\n win[globalKey] = {};\n }\n\n return win[globalKey];\n}\n\nexport function tryGlobal<T, R>(win : CrossDomainWindowType, handler : (T) => R) : ?R {\n try {\n return handler(getGlobal(win));\n } catch (err) {\n // pass\n }\n}\n\nexport function destroyGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeMessage, deserializeMessage, toProxyWindow, type ProxyWindow } from 'post-robot/src';\nimport { uniqueID, base64encode, base64decode } from 'belter/src';\nimport type { CrossDomainWindowType, DomainMatcher } from '@krakenjs/cross-domain-utils/src';\n\nimport { getGlobal } from './global';\n\nexport type ProxyObject<T> = {|\n get : () => ZalgoPromise<T>\n|};\n\nexport function getProxyObject<T>(obj : T) : ProxyObject<T> {\n return {\n get() : ZalgoPromise<T> {\n return ZalgoPromise.try(() => {\n // $FlowFixMe[object-this-reference]\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\nexport function basicSerialize<T>(data : T) : string {\n return base64encode(JSON.stringify(data));\n}\n\nexport function basicDeserialize<T>(serializedData : string) : T {\n return JSON.parse(base64decode(serializedData));\n}\n\nexport const REFERENCE_TYPE = {\n UID: ('uid' : 'uid'),\n RAW: ('raw' : 'raw')\n};\n\nexport type UIDReferenceType = {| type : typeof REFERENCE_TYPE.UID, uid : string |};\nexport type RawReferenceType<T> = {| type : typeof REFERENCE_TYPE.RAW, val : T |};\n\nexport type ReferenceType<T> =\n UIDReferenceType |\n RawReferenceType<T>;\n\nexport function getUIDRefStore<T>(win : CrossDomainWindowType) : { [string] : T } {\n const global = getGlobal(win);\n global.references = global.references || {};\n return global.references;\n}\n\nexport function getUIDRef<T>(val : T) : ReferenceType<T> {\n const uid = uniqueID();\n const references = getUIDRefStore(window);\n references[uid] = val;\n return { type: REFERENCE_TYPE.UID, uid };\n}\n\nexport function getRawRef<T>(val : T) : ReferenceType<T> {\n return { type: REFERENCE_TYPE.RAW, val };\n}\n\nexport function getRefValue<T>(win : CrossDomainWindowType, ref : ReferenceType<T>) : T {\n if (ref.type === REFERENCE_TYPE.RAW) {\n return ref.val;\n }\n\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n return references[ref.uid];\n }\n\n throw new Error(`Unsupported ref type: ${ ref.type }`);\n}\n\nexport function cleanupRef<T>(win : CrossDomainWindowType, ref : ReferenceType<T>) {\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n delete references[ref.uid];\n }\n}\n\ntype Message<T, M> = {|\n sender : {|\n domain : string\n |},\n metaData : M,\n reference : ReferenceType<T>\n|};\n\ntype CrossDomainSerializeOptions<T, M> = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string\n |},\n receiver : {|\n win : ProxyWindow | CrossDomainWindowType,\n domain : DomainMatcher\n |},\n passByReference? : boolean,\n basic? : boolean\n|};\n\ntype CrossDomainSerializedMessage = {|\n serializedData : string,\n cleanReference : () => void\n|};\n\nexport function crossDomainSerialize<T, M>({ data, metaData, sender, receiver, passByReference = false, basic = false } : CrossDomainSerializeOptions<T, M>) : CrossDomainSerializedMessage {\n const proxyWin = toProxyWindow(receiver.win);\n const serializedMessage = basic\n ? JSON.stringify(data)\n : serializeMessage(proxyWin, receiver.domain, data);\n\n const reference = passByReference\n ? getUIDRef(serializedMessage)\n : getRawRef(serializedMessage);\n\n const message : Message<string, M> = {\n sender: {\n domain: sender.domain\n },\n metaData,\n reference\n };\n\n const cleanReference = () => {\n cleanupRef(window, reference);\n };\n\n return {\n serializedData: basicSerialize(message),\n cleanReference\n };\n}\n\ntype CrossDomainDeserializeOptions<M> = {|\n data : string,\n sender : {|\n win : CrossDomainWindowType | ({| metaData : M |}) => CrossDomainWindowType,\n domain? : string | ({| metaData : M |}) => string\n |},\n basic? : boolean\n|};\n\ntype CrossDomainDeserializedMessage<T, M> = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n reference : ReferenceType<string>\n|};\n\nexport function crossDomainDeserialize<T, M>({ data, sender, basic = false } : CrossDomainDeserializeOptions<M>) : CrossDomainDeserializedMessage<T, M> {\n const message : Message<string, M> = basicDeserialize(data);\n\n const { reference, metaData } = message;\n\n let win;\n if (typeof sender.win === 'function') {\n win = sender.win({ metaData });\n } else {\n win = sender.win;\n }\n\n let domain;\n if (typeof sender.domain === 'function') {\n domain = sender.domain({ metaData });\n } else if (typeof sender.domain === 'string') {\n domain = sender.domain;\n } else {\n domain = message.sender.domain;\n }\n\n const serializedData = getRefValue(win, reference);\n const deserializedData = basic\n ? JSON.parse(serializedData)\n : deserializeMessage(win, domain, serializedData);\n \n return {\n data: deserializedData,\n metaData,\n sender: { win, domain },\n reference\n };\n}\n","/* @flow */\n\nimport { WINDOW_TYPE } from '@krakenjs/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' : 'string'),\n OBJECT: ('object' : 'object'),\n FUNCTION: ('function' : 'function'),\n BOOLEAN: ('boolean' : 'boolean'),\n NUMBER: ('number' : 'number'),\n ARRAY: ('array' : 'array')\n};\n\nexport const WINDOW_REFERENCE = {\n OPENER: ('opener' : 'opener'),\n PARENT: ('parent' : 'parent'),\n GLOBAL: ('global' : 'global'),\n NAME: ('name' : 'name')\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\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { assertExists, memoize } from 'belter/src';\nimport { isSameDomain, getOpener, getNthParentFromTop, getAncestor, getAllFramesInWindow, getParent, isTop,\n findFrameByName, getDomain, assertSameDomain, type CrossDomainWindowType, getDistanceFromTop } from '@krakenjs/cross-domain-utils/src';\n\nimport { ZOID, WINDOW_REFERENCE } from '../constants';\nimport type { InitialChildPayload, WindowRef } from '../parent';\n\nimport { crossDomainDeserialize, crossDomainSerialize, REFERENCE_TYPE, type ReferenceType } from './serialize';\nimport { tryGlobal } from './global';\n\nfunction getWindowByRef(windowRef : WindowRef) : CrossDomainWindowType {\n if (windowRef.type === WINDOW_REFERENCE.OPENER) {\n return assertExists('opener', getOpener(window));\n\n } else if (windowRef.type === WINDOW_REFERENCE.PARENT && typeof windowRef.distance === 'number') {\n return assertExists('parent', getNthParentFromTop(window, windowRef.distance));\n\n } else if (windowRef.type === WINDOW_REFERENCE.GLOBAL && windowRef.uid && typeof windowRef.uid === 'string') {\n const { uid } = windowRef;\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 win = tryGlobal(frame, global => global.windows && global.windows[uid]);\n\n if (win) {\n return win;\n }\n }\n }\n } else if (windowRef.type === WINDOW_REFERENCE.NAME) {\n const { name } = windowRef;\n return assertExists('namedWindow', findFrameByName(assertExists('ancestor', getAncestor(window)), name));\n }\n\n throw new Error(`Unable to find ${ windowRef.type } parent component window`);\n}\n\nexport function buildChildWindowName({ name, serializedPayload } : {| name : string, serializedPayload : string |}) : string {\n return `__${ ZOID }__${ name }__${ serializedPayload }__`;\n}\n\nfunction parseWindowName(windowName : string) : {| name : string, serializedInitialPayload : string |} {\n if (!windowName) {\n throw new Error(`No window name`);\n }\n\n const [ , zoidcomp, name, serializedInitialPayload ] = 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 (!serializedInitialPayload) {\n throw new Error(`Expected serialized payload ref`);\n }\n\n return { name, serializedInitialPayload };\n}\n\nexport type InitialParentPayload<P, X> = {|\n parent : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n payload : InitialChildPayload<P, X>,\n reference : ReferenceType<string>\n|};\n\nconst parseInitialParentPayload = memoize(<P, X>(windowName : string) : InitialParentPayload<P, X> => {\n const { serializedInitialPayload } = parseWindowName(windowName);\n\n const { data: payload, sender: parent, reference } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: ({ metaData: { windowRef } }) => getWindowByRef(windowRef)\n }\n });\n\n return {\n parent,\n payload,\n reference\n };\n});\n\nexport function getInitialParentPayload<P, X>() : InitialParentPayload<P, X> {\n return parseInitialParentPayload(window.name);\n}\n\nexport function isChildComponentWindow(name : string) : boolean {\n try {\n return parseWindowName(window.name).name === name;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getWindowRef(targetWindow : CrossDomainWindowType, currentWindow? : CrossDomainWindowType = window) : ?WindowRef {\n if (targetWindow === getParent(currentWindow)) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(targetWindow) };\n }\n\n if (targetWindow === getOpener(currentWindow)) {\n return { type: WINDOW_REFERENCE.OPENER };\n }\n\n if (isSameDomain(targetWindow) && !isTop(targetWindow)) {\n const windowName = assertSameDomain(targetWindow).name;\n if (windowName) {\n return { type: WINDOW_REFERENCE.NAME, name: windowName };\n }\n }\n}\n\ntype UpdateChildWindowNameWithRefOptions = {|\n componentName : string,\n parentComponentWindow : CrossDomainWindowType\n|};\n\nexport function updateChildWindowNameWithRef({ componentName, parentComponentWindow } : UpdateChildWindowNameWithRefOptions) {\n const { serializedInitialPayload } = parseWindowName(window.name);\n\n const { data, sender, reference, metaData } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: parentComponentWindow\n },\n basic: true\n });\n\n if (reference.type === REFERENCE_TYPE.UID || metaData.windowRef.type === WINDOW_REFERENCE.GLOBAL) {\n const windowRef = getWindowRef(parentComponentWindow);\n\n const { serializedData: serializedPayload } = crossDomainSerialize({\n data,\n metaData: {\n windowRef\n },\n sender: {\n domain: sender.domain\n },\n receiver: {\n win: window,\n domain: getDomain()\n },\n basic: true\n });\n\n window.name = buildChildWindowName({\n name: componentName,\n serializedPayload\n });\n }\n}\n","/* @flow */\n\nimport { getDomain, isSameDomain, type CrossDomainWindowType } from '@krakenjs/cross-domain-utils/src';\n\nimport type { PropsDefinitionType, PropsType, ChildPropsType } from '../component/props';\n\nimport type { ChildHelpers } from './index';\n\n// $FlowFixMe\nexport function normalizeChildProp<P, T, X>(propsDef : PropsDefinitionType<P, X>, props : PropsType<P>, key : string, value : ?T, helpers : ChildHelpers<P, X>) : ?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 { uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings } = helpers;\n const decoratedValue = prop.childDecorate({ value, uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings });\n\n // $FlowFixMe\n return decoratedValue;\n }\n\n return value;\n}\n\n// eslint-disable-next-line max-params\nexport function normalizeChildProps<P, X>(parentComponentWindow : CrossDomainWindowType, propsDef : PropsDefinitionType<P, X>, props : PropsType<P>, origin : string, helpers : ChildHelpers<P, X>, isUpdate : boolean = false) : ChildPropsType<P, X> {\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/* eslint max-lines: 0 */\n\nimport { isSameDomain, matchDomain, getAllFramesInWindow, type CrossDomainWindowType,\n onCloseWindow, assertSameDomain } from '@krakenjs/cross-domain-utils/src';\nimport { markWindowKnown, type CrossDomainFunctionType } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { extend, onResize, elementReady, noop } from 'belter/src';\n\nimport { getGlobal, tryGlobal, getInitialParentPayload, updateChildWindowNameWithRef } from '../lib';\nimport { CONTEXT } from '../constants';\nimport type { NormalizedComponentOptionsType, getSiblingsPropType } from '../component';\nimport type { PropsType, ChildPropsType } from '../component/props';\nimport type { StringMatcherType } from '../types';\n\nimport { normalizeChildProps } from './props';\n\nexport type ChildExportsType<P> = {|\n updateProps : CrossDomainFunctionType<[ PropsType<P> ], void>,\n close : CrossDomainFunctionType<[], void>\n|};\n\nexport type ChildHelpers<P, X> = {|\n uid : string,\n tag : string,\n close : () => ZalgoPromise<void>,\n focus : () => ZalgoPromise<void>,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise<void>,\n onError : (mixed) => ZalgoPromise<void>,\n onProps : ((PropsType<P>) => void) => {| cancel : () => void |},\n getParent : () => CrossDomainWindowType,\n getParentDomain : () => string,\n show : () => ZalgoPromise<void>,\n hide : () => ZalgoPromise<void>,\n export : (X) => ZalgoPromise<void>,\n getSiblings : getSiblingsPropType\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<void> {\n return ZalgoPromise.try(() => {\n window.focus();\n });\n}\n\nfunction destroy() : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n window.close();\n });\n}\n\nexport type ChildComponent<P, X> = {|\n getProps : () => ChildPropsType<P, X>,\n init : () => ZalgoPromise<void>\n|};\n\nexport function childComponent<P, X, C>(options : NormalizedComponentOptionsType<P, X, C>) : ChildComponent<P, X> {\n const { tag, propsDef, autoResize, allowedParentDomains } = options;\n\n const onPropHandlers = [];\n\n const { parent, payload } = getInitialParentPayload();\n const { win: parentComponentWindow, domain: parentDomain } = parent;\n\n let props : ChildPropsType<P, X>;\n const exportsPromise = new ZalgoPromise();\n\n const { version, uid, exports: parentExports, context, props: initialProps } = payload;\n\n if (version !== __ZOID__.__VERSION__) {\n throw new Error(`Parent window has zoid version ${ version }, child window has version ${ __ZOID__.__VERSION__ }`);\n }\n\n const { show, hide, close, onError, checkClose, export: parentExport, resize: parentResize, init: parentInit } = parentExports;\n\n const getParent = () => parentComponentWindow;\n const getParentDomain = () => parentDomain;\n \n const onProps = (handler : Function) => {\n onPropHandlers.push(handler);\n return {\n cancel: () => {\n onPropHandlers.splice(onPropHandlers.indexOf(handler), 1);\n }\n };\n };\n\n const resize = ({ width, height } : {| width : ?number, height : ?number |}) : ZalgoPromise<void> => {\n return parentResize.fireAndForget({ width, height });\n };\n\n const xport = (xports : X) : ZalgoPromise<void> => {\n exportsPromise.resolve(xports);\n return parentExport(xports);\n };\n\n const getSiblings = ({ anyParent } = {}) => {\n const result = [];\n const currentParent = props.parent;\n\n if (typeof anyParent === 'undefined') {\n anyParent = !currentParent;\n }\n\n if (!anyParent && !currentParent) {\n throw new Error(`No parent found for ${ tag } child`);\n }\n\n for (const win of getAllFramesInWindow(window)) {\n if (!isSameDomain(win)) {\n continue;\n }\n\n const xprops : ChildPropsType<mixed, mixed> = assertSameDomain(win).xprops;\n\n if (!xprops || getParent() !== xprops.getParent()) {\n continue;\n }\n\n const winParent = xprops.parent;\n\n if (!anyParent && currentParent) {\n if (!winParent || winParent.uid !== currentParent.uid) {\n continue;\n }\n }\n\n const xports = tryGlobal(win, global => global.exports);\n\n result.push({\n props: xprops,\n exports: xports\n });\n }\n\n return result;\n };\n\n const getHelpers = () : ChildHelpers<P, X> => {\n return {\n tag, show, hide, close, focus, onError, resize, getSiblings,\n onProps, getParent, getParentDomain, uid, export: xport\n };\n };\n\n const watchForClose = () => {\n window.addEventListener('beforeunload', () => {\n checkClose.fireAndForget();\n });\n\n window.addEventListener('unload', () => {\n checkClose.fireAndForget();\n });\n\n onCloseWindow(parentComponentWindow, () => {\n destroy();\n });\n };\n\n const setProps = (newProps : PropsType<P>, 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 = () : ZalgoPromise<{| width : boolean, height : boolean, element : ?HTMLElement |}> => {\n const { width = false, height = false, element: elementRef = 'body' } = autoResize;\n return elementReady(elementRef).catch(noop).then(element => {\n return { width, height, element };\n });\n };\n\n const watchForResize = () : ?ZalgoPromise<void> => {\n return getAutoResize().then(({ width, height, element }) => {\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<P>)) : ZalgoPromise<void> => {\n return ZalgoPromise.try(() => setProps(newProps, parentDomain, true));\n };\n\n const init = () => {\n return ZalgoPromise.try(() => {\n if (isSameDomain(parentComponentWindow)) {\n updateChildWindowNameWithRef({\n componentName: options.name,\n parentComponentWindow\n });\n }\n\n getGlobal(window).exports = options.exports({\n getExports: () => exportsPromise\n });\n\n checkParentDomain(allowedParentDomains, parentDomain);\n markWindowKnown(parentComponentWindow);\n watchForClose();\n\n return parentInit({ 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 } else {\n setProps(initialProps, parentDomain);\n return props;\n }\n };\n\n return {\n init,\n getProps\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 '@krakenjs/cross-domain-utils/src';\nimport { ProxyWindow, toProxyWindow } from 'post-robot/src';\n\nimport type { CssDimensionsType } from '../types';\nimport { PROP_SERIALIZATION, PROP_TYPE } from '../constants';\n\nexport type EventHandlerType<T> = (T) => void | ZalgoPromise<void>;\nexport type Sibling = {|\n props : mixed,\n exports : mixed\n|};\n\nexport type timeoutPropType = number;\nexport type windowPropType = CrossDomainWindowType | ProxyWindow;\nexport type cspNoncePropType = string;\nexport type uidPropType = string;\nexport type tagPropType = string;\nexport type closePropType = () => ZalgoPromise<void>;\nexport type focusPropType = () => ZalgoPromise<void>;\nexport type showPropType = () => ZalgoPromise<void>;\nexport type exportPropType<X> = (X) => ZalgoPromise<void>;\nexport type getSiblingsPropType = (opts? : {| anyParent? : boolean |}) => $ReadOnlyArray<Sibling>;\nexport type hidePropType = () => ZalgoPromise<void>;\nexport type resizePropType = ({| width : ?number, height : ?number |}) => ZalgoPromise<void>;\nexport type getParentPropType = () => CrossDomainWindowType;\nexport type getParentDomainPropType = () => string;\n\nexport type onDisplayPropType = EventHandlerType<void>;\nexport type onRenderedPropType = EventHandlerType<void>;\nexport type onRenderPropType = EventHandlerType<void>;\nexport type onClosePropType = EventHandlerType<void>;\nexport type onDestroyPropType = EventHandlerType<void>;\nexport type onResizePropType = EventHandlerType<void>;\nexport type onFocusPropType = EventHandlerType<void>;\nexport type onErrorPropType = EventHandlerType<mixed>;\nexport type onPropsPropType<P> = ((PropsType<P>) => void) => {| cancel : () => void |}; // eslint-disable-line no-use-before-define\n\nexport type ParentPropType<P, X> = {|\n uid : string,\n // eslint-disable-next-line no-use-before-define\n props : PropsType<P>,\n export : exportPropType<X>\n|};\n\nexport type PropsInputType<P> = {|\n parent? : ParentPropType<mixed, mixed>,\n \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<P>,\n\n ...P\n|};\n\nexport type PropsType<P> = {|\n timeout? : timeoutPropType,\n window? : ?windowPropType,\n cspNonce? : ?cspNoncePropType,\n dimensions : CssDimensionsType,\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<P>,\n \n ...P\n|};\n\ntype onErrorChildPropType = (mixed) => ZalgoPromise<void>;\n\nexport type ChildPropsType<P, X> = {|\n ...PropsType<P>,\n\n parent? : ParentPropType<mixed, mixed>,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType<X>,\n getParent : getParentPropType,\n getParentDomain : getParentDomainPropType,\n resize : resizePropType,\n onError : onErrorChildPropType,\n onProps : onPropsPropType<P>,\n getSiblings : getSiblingsPropType\n|};\n\nexport type PropDefinitionType<T, P, S : $Values<typeof PROP_TYPE>, X> = {|\n type : S,\n alias? : string,\n value? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise<void>,\n focus : () => ZalgoPromise<void>,\n onError : (mixed) => ZalgoPromise<void>,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n default? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise<void>,\n focus : () => ZalgoPromise<void>,\n onError : (mixed) => ZalgoPromise<void>,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n decorate? : ({|\n value : T,\n props : PropsType<P>,\n state : Object,\n close : () => ZalgoPromise<void>,\n focus : () => ZalgoPromise<void>,\n onError : (mixed) => ZalgoPromise<void>,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => T,\n childDecorate? : ({|\n value : ?T,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType<P>,\n resize : resizePropType,\n getParentDomain : getParentDomainPropType,\n getParent : getParentPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType<X>,\n getSiblings : getSiblingsPropType\n |}) => ?T,\n required? : boolean,\n queryParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise<string>),\n bodyParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise<string>),\n // eslint-disable-next-line no-undef\n queryValue? : <R>({| value : T |}) => (ZalgoPromise<R> | R | string),\n // eslint-disable-next-line no-undef\n bodyValue? : <R>({| value : T |}) => (ZalgoPromise<R> | R | string),\n sendToChild? : boolean,\n allowDelegate? : boolean,\n validate? : ({| value : T, props : PropsType<P> |}) => void,\n sameDomain? : boolean,\n serialization? : $Values<typeof PROP_SERIALIZATION>\n|};\n\nexport type BOOLEAN_DEFINITION_TYPE = typeof PROP_TYPE.BOOLEAN;\nexport type STRING_DEFINITION_TYPE = typeof PROP_TYPE.STRING;\nexport type NUMBER_DEFINITION_TYPE = typeof PROP_TYPE.NUMBER;\nexport type FUNCTION_DEFINITION_TYPE = typeof PROP_TYPE.FUNCTION;\nexport type ARRAY_DEFINITION_TYPE = typeof PROP_TYPE.ARRAY;\nexport type OBJECT_DEFINITION_TYPE = typeof PROP_TYPE.OBJECT;\n\nexport type DEFINITION_TYPE =\n BOOLEAN_DEFINITION_TYPE | STRING_DEFINITION_TYPE | NUMBER_DEFINITION_TYPE |\n FUNCTION_DEFINITION_TYPE | ARRAY_DEFINITION_TYPE | OBJECT_DEFINITION_TYPE;\n\n\nexport type BooleanPropDefinitionType<T : boolean, P, X> = PropDefinitionType<T, P, BOOLEAN_DEFINITION_TYPE, X>;\nexport type StringPropDefinitionType<T : string, P, X> = PropDefinitionType<T, P, STRING_DEFINITION_TYPE, X>;\nexport type NumberPropDefinitionType<T : number, P, X> = PropDefinitionType<T, P, NUMBER_DEFINITION_TYPE, X>;\nexport type FunctionPropDefinitionType<T : Function, P, X> = PropDefinitionType<T, P, FUNCTION_DEFINITION_TYPE, X>;\nexport type ArrayPropDefinitionType<T : Array<*> | $ReadOnlyArray<*>, P, X> = PropDefinitionType<T, P, ARRAY_DEFINITION_TYPE, X>; // eslint-disable-line flowtype/no-mutable-array\nexport type ObjectPropDefinitionType<T : Object, P, X> = PropDefinitionType<T, P, OBJECT_DEFINITION_TYPE, X>;\n\nexport type MixedPropDefinitionType<P, X> =\n BooleanPropDefinitionType<*, P, X> |\n StringPropDefinitionType<*, P, X> |\n NumberPropDefinitionType<*, P, X> |\n FunctionPropDefinitionType<*, P, X> |\n ObjectPropDefinitionType<*, P, X> |\n ArrayPropDefinitionType<*, P, X>;\n\nexport type UserPropsDefinitionType<P, X> = {|\n [string] : MixedPropDefinitionType<P, X>\n|};\n\nexport type BuiltInPropsDefinitionType<P, X> = {|\n timeout : NumberPropDefinitionType<timeoutPropType, P, X>,\n window : ObjectPropDefinitionType<windowPropType, P, X>,\n close : FunctionPropDefinitionType<closePropType, P, X>,\n focus : FunctionPropDefinitionType<focusPropType, P, X>,\n resize : FunctionPropDefinitionType<resizePropType, P, X>,\n uid : StringPropDefinitionType<uidPropType, P, X>,\n tag : StringPropDefinitionType<tagPropType, P, X>,\n cspNonce : StringPropDefinitionType<cspNoncePropType, P, X>,\n getParent : FunctionPropDefinitionType<getParentPropType, P, X>,\n getParentDomain : FunctionPropDefinitionType<getParentDomainPropType, P, X>,\n hide : FunctionPropDefinitionType<hidePropType, P, X>,\n show : FunctionPropDefinitionType<showPropType, P, X>,\n export : FunctionPropDefinitionType<exportPropType<X>, P, X>,\n getSiblings : FunctionPropDefinitionType<getSiblingsPropType, P, X>,\n\n onDisplay : FunctionPropDefinitionType<onDisplayPropType, P, X>,\n onRendered : FunctionPropDefinitionType<onRenderedPropType, P, X>,\n onRender : FunctionPropDefinitionType<onRenderPropType, P, X>,\n onClose : FunctionPropDefinitionType<onClosePropType, P, X>,\n onDestroy : FunctionPropDefinitionType<onDestroyPropType, P, X>,\n onResize : FunctionPropDefinitionType<onClosePropType, P, X>,\n onFocus : FunctionPropDefinitionType<onFocusPropType, P, X>,\n onError : FunctionPropDefinitionType<onErrorPropType, P, X>,\n onProps : FunctionPropDefinitionType<onPropsPropType<P>, P, X>\n|};\n\nexport type PropsDefinitionType<P, X> = {|\n ...BuiltInPropsDefinitionType<P, X>,\n [ string ] : MixedPropDefinitionType<P, X>\n|};\n\nconst defaultNoop = () => noop;\n// eslint-disable-next-line flowtype/require-exact-type\nconst decorateOnce = <F : Function>({ value } : { value : F }) : F => once(value);\n\nexport function getBuiltInProps<P, X>() : BuiltInPropsDefinitionType<P, X> {\n return {\n window: {\n type: PROP_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: PROP_TYPE.NUMBER,\n required: false,\n sendToChild: false\n },\n\n cspNonce: {\n type: PROP_TYPE.STRING,\n required: false\n },\n\n onDisplay: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRendered: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRender: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onClose: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onDestroy: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onResize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n onFocus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n close: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ close }) => close\n },\n\n focus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ focus }) => focus\n },\n\n resize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ resize }) => resize\n },\n\n uid: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ uid }) => uid\n },\n\n tag: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ tag }) => tag\n },\n\n getParent: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParent }) => getParent\n },\n\n getParentDomain: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParentDomain }) => getParentDomain\n },\n\n show: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ show }) => show\n },\n\n hide: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ hide }) => hide\n },\n\n export: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ 'export': xport }) => xport\n },\n\n onError: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onError }) => onError\n },\n\n onProps: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onProps }) => onProps\n },\n\n getSiblings: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getSiblings }) => getSiblings\n }\n };\n}\n\ntype PropCallback<P, X, R> =\n ((string, BooleanPropDefinitionType<boolean, P, X> | void, boolean) => R) &\n ((string, StringPropDefinitionType<string, P, X> | void, string) => R) &\n ((string, NumberPropDefinitionType<number, P, X> | void, number) => R) &\n ((string, FunctionPropDefinitionType<Function, P, X> | void, Function) => R) &\n ((string, ArrayPropDefinitionType<$ReadOnlyArray<*> | $ReadOnlyArray<*>, P, X> | void, $ReadOnlyArray<*> | $ReadOnlyArray<*>) => R) &\n ((string, ObjectPropDefinitionType<Object, P, X> | void, Object) => R);\n\nexport function eachProp<P, X>(props : PropsType<P>, propsDef : PropsDefinitionType<P, X>, handler : PropCallback<P, X, void>) {\n // $FlowFixMe[cannot-spread-indexer]\n for (const key of Object.keys({ ...props, ...propsDef })) {\n const propDef = propsDef[key];\n const value = props[key];\n\n // $FlowFixMe[incompatible-call]\n handler(key, propDef, value);\n }\n}\n\nexport function mapProps<P, X, T>(props : PropsType<P>, propsDef : PropsDefinitionType<P, X>, handler : PropCallback<P, X, T>) : $ReadOnlyArray<T> {\n const results = [];\n\n eachProp(props, propsDef, (key, propDef, value) => {\n // $FlowFixMe[incompatible-call]\n const result = handler(key, propDef, value);\n results.push(result);\n });\n return results;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { dotify, isDefined, base64encode, noop } from 'belter/src';\n\nimport { eachProp, mapProps, type PropsInputType, type PropsType, type PropsDefinitionType } from '../component/props';\nimport { PROP_SERIALIZATION, METHOD, PROP_TYPE } from '../constants';\n\nimport type { ParentHelpers } from './index';\n\nexport function extendProps<P, X>(propsDef : PropsDefinitionType<P, X>, existingProps : PropsType<P>, inputProps : PropsInputType<P>, helpers : ParentHelpers<P>, container : HTMLElement | void) {\n const { state, close, focus, event, onError } = helpers;\n\n // $FlowFixMe\n eachProp(inputProps, propsDef, (key, propDef, val) => {\n let valueDetermined = false;\n let value = val;\n\n const getDerivedValue = () => {\n if (!propDef) {\n return value;\n }\n\n const alias = propDef.alias;\n if (alias && !isDefined(val) && isDefined(inputProps[alias])) {\n value = inputProps[alias];\n }\n \n if (propDef.value) {\n value = propDef.value({ props: existingProps, state, close, focus, event, onError, container });\n }\n \n if (propDef.default && !isDefined(value) && !isDefined(inputProps[key])) {\n value = propDef.default({ props: existingProps, state, close, focus, event, onError, container });\n }\n\n if (isDefined(value)) {\n if (propDef.type === PROP_TYPE.ARRAY ? !Array.isArray(value) : (typeof value !== propDef.type)) {\n throw new TypeError(`Prop is not of type ${ propDef.type }: ${ key }`);\n }\n } else {\n if (propDef.required !== false && !isDefined(inputProps[key])) {\n throw new Error(`Expected prop \"${ key }\" to be defined`);\n }\n }\n \n if (__DEBUG__ && isDefined(value) && propDef.validate) {\n // $FlowFixMe\n propDef.validate({ value, props: inputProps });\n }\n\n if (isDefined(value) && propDef.decorate) {\n // $FlowFixMe\n value = propDef.decorate({ value, props: existingProps, state, close, focus, event, onError, container });\n }\n\n return value;\n };\n\n const getter = () => {\n if (valueDetermined) {\n return value;\n }\n\n valueDetermined = true;\n return getDerivedValue();\n };\n\n Object.defineProperty(existingProps, key, {\n configurable: true,\n enumerable: true,\n get: getter\n });\n });\n\n // $FlowFixMe\n eachProp(existingProps, propsDef, noop);\n}\n\nexport function serializeProps<P, X>(propsDef : PropsDefinitionType<P, X>, props : (PropsType<P>), method : $Values<typeof METHOD>) : ZalgoPromise<{ [string] : string | boolean }> {\n\n const params = {};\n\n return ZalgoPromise.all(mapProps(props, propsDef, (key, propDef, value) => {\n return ZalgoPromise.resolve().then(() => {\n\n if (value === null || typeof value === 'undefined' || !propDef) {\n return;\n }\n\n const getParam = {\n [ METHOD.GET ]: propDef.queryParam,\n [ METHOD.POST ]: propDef.bodyParam\n }[method];\n\n const getValue = {\n [ METHOD.GET ]: propDef.queryValue,\n [ METHOD.POST ]: propDef.bodyValue\n }[method];\n \n if (!getParam) {\n return;\n }\n\n return ZalgoPromise.hash({\n\n finalParam: ZalgoPromise.try(() => {\n if (typeof getParam === 'function') {\n // $FlowFixMe[incompatible-call]\n return getParam({ value });\n } else if (typeof getParam === 'string') {\n return getParam;\n } else {\n return key;\n }\n }),\n \n finalValue: ZalgoPromise.try(() => {\n if (typeof getValue === 'function' && isDefined(value)) {\n // $FlowFixMe[incompatible-call]\n // $FlowFixMe[incompatible-return]\n return getValue({ value });\n } else {\n // $FlowFixMe[incompatible-return]\n return value;\n }\n })\n\n }).then(({ finalParam, finalValue }) => {\n\n let result;\n\n if (typeof finalValue === 'boolean') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'string') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'object' && finalValue !== null) {\n\n if (propDef.serialization === PROP_SERIALIZATION.JSON) {\n result = JSON.stringify(finalValue);\n } else if (propDef.serialization === PROP_SERIALIZATION.BASE64) {\n result = base64encode(JSON.stringify(finalValue));\n } else if (propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization) {\n result = dotify(finalValue, 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 finalValue === 'number') {\n result = finalValue.toString();\n }\n\n params[finalParam] = result;\n });\n });\n\n })).then(() => {\n return params;\n });\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { send, bridge, ProxyWindow, toProxyWindow, type CrossDomainFunctionType, cleanUpWindow } from 'post-robot/src';\nimport { isSameDomain, matchDomain, getDomainFromUrl, isBlankDomain, getAncestor, getDomain, type CrossDomainWindowType,\n getDistanceFromTop, normalizeMockUrl, assertSameDomain, closeWindow, onCloseWindow, isWindowClosed, isSameTopWindow,\n type DomainMatcher } from '@krakenjs/cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { addEventListener, uniqueID, elementReady, writeElementToWindow, eventEmitter, type EventEmitterType,\n noop, onResize, extendUrl, appendChild, cleanup,\n once, stringifyError, destroyElement, getElementSafe, showElement, hideElement, iframe, memoize, isElementClosed,\n awaitFrameWindow, popup, normalizeDimension, watchElementForClose, isShadowElement, insertShadowSlot, extend } from 'belter/src';\n\nimport { ZOID, POST_MESSAGE, CONTEXT, EVENT, METHOD,\n WINDOW_REFERENCE, DEFAULT_DIMENSIONS } from '../constants';\nimport { getGlobal, getProxyObject, crossDomainSerialize, buildChildWindowName, type ProxyObject } from '../lib';\nimport type { PropsInputType, PropsType } from '../component/props';\nimport type { ChildExportsType } from '../child';\nimport type { CssDimensionsType, ContainerReferenceType } from '../types';\nimport type { NormalizedComponentOptionsType, AttributesType } from '../component';\n\nimport { serializeProps, extendProps } from './props';\n\nexport type RenderOptionsType<P> = {|\n uid : string,\n props : PropsType<P>,\n tag : string,\n context : $Values<typeof CONTEXT>,\n close : (?string) => ZalgoPromise<void>,\n focus : () => ZalgoPromise<void>,\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<P, X> = {|\n init : (ChildExportsType<P>) => ZalgoPromise<void>,\n close : () => ZalgoPromise<void>,\n checkClose : CrossDomainFunctionType<[], boolean>,\n resize : CrossDomainFunctionType<[{| width? : ?number, height? : ?number |}], void>,\n onError : (mixed) => ZalgoPromise<void>,\n show : () => ZalgoPromise<void>,\n hide : () => ZalgoPromise<void>,\n export : (X) => ZalgoPromise<void>\n|};\n\nexport type WindowRef =\n {| type : typeof WINDOW_REFERENCE.OPENER |} |\n {| type : typeof WINDOW_REFERENCE.PARENT, distance : number |} |\n {| type : typeof WINDOW_REFERENCE.GLOBAL, uid : string |} |\n {| type : typeof WINDOW_REFERENCE.NAME, name : string |};\n\nexport type InitialChildPayload<P, X> = {|\n uid : string,\n tag : string,\n version : string,\n context : $Values<typeof CONTEXT>,\n childDomainMatch : DomainMatcher,\n props : PropsType<P>,\n exports : ParentExportsType<P, X>\n|};\n\nexport type InitialChildPayloadMetadata = {|\n windowRef : WindowRef\n|};\n\nexport type StateType = Object;\n\nexport type ParentHelpers<P> = {|\n state : StateType,\n close : () => ZalgoPromise<void>,\n focus : () => ZalgoPromise<void>,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise<void>,\n onError : (mixed) => ZalgoPromise<void>,\n updateProps : PropsInputType<P> => ZalgoPromise<void>,\n event : EventEmitterType,\n show : () => ZalgoPromise<void>,\n hide : () => ZalgoPromise<void>\n|};\n\nfunction getDefaultProps<P>() : PropsType<P> {\n // $FlowFixMe\n return {};\n}\n\ntype InternalState = {|\n visible : boolean\n|};\n\ntype Rerender = () => ZalgoPromise<void>;\n\ntype RenderContainerOptions = {|\n context : $Values<typeof CONTEXT>,\n proxyFrame : ?ProxyObject<HTMLIFrameElement>,\n proxyPrerenderFrame : ?ProxyObject<HTMLIFrameElement>,\n rerender : Rerender\n|};\n\ntype ResolveInitPromise = () => ZalgoPromise<void>;\ntype RejectInitPromise = (mixed) => ZalgoPromise<void>;\ntype GetProxyContainer = (container : ContainerReferenceType) => ZalgoPromise<ProxyObject<HTMLElement>>;\ntype Show = () => ZalgoPromise<void>;\ntype Hide = () => ZalgoPromise<void>;\ntype Close = () => ZalgoPromise<void>;\ntype OnError = (mixed) => ZalgoPromise<void>;\ntype RenderContainer = (proxyContainer : ProxyObject<HTMLElement>, RenderContainerOptions) => ZalgoPromise<?ProxyObject<HTMLElement>>;\ntype SetProxyWin = (ProxyWindow) => ZalgoPromise<void>;\ntype GetProxyWindow = () => ZalgoPromise<ProxyWindow>;\ntype OpenFrame = (context : $Values<typeof CONTEXT>, {| windowName : string |}) => ZalgoPromise<?ProxyObject<HTMLIFrameElement>>;\ntype OpenPrerenderFrame = (context : $Values<typeof CONTEXT>) => ZalgoPromise<?ProxyObject<HTMLIFrameElement>>;\ntype Prerender = (proxyPrerenderWin : ProxyWindow, {| context : $Values<typeof CONTEXT>|}) => ZalgoPromise<void>;\ntype Open = (context : $Values<typeof CONTEXT>, {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject<HTMLIFrameElement>, windowName : string |}) => ZalgoPromise<ProxyWindow>;\ntype OpenPrerender = (context : $Values<typeof CONTEXT>, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject<HTMLIFrameElement>) => ZalgoPromise<ProxyWindow>;\ntype WatchForUnload = () => ZalgoPromise<void>;\ntype GetInternalState = () => ZalgoPromise<InternalState>;\ntype SetInternalState = (InternalState) => ZalgoPromise<InternalState>;\n\ntype ParentDelegateOverrides<P> = {|\n props : PropsType<P>,\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 resolveInitPromise : ResolveInitPromise,\n rejectInitPromise : RejectInitPromise\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 RenderOptions = {|\n target : CrossDomainWindowType,\n container : ContainerReferenceType,\n context : $Values<typeof CONTEXT>,\n rerender : Rerender\n|};\n\ntype ParentComponent<P, X> = {|\n init : () => void,\n render : (RenderOptions) => ZalgoPromise<void>,\n getProps : () => PropsType<P>,\n setProps : (newProps : PropsInputType<P>, isUpdate? : boolean) => void,\n export : (X) => ZalgoPromise<void>,\n destroy : (err? : mixed) => ZalgoPromise<void>,\n getHelpers : () => ParentHelpers<P>,\n getDelegateOverrides : () => ZalgoPromise<DelegateOverrides>,\n getExports : () => X\n|};\n\nconst getDefaultOverrides = <P>() : ParentDelegateOverrides<P> => {\n // $FlowFixMe\n return {};\n};\n\ntype ParentOptions<P, X, C> = {|\n uid : string,\n options : NormalizedComponentOptionsType<P, X, C>,\n overrides? : ParentDelegateOverrides<P>,\n parentWin? : CrossDomainWindowType\n|};\n\nexport function parentComponent<P, X, C>({ uid, options, overrides = getDefaultOverrides(), parentWin = window } : ParentOptions<P, X, C>) : ParentComponent<P, X> {\n const { propsDef, containerTemplate, prerenderTemplate, tag, name, attributes, dimensions, autoResize, url, domain: domainMatch, validate, exports: xports } = options;\n\n const initPromise = new ZalgoPromise();\n const handledErrors = [];\n const clean = cleanup();\n const state = {};\n const inputProps = {};\n let internalState = {\n visible: true\n };\n const event = overrides.event ? overrides.event : eventEmitter();\n const props : PropsType<P> = overrides.props ? overrides.props : getDefaultProps();\n\n let currentProxyWin : ?ProxyWindow;\n let currentProxyContainer : ?ProxyObject<HTMLElement>;\n let childComponent : ?ChildExportsType<P>;\n let currentChildDomain : ?string;\n let currentContainer : HTMLElement | void;\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 getDimensions = () : CssDimensionsType => {\n if (typeof dimensions === 'function') {\n return dimensions({ props });\n }\n return dimensions;\n };\n\n const resolveInitPromise = () => {\n return ZalgoPromise.try(() => {\n if (overrides.resolveInitPromise) {\n return overrides.resolveInitPromise();\n }\n\n return initPromise.resolve();\n });\n };\n\n const rejectInitPromise = (err : mixed) => {\n return ZalgoPromise.try(() => {\n if (overrides.rejectInitPromise) {\n return overrides.rejectInitPromise(err);\n }\n\n return initPromise.reject(err);\n });\n };\n\n const getPropsForChild = (initialChildDomain : string) : ZalgoPromise<PropsType<P>> => {\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(initialChildDomain, 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 rejectInitPromise(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<ProxyWindow> => {\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 setProxyWin = (proxyWin : ProxyWindow) : ZalgoPromise<void> => {\n if (setProxyWinOverride) {\n return setProxyWinOverride(proxyWin);\n }\n\n return ZalgoPromise.try(() => {\n currentProxyWin = proxyWin;\n });\n };\n\n const show = () : ZalgoPromise<void> => {\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<void> => {\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 buildQuery = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.GET);\n };\n\n const buildBody = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.POST);\n };\n\n const buildUrl = () : ZalgoPromise<string> => {\n return buildQuery().then(query => {\n return extendUrl(normalizeMockUrl(getUrl()), { query });\n });\n };\n\n const getInitialChildDomain = () : string => {\n return getDomainFromUrl(getUrl());\n };\n\n const getDomainMatcher = () : DomainMatcher => {\n if (domainMatch) {\n return domainMatch;\n }\n\n return getInitialChildDomain();\n };\n\n const openFrame = (context : $Values<typeof CONTEXT>, { windowName } : {| windowName : string |}) : ZalgoPromise<?ProxyObject<HTMLIFrameElement>> => {\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<typeof CONTEXT>) : ZalgoPromise<?ProxyObject<HTMLIFrameElement>> => {\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<typeof CONTEXT>, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject<HTMLIFrameElement>) : ZalgoPromise<ProxyWindow> => {\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<void> => {\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 getCurrentWindowReferenceUID = () : string => {\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 return uid;\n };\n\n const getWindowRef = (target : CrossDomainWindowType, initialChildDomain : string, context : $Values<typeof CONTEXT>, proxyWin : ProxyWindow) : WindowRef => {\n if (initialChildDomain === getDomain(window)) {\n return { type: WINDOW_REFERENCE.GLOBAL, uid: getCurrentWindowReferenceUID() };\n }\n\n if (target !== window) {\n throw new Error(`Can not construct cross-domain window reference for different target window`);\n }\n\n if (props.window) {\n const actualComponentWindow = proxyWin.getWindow();\n if (!actualComponentWindow) {\n throw new Error(`Can not construct cross-domain window reference for lazy window prop`);\n }\n\n if (getAncestor(actualComponentWindow) !== window) {\n throw new Error(`Can not construct cross-domain window reference for window prop with different ancestor`);\n }\n }\n\n if (context === CONTEXT.POPUP) {\n return { type: WINDOW_REFERENCE.OPENER };\n } else if (context === CONTEXT.IFRAME) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(window) };\n }\n\n throw new Error(`Can not construct window reference for child`);\n };\n\n const runTimeout = () : ZalgoPromise<void> => {\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 = (childDomain : string, childExports : ChildExportsType<P>) : ZalgoPromise<void> => {\n return ZalgoPromise.try(() => {\n currentChildDomain = childDomain;\n childComponent = childExports;\n resolveInitPromise();\n clean.register(() => childExports.close.fireAndForget().catch(noop));\n });\n };\n\n const resize = ({ width, height } : {| width? : ?number, height? : ?number |}) : ZalgoPromise<void> => {\n return ZalgoPromise.try(() => {\n event.trigger(EVENT.RESIZE, { width, height });\n });\n };\n\n const destroy = (err : mixed) : ZalgoPromise<void> => {\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(err);\n }).then(() => {\n initPromise.asyncReject(err || new Error('Component destroyed'));\n });\n };\n\n const close = memoize((err? : mixed) : ZalgoPromise<void> => {\n return ZalgoPromise.try(() => {\n\n if (closeOverride) {\n // $FlowFixMe\n const source = closeOverride.__source__;\n\n if (isWindowClosed(source)) {\n return;\n }\n\n return closeOverride();\n }\n\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.CLOSE);\n }).then(() => {\n return destroy(err || new Error(`Component closed`));\n });\n });\n });\n\n const open = (context : $Values<typeof CONTEXT>, { proxyWin, proxyFrame, windowName } : {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject<HTMLIFrameElement>, windowName : string |}) : ZalgoPromise<ProxyWindow> => {\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 clean.register(() => destroyElement(frame));\n clean.register(() => cleanUpWindow(win));\n return win;\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n let { width = DEFAULT_DIMENSIONS.WIDTH, height = DEFAULT_DIMENSIONS.HEIGHT } = getDimensions();\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.setName(windowName).then(() => {\n return proxyWin;\n });\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, context : $Values<typeof CONTEXT>) : ZalgoPromise<void> => {\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 (!cancelled) {\n if (isClosed) {\n return close(new Error(`Detected ${ context } close`));\n } else {\n return watchForClose(proxyWin, context);\n }\n }\n });\n };\n\n const checkWindowClose = (proxyWin : ProxyWindow) : ZalgoPromise<boolean> => {\n let closed = false;\n \n return proxyWin.isClosed().then(isClosed => {\n if (isClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n\n return ZalgoPromise.delay(200)\n .then(() => proxyWin.isClosed())\n .then(secondIsClosed => {\n if (secondIsClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n });\n }).then(() => {\n return closed;\n });\n };\n\n const onError = (err : mixed) : ZalgoPromise<void> => {\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 const exportsPromise : ZalgoPromise<X> = new ZalgoPromise();\n\n const getExports = () : X => {\n return xports({\n getExports: () => exportsPromise\n });\n };\n\n const xport = (actualExports : X) : ZalgoPromise<void> => {\n return ZalgoPromise.try(() => {\n exportsPromise.resolve(actualExports);\n });\n };\n\n initChild.onError = onError;\n\n const buildParentExports = (win : ProxyWindow) : ParentExportsType<P, X> => {\n const checkClose = () => checkWindowClose(win);\n function init(childExports : ChildExportsType<P>) : ZalgoPromise<void> {\n return initChild(this.origin, childExports);\n }\n return { init, close, checkClose, resize, onError, show, hide, export: xport };\n };\n\n const buildInitialChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, context : $Values<typeof CONTEXT>|} = {}) : ZalgoPromise<InitialChildPayload<P, X>> => {\n return getPropsForChild(initialChildDomain).then(childProps => {\n return {\n uid,\n context,\n tag,\n childDomainMatch,\n version: __ZOID__.__VERSION__,\n props: childProps,\n exports: buildParentExports(proxyWin)\n };\n });\n };\n\n const buildSerializedChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, target = window, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values<typeof CONTEXT>|} = {}) : ZalgoPromise<string> => {\n return buildInitialChildPayload({ proxyWin, initialChildDomain, childDomainMatch, context }).then(childPayload => {\n const { serializedData, cleanReference } = crossDomainSerialize({\n data: childPayload,\n metaData: {\n windowRef: getWindowRef(target, initialChildDomain, context, proxyWin)\n },\n sender: {\n domain: getDomain(window)\n },\n receiver: {\n win: proxyWin,\n domain: childDomainMatch\n },\n passByReference: initialChildDomain === getDomain()\n });\n\n clean.register(cleanReference);\n return serializedData;\n });\n };\n\n const buildWindowName = ({ proxyWin, initialChildDomain, childDomainMatch, target, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values<typeof CONTEXT>|}) : ZalgoPromise<string> => {\n return buildSerializedChildPayload({ proxyWin, initialChildDomain, childDomainMatch, target, context }).then(serializedPayload => {\n return buildChildWindowName({ name, serializedPayload });\n });\n };\n\n const renderTemplate = (renderer : (RenderOptionsType<P>) => ?HTMLElement, { context, container, doc, frame, prerenderFrame } : {| context : $Values<typeof CONTEXT>, container? : HTMLElement, doc : Document, frame? : ?HTMLIFrameElement, prerenderFrame? : ?HTMLIFrameElement |}) : ?HTMLElement => {\n \n return renderer({\n uid, container, context, doc, frame, prerenderFrame,\n focus, close, state, props, tag, dimensions: getDimensions(), event\n });\n };\n\n const prerender = (proxyPrerenderWin : ProxyWindow, { context } : {| context : $Values<typeof CONTEXT>|}) : ZalgoPromise<void> => {\n if (prerenderOverride) {\n return prerenderOverride(proxyPrerenderWin, { context });\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, 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 const renderContainer : RenderContainer = (proxyContainer : ProxyObject<HTMLElement>, { proxyFrame, proxyPrerenderFrame, context, rerender } : RenderContainerOptions) : ZalgoPromise<?ProxyObject<HTMLElement>> => {\n\n if (renderContainerOverride) {\n return renderContainerOverride(proxyContainer, { proxyFrame, proxyPrerenderFrame, context, rerender });\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, container, frame, prerenderFrame, doc: document });\n if (innerContainer) {\n if (!visible) {\n hideElement(innerContainer);\n }\n appendChild(container, innerContainer);\n const containerWatcher = watchElementForClose(innerContainer, () => {\n const removeError = new Error(`Detected container element removed from DOM`);\n return ZalgoPromise.delay(1).then(() => {\n if (isElementClosed(innerContainer)) {\n close(removeError);\n } else {\n clean.all(removeError);\n return rerender().then(resolveInitPromise, rejectInitPromise);\n }\n });\n });\n \n clean.register(() => containerWatcher.cancel());\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, initialChildDomain : string, context : $Values<typeof CONTEXT>) : ?ZalgoPromise<?CrossDomainWindowType> => {\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: initialChildDomain }) || bridge.hasBridge(initialChildDomain, initialChildDomain)) {\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, initialChildDomain);\n return bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain);\n });\n }\n };\n\n const getHelpers = () : ParentHelpers<P> => {\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 getProps = () => props;\n\n const getDefaultPropsInput = () : PropsInputType<P> => {\n // $FlowFixMe\n return {};\n };\n\n const setProps = (newInputProps : PropsInputType<P> = getDefaultPropsInput()) => {\n if (__DEBUG__ && validate) {\n validate({ props: newInputProps });\n }\n\n const container = currentContainer;\n const helpers = getHelpers();\n extend(inputProps, newInputProps);\n\n // $FlowFixMe\n extendProps(propsDef, props, inputProps, helpers, container);\n };\n\n const updateProps = (newProps : PropsInputType<P>) : ZalgoPromise<void> => {\n setProps(newProps);\n\n return initPromise.then(() => {\n const child = childComponent;\n const proxyWin = currentProxyWin;\n const childDomain = currentChildDomain;\n \n if (!child || !proxyWin || !childDomain) {\n return;\n }\n\n return getPropsForChild(childDomain).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 getProxyContainer : GetProxyContainer = (container : ContainerReferenceType) : ZalgoPromise<ProxyObject<HTMLElement>> => {\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 currentContainer = containerElement;\n return getProxyObject(containerElement);\n });\n };\n\n const delegate = (context : $Values<typeof CONTEXT>, target : CrossDomainWindowType) : ZalgoPromise<DelegateOverrides> => {\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 uid,\n overrides: {\n props: delegateProps, event, close, onError, getInternalState,\n setInternalState, resolveInitPromise, rejectInitPromise\n }\n }).then(({ data: { parent } }) => {\n const parentComp : ParentComponent<P, X> = parent;\n\n clean.register(err => {\n if (!isWindowClosed(target)) {\n return parentComp.destroy(err);\n }\n });\n return parentComp.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<DelegateOverrides> => {\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, childDomainMatch : DomainMatcher, container : ContainerReferenceType) => {\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(childDomainMatch, origin) && !isSameDomain(target)) {\n throw new Error(`Can not render remotely to ${ childDomainMatch.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, container, context, rerender } : RenderOptions) : ZalgoPromise<void> => {\n return ZalgoPromise.try(() => {\n const initialChildDomain = getInitialChildDomain();\n const childDomainMatch = getDomainMatcher();\n \n checkAllowRender(target, childDomainMatch, 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 buildBodyPromise = buildBody();\n const onRenderPromise = event.trigger(EVENT.RENDER);\n\n const getProxyContainerPromise = getProxyContainer(container);\n const getProxyWindowPromise = getProxyWindow();\n\n const finalSetPropsPromise = getProxyContainerPromise.then(() => {\n return setProps();\n });\n\n const buildUrlPromise = finalSetPropsPromise.then(() => {\n return buildUrl();\n });\n\n const buildWindowNamePromise = getProxyWindowPromise.then(proxyWin => {\n return buildWindowName({ proxyWin, initialChildDomain, childDomainMatch, target, context });\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, proxyFrame, proxyPrerenderFrame, rerender });\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 });\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 getMethodPromise = ZalgoPromise.hash({ body: buildBodyPromise }).then(({ body }) => {\n if (options.method) {\n return options.method;\n }\n\n if (Object.keys(body).length) {\n return METHOD.POST;\n }\n\n return METHOD.GET;\n });\n\n\n const loadUrlPromise = ZalgoPromise.hash({ proxyWin: openPromise, windowUrl: buildUrlPromise, body: buildBodyPromise, method: getMethodPromise, windowName: setWindowNamePromise, prerender: prerenderPromise }).then(({ proxyWin, windowUrl, body, method }) => {\n return proxyWin.setLocation(windowUrl, { method, body });\n });\n\n const watchForClosePromise = openPromise.then(proxyWin => {\n watchForClose(proxyWin, context);\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, initialChildDomain, 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, finalSetPropsPromise\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 getProps,\n setProps,\n export: xport,\n getHelpers,\n getDelegateOverrides,\n getExports\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\n\nexport function defaultContainerTemplate<P>({ uid, frame, prerenderFrame, doc, props, event, dimensions } : RenderOptionsType<P>) : ?HTMLElement {\n const { width, height } = dimensions;\n\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/* eslint react/react-in-jsx-scope: off */\n\nimport { type RenderOptionsType } from '../../parent/parent';\n\nexport function defaultPrerenderTemplate<P>({ doc, props } : RenderOptionsType<P>) : ?HTMLElement {\n if (__ZOID__.__DEFAULT_PRERENDER__) {\n const html = doc.createElement('html');\n const body = doc.createElement('body');\n const style = doc.createElement('style');\n const spinner = doc.createElement('div');\n spinner.classList.add('spinner');\n\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n html.appendChild(body);\n body.appendChild(spinner);\n body.appendChild(style);\n style.appendChild(doc.createTextNode(`\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n `));\n\n return html;\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, matchDomain, type CrossDomainWindowType, type DomainMatcher } from '@krakenjs/cross-domain-utils/src';\nimport { noop, isElement, cleanup, memoize, identity, extend, uniqueID } from 'belter/src';\n\nimport { childComponent, type ChildComponent } from '../child';\nimport { type RenderOptionsType, type ParentHelpers, parentComponent } from '../parent/parent';\nimport { ZOID, CONTEXT, POST_MESSAGE, WILDCARD, METHOD, PROP_TYPE } from '../constants';\nimport { react, angular, vue, vue3, angular2 } from '../drivers';\nimport { getGlobal, destroyGlobal, getInitialParentPayload, isChildComponentWindow } from '../lib';\nimport type { CssDimensionsType, StringMatcherType, ContainerReferenceType } from '../types';\n\nimport { validateOptions } from './validate';\nimport { defaultContainerTemplate, defaultPrerenderTemplate } from './templates';\nimport { getBuiltInProps, type UserPropsDefinitionType, type PropsDefinitionType, type PropsInputType,\n type PropsType, type ParentPropType, type exportPropType, type DEFINITION_TYPE } 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\ntype Attributes = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\nexport type ExportsConfigDefinition = {|\n [string] : {|\n type : DEFINITION_TYPE\n |}\n|};\n\nexport type ExportsMapperDefinition<X> = ({|\n getExports : () => ZalgoPromise<X>\n|}) => X;\n\nexport type ExportsDefinition<X> = ExportsConfigDefinition | ExportsMapperDefinition<X>;\n\nexport type ComponentOptionsType<P, X, C> = {|\n\n tag : string,\n\n url : string | ({| props : PropsType<P> |}) => string,\n domain? : DomainMatcher,\n bridgeUrl? : string,\n method? : $Values<typeof METHOD>,\n\n props? : UserPropsDefinitionType<P, X>,\n\n dimensions? : CssDimensionsType | ({| props : PropsType<P> |}) => CssDimensionsType,\n autoResize? : {| width? : boolean, height? : boolean, element? : string |},\n\n allowedParentDomains? : StringMatcherType,\n\n attributes? : Attributes | ({| props : PropsType<P> |}) => Attributes,\n\n eligible? : ({| props : PropsInputType<P> |}) => {| eligible : boolean, reason? : string |},\n\n defaultContext? : $Values<typeof CONTEXT>,\n\n containerTemplate? : (RenderOptionsType<P>) => ?HTMLElement,\n prerenderTemplate? : (RenderOptionsType<P>) => ?HTMLElement,\n\n validate? : ({| props : PropsInputType<P> |}) => void,\n\n logger? : Logger,\n\n children? : () => C,\n\n exports? : ExportsDefinition<X>\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<P, X, C> = {|\n tag : string,\n name : string,\n\n url : string | ({| props : PropsType<P> |}) => string,\n domain : ?DomainMatcher,\n bridgeUrl : ?string,\n method : ?$Values<typeof METHOD>,\n\n propsDef : PropsDefinitionType<P, X>,\n dimensions : CssDimensionsType | ({| props : PropsType<P> |}) => CssDimensionsType,\n autoResize : AutoResizeType,\n\n allowedParentDomains : StringMatcherType,\n\n attributes : AttributesType | ({| props : PropsType<P> |}) => AttributesType,\n\n eligible : ({| props : PropsInputType<P> |}) => {| eligible : boolean, reason? : string |},\n\n defaultContext : $Values<typeof CONTEXT>,\n\n containerTemplate : (RenderOptionsType<P>) => ?HTMLElement,\n prerenderTemplate : ?(RenderOptionsType<P>) => ?HTMLElement,\n\n validate : ?({| props : PropsInputType<P> |}) => void,\n logger : Logger,\n\n children : () => C,\n\n exports : ExportsMapperDefinition<X>\n|};\n\nexport type ZoidComponentInstance<P, X = void, C = void> = {|\n ...ParentHelpers<P>,\n ...X,\n ...C,\n isEligible : () => boolean,\n clone : () => ZoidComponentInstance<P, X, C>,\n render : (container? : ContainerReferenceType, context? : $Values<typeof CONTEXT>) => ZalgoPromise<void>,\n renderTo : (target : CrossDomainWindowType, container? : ContainerReferenceType, context? : $Values<typeof CONTEXT>) => ZalgoPromise<void>\n|};\n\n// eslint-disable-next-line flowtype/require-exact-type\nexport type ZoidComponent<P, X = void, C = void> = {\n (props? : PropsInputType<P> | void) : ZoidComponentInstance<P, X, C>,\n // eslint-disable-next-line no-undef\n driver : <T>(string, mixed) => T,\n isChild : () => boolean,\n xprops? : PropsType<P>,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise<boolean>,\n instances : $ReadOnlyArray<ZoidComponentInstance<P, X, C>>\n};\n\nconst getDefaultAttributes = () : AttributesType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultAutoResize = () : AutoResizeType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultExports = <X>() : () => X => {\n // $FlowFixMe\n return noop;\n};\n\nconst getDefaultDimensions = () : CssDimensionsType => {\n // $FlowFixMe\n return {};\n};\n\nfunction normalizeOptions<P, X, C>(options : ComponentOptionsType<P, X, C>) : NormalizedComponentOptionsType<P, X, C> {\n const {\n tag,\n url,\n domain,\n bridgeUrl,\n props = {},\n dimensions = getDefaultDimensions(),\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 exports: xportsDefinition = getDefaultExports(),\n method,\n children = () : C => {\n // $FlowFixMe\n return {};\n }\n } = options;\n\n const name = tag.replace(/-/g, '_');\n\n // $FlowFixMe[incompatible-type]\n // $FlowFixMe[cannot-spread-inexact]\n const propsDef : PropsDefinitionType<P, X> = {\n ...getBuiltInProps(),\n ...props\n };\n\n if (!containerTemplate) {\n throw new Error(`Container template required`);\n }\n\n const xports = typeof xportsDefinition === 'function'\n ? xportsDefinition\n : ({ getExports }) : X => {\n const result = {};\n\n for (const key of Object.keys(xportsDefinition)) {\n const { type } = xportsDefinition[key];\n const valuePromise = getExports().then(res => {\n // $FlowFixMe\n return res[key];\n });\n\n if (type === PROP_TYPE.FUNCTION) {\n result[key] = (...args) => valuePromise.then(value => value(...args));\n } else {\n result[key] = valuePromise;\n }\n }\n\n // $FlowFixMe\n return result;\n };\n\n return {\n name,\n tag,\n url,\n domain,\n bridgeUrl,\n method,\n propsDef,\n dimensions,\n autoResize,\n allowedParentDomains,\n attributes,\n defaultContext,\n containerTemplate,\n prerenderTemplate,\n validate,\n logger,\n eligible,\n children,\n exports: xports\n };\n}\n\nlet cleanInstances = cleanup();\nconst cleanZoid = cleanup();\n\nexport type Component<P, X, C> = {|\n init : (props? : PropsInputType<P> | void) => ZoidComponentInstance<P, X, C>,\n instances : $ReadOnlyArray<ZoidComponentInstance<P, X, C>>,\n driver : (string, mixed) => mixed,\n isChild : () => boolean,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise<boolean>,\n registerChild : () => ?ChildComponent<P, X>\n|};\n\nexport function component<P, X, C>(opts : ComponentOptionsType<P, X, C>) : Component<P, X, C> {\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 children\n } = options;\n\n const global = getGlobal(window);\n const driverCache = {};\n const instances = [];\n\n const isChild = () : boolean => {\n if (isChildComponentWindow(name)) {\n const { payload } = getInitialParentPayload();\n if (payload.tag === tag && matchDomain(payload.childDomainMatch, getDomain())) {\n return true;\n }\n }\n\n return false;\n };\n\n const registerChild = memoize(() : ?ChildComponent<P, X> => {\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 const allowDelegateListener = on(`${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`, () => {\n return true;\n });\n\n const delegateListener = on(`${ POST_MESSAGE.DELEGATE }_${ name }`, ({ source, data: { uid, overrides } }) => {\n return {\n parent: parentComponent({\n uid, options, overrides, parentWin: source\n })\n };\n });\n\n cleanZoid.register(allowDelegateListener.cancel);\n cleanZoid.register(delegateListener.cancel);\n };\n\n const canRenderTo = (win : CrossDomainWindowType) : ZalgoPromise<boolean> => {\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<typeof CONTEXT>, container? : ContainerReferenceType) : ContainerReferenceType => {\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<P>, context : ?$Values<typeof CONTEXT>) : ZalgoPromise<$Values<typeof CONTEXT>> => {\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<P> => {\n // $FlowFixMe\n return {};\n };\n\n const init = (inputProps? : PropsInputType<P> | void) : ZoidComponentInstance<P, X, C> => {\n // eslint-disable-next-line prefer-const\n let instance;\n\n const uid = `${ ZOID }-${ tag }-${ uniqueID() }`;\n const props = inputProps || 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({\n uid, options\n });\n\n parent.init();\n\n if (eligibility) {\n parent.setProps(props);\n } else {\n if (props.onDestroy) {\n props.onDestroy();\n }\n }\n\n cleanInstances.register(err => {\n return parent.destroy(err || new Error(`zoid destroyed all components`));\n });\n\n const clone = ({ decorate = identity } = {}) => {\n return init(decorate(props));\n };\n\n const getChildren = () : C => {\n // $FlowFixMe\n const childComponents : {| [string] : ZoidComponent<mixed> |} = children();\n const result = {};\n\n for (const childName of Object.keys(childComponents)) {\n const Child : ZoidComponent<mixed> = childComponents[childName];\n\n result[childName] = (childInputProps) => {\n const parentProps : PropsType<P> = parent.getProps();\n const parentExport : exportPropType<X> = parent.export;\n\n const childParent : ParentPropType<P, X> = {\n uid,\n props: parentProps,\n export: parentExport\n };\n \n const childProps : PropsInputType<mixed> = {\n ...childInputProps,\n parent: childParent\n };\n\n return Child(childProps);\n };\n }\n\n // $FlowFixMe\n return result;\n };\n\n const render = (target, container, context) => {\n return ZalgoPromise.try(() => {\n if (!eligibility) {\n const err = new Error(reason || `${ name } component is not eligible`);\n\n return parent.destroy(err).then(() => {\n throw err;\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\n if (target !== window && typeof container !== 'string') {\n throw new Error(`Must pass string element when rendering to another window`);\n }\n\n return parent.render({\n target,\n container,\n context: finalContext,\n rerender: () => {\n const newInstance = clone();\n extend(instance, newInstance);\n return newInstance.renderTo(target, container, context);\n }\n });\n\n }).catch(err => {\n return parent.destroy(err).then(() => {\n throw err;\n });\n });\n };\n\n instance = {\n ...parent.getExports(),\n ...parent.getHelpers(),\n ...getChildren(),\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, vue3, 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<P, L, D, X, C> = {|\n register : (string, PropsDefinitionType<P, X>, (PropsInputType<P>) => ZoidComponentInstance<P, X, C>, L) => D\n|};\n\nexport type ZoidProps<P> = PropsType<P>;\n\n// eslint-disable-next-line no-undef\nexport type CreateZoidComponent = <P, X, C>(options : ComponentOptionsType<P, X, C>) => ZoidComponent<P, X, C>;\n\nexport const create : CreateZoidComponent = <P, X, C>(options : ComponentOptionsType<P, X, C>) : ZoidComponent<P, X, C> => {\n setupPostRobot();\n\n const comp = component(options);\n\n const init = (props? : PropsInputType<P> | void) => 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 destroyComponents(err? : mixed) : ZalgoPromise<void> {\n if (bridge) {\n bridge.destroyBridges();\n }\n\n const destroyPromise = cleanInstances.all(err);\n cleanInstances = cleanup();\n return destroyPromise;\n}\n\nexport const destroyAll = destroyComponents;\n\nexport function destroy(err? : mixed) : ZalgoPromise<void> {\n destroyAll();\n destroyGlobal();\n destroyPostRobot();\n return cleanZoid.all(err);\n}\n"],"sourceRoot":""}