customerio-gist-web
Version:
Build beautiful in-app flows with no code and deliver them instantly to your app. http://customer.io
1 lines • 25.9 kB
JavaScript
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Gist=t():e.Gist=t()}(this,(()=>(()=>{var e={548:(e,t,n)=>{"use strict";n.d(t,{A:()=>Re});class s{on(e,t){var n=this[e];n?n.push(t):this[e]=[t]}dispatch(e,t){var n=this[e];n&&n.forEach((e=>e(t)))}}function i(e){Re.config.logging&&console.log(`Gist: ${e}`)}var a,o=new Uint8Array(16);function r(){if(!a&&!(a="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return a(o)}const c=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var u=[],d=0;d<256;++d)u.push((d+256).toString(16).substr(1));const g=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(u[e[t+0]]+u[e[t+1]]+u[e[t+2]]+u[e[t+3]]+"-"+u[e[t+4]]+u[e[t+5]]+"-"+u[e[t+6]]+u[e[t+7]]+"-"+u[e[t+8]]+u[e[t+9]]+"-"+u[e[t+10]]+u[e[t+11]]+u[e[t+12]]+u[e[t+13]]+u[e[t+14]]+u[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&c.test(e)}(n))throw TypeError("Stringified UUID is invalid");return n},l=function(e,t,n){var s=(e=e||{}).random||(e.rng||r)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){n=n||0;for(var i=0;i<16;++i)t[n+i]=s[i];return t}return g(s)},m=365,f="gist.web.isPersistingSession";function h(e,t,n=null){var s=n;s||(s=new Date).setDate(s.getDate()+m);const i={value:t,expiry:s};y().setItem(e,JSON.stringify(i))}function p(e){const t=y().getItem(e);if(!t)return null;const n=JSON.parse(t),s=new Date,i=new Date(n.expiry),a=e.startsWith("gist.web.message.broadcasts")&&!e.endsWith("shouldShow")&&!e.endsWith("numberOfTimesShown")||e.startsWith("gist.web.message.user")&&!e.endsWith("seen"),o=new Date(s.getTime()+366e4);return a&&i.getTime()>o.getTime()||s.getTime()>i.getTime()?(w(e),null):n.value}function w(e){y().removeItem(e)}function v(){const e=sessionStorage.getItem(f);return null===e?(sessionStorage.setItem(f,"true"),!0):"true"===e}function y(){return v()?localStorage:sessionStorage}const b="gist.web.userQueueUseSSE",S="gist.web.activeSSEConnection";let I,E=30;const $={RENDERER_HOST:"https://code.gist.build",ENGINE_API_ENDPOINT:{prod:"https://engine.api.gist.build",dev:"https://engine.api.dev.gist.build",local:"http://engine.api.local.gist.build:82"},GIST_QUEUE_API_ENDPOINT:{prod:"https://consumer.cloud.gist.build",dev:"https://consumer.cloud.dev.gist.build",local:"http://api.local.gist.build:86"},GIST_QUEUE_REALTIME_API_ENDPOINT:{prod:"https://realtime.cloud.gist.build",dev:"https://realtime.cloud.dev.gist.build",local:"http://api.local.gist.build:3000"},GIST_VIEW_ENDPOINT:{prod:"https://renderer.gist.build/3.0",dev:"https://renderer.gist.build/3.0",local:"http://app.local.gist.build:8080/web"},getSdkId:function(){return I||(I=l()),I},useSSE:function(){return p(b)??!1},setUseSSEFlag:function(e){h(b,e,new Date((new Date).getTime()+6e4)),i(`Set user uses SSE to "${e}"`)},removeActiveSSEConnection:function(){w(S)},setActiveSSEConnection:function(){h(S,$.getSdkId(),new Date((new Date).getTime()+$.getSSEHeartbeat()))},hasActiveSSEConnection:function(){return p(S)??!1},isSSEConnectionManagedBySDK:function(){return p(S)===$.getSdkId()},getSSEHeartbeat:function(){return 1e3*(E+5)},setSSEHeartbeat:function(e){e&&e>0&&(E=e)}};function x(){const e=$.GIST_QUEUE_API_ENDPOINT[Re.config.env],t={"X-CIO-Site-Id":Re.config.siteId,"X-CIO-Client-Platform":"web"},n=O();async function s(n,s={}){const i=e+n,a=new AbortController,o=setTimeout((()=>a.abort()),5e3);try{const e=await fetch(i,{method:s.method||"GET",headers:{...t,...s.headers||{}},body:s.method&&"GET"!==s.method.toUpperCase()?s.body:void 0,signal:a.signal});clearTimeout(o);const n=e.headers.get("content-type")?.includes("application/json"),r=n?await e.json():await e.text(),c=Object.fromEntries(e.headers.entries());if(e.status<200||e.status>=400)throw{response:{status:e.status,data:r,headers:c}};return{status:e.status,headers:c,data:r}}catch(e){throw clearTimeout(o),e.response||(e.response={status:0,data:e.message||"Unknown error"}),e}}return null!=n&&(t["X-Gist-Encoded-User-Token"]=n),s.post=(e,t={},n={})=>s(e,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",...n.headers||{}}}),s}const T="gist.web.userLocale";var D=600,k=!1;const C="gist.web.userQueueNextPullCheck",M="gist.web.sessionId";function q(){var e=p(M);return e||(e=l()),h(M,e,new Date((new Date).getTime()+18e5)),e}const P="gist.web.userToken",R="gist.web.usingGuestUserToken",L="gist.web.guestUserToken";function A(){return null!==p(R)}function N(){return p(P)}function U(){if(null===N()){var e=p(L);null==e&&(e=l(),h(L,e),i(`Set guest user token "${e}" with expiry date set to 1 year from today`)),h(P,e),h(R,!0),i(`Using anonymous session with token: "${e}"`)}}async function W(){var e=N();return null===e?null:await async function(e){const t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map((e=>e.toString(16).padStart(2,"0"))).join("")}(e)}function O(){var e=N();return null===e?null:btoa(e)}function _(e){const t={isEmbedded:!1,elementId:"",hasRouteRule:!1,routeRule:"",position:"",hasPosition:!1,shouldScale:!1,campaignId:null,messageWidth:414,overlayColor:"#00000033",persistent:!1,exitClick:!1,hasCustomWidth:!1},n=e?.properties?.gist;return n?{isEmbedded:!!n.elementId,elementId:n.elementId||"",hasRouteRule:!!n.routeRuleWeb,routeRule:n.routeRuleWeb||"",position:n.position||"",hasPosition:!!n.position,shouldScale:!!n.scale,campaignId:n.campaignId??null,messageWidth:n.messageWidth>0?n.messageWidth:t.messageWidth,hasCustomWidth:n.messageWidth>0,overlayColor:n.overlayColor||t.overlayColor,persistent:!!n.persistent,exitClick:!!n.exitClick}:t}var H=["x-gist-top","x-gist-floating-top","x-gist-bottom","x-gist-floating-bottom","x-gist-floating-bottom-left","x-gist-floating-bottom-right","x-gist-floating-top-left","x-gist-floating-top-right"];const G=e=>new Promise((t=>setTimeout(t,e))),j=["x-gist-top","x-gist-bottom","x-gist-floating-top","x-gist-floating-bottom"];function V(e){var t=J(e);if(t)return t.style&&t.style.height&&"0px"!=t.style.height}function z(e,t){const n=document.getElementById(e);n&&(n.onload=function(){!function(e,t){const n=document.getElementById(e);n&&n.contentWindow&&n.contentWindow.postMessage({options:t},"*")}(e,t)})}function F(){var e=document.querySelector("#gist-embed-message");e&&e.parentNode.removeChild(e)}function B(e){return`gist-${e}`}function Q(){var e=document.querySelector(".gist-message");e&&e.classList.add("gist-visible")}function J(e){try{return document.querySelector(`#${e}`)||null}catch{return null}}const X="gist.web.message.broadcasts",K=60;async function Y(e){const t=await te();if(!t)return;const n=new Date;n.setMinutes(n.getMinutes()+K),h(t,e.filter(ee),n)}async function Z(e,t){return p(e).find((e=>e.queueId===t))}function ee(e){return e.properties&&e.properties.gist&&e.properties.gist.broadcast}async function te(){const e=await W();return e?`${X}.${e}`:null}function ne(e,t){return`${e}.${t}.numberOfTimesShown`}function se(e,t){return`${e}.${t}.shouldShow`}const ie="gist.web.message.user",ae=60;async function oe(e){const t=await re();if(!t)return;const n=e.filter((e=>!(e.properties&&e.properties.gist&&e.properties.gist.broadcast))),s=new Date;s.setMinutes(s.getMinutes()+ae),h(t,n,s)}async function re(){const e=await W();return e?`${ie}.${e}`:null}async function ce(){const e=await W();return e?`${ie}.${e}.seen`:null}async function ue(e){const t=await W();return t?`${ie}.${t}.message.${e}.loading`:null}async function de(e){if(Re.isDocumentVisible){if(Re.overlayInstanceId)return i(`Message ${Re.overlayInstanceId} already showing.`),null;var t=_(e);return e.instanceId=l(),e.overlay=!0,e.firstLoad=!0,e.shouldResizeHeight=!0,e.shouldScale=t.shouldScale,e.renderStartTime=(new Date).getTime(),Re.overlayInstanceId=e.instanceId,Re.currentMessages.push(e),pe(e)}return i("Document hidden, not showing message now."),null}async function ge(e,t){return Re.isDocumentVisible?(e.instanceId=l(),e.overlay=!1,e.firstLoad=!0,e.shouldScale=!1,e.elementId=t,e.shouldResizeHeight=!V(t),e.renderStartTime=(new Date).getTime(),Re.currentMessages.push(e),pe(e,t)):(i("Document hidden, not showing message now."),null)}async function le(e){e?(Re.messageDismissed(e),e.overlay?await he(!0,e):fe(e)):i(`Message with instance id: ${e.instanceId} not found`)}async function me(e){var t=_(e);e?t.persistent&&(i("Persistent message dismissed, logging view"),await Ee(e),await we(e)):i(`Message with instance id: ${e.instanceId} not found`)}function fe(e){var t;ye(e.instanceId),(t=J(e.elementId))&&(t.classList.remove("gist-visible"),t.style.removeProperty("height"),t.innerHTML="")}async function he(e,t){e?await async function(){var e=document.querySelector(".gist-message");e&&(e.classList.remove("gist-visible"),await G(300)),F()}():F(),0==Re.currentMessages.length&&(window.removeEventListener("message",Ie),window.removeEventListener("touchstart",Se)),ye(t.instanceId),Re.overlayInstanceId=null}function pe(e,t=null){if(t&&function(e){var t=J(e);return!(!t||!t.classList.contains("gist-visible"))}(t))return i(`Message ${e.messageId} already showing in element ${t}.`),null;var n={endpoint:$.ENGINE_API_ENDPOINT[Re.config.env],siteId:Re.config.siteId,dataCenter:Re.config.dataCenter,messageId:e.messageId,instanceId:e.instanceId,livePreview:!1,properties:e.properties},s=`${$.GIST_VIEW_ENDPOINT[Re.config.env]}/index.html`;return window.addEventListener("message",Ie),window.addEventListener("touchstart",Se),t?(H.includes(t)&&function(e){const t=document.createElement("div");t.id=e,"x-gist-top"===e?document.body.insertBefore(t,document.body.firstChild):document.body.insertAdjacentElement("beforeend",t),i("Top & bottom elements injected into page")}(t),function(e,t,n,s){var a=J(e);if(a){var o=B(n.instanceId);a.classList.add(o);var r=_(n),c=r.messageWidth+"px";j.includes(e)&&!r.hasCustomWidth&&(c="100%"),H.includes(e)&&(a.style.width=c),V(e)||(a.style.height="0px"),a.innerHTML=function(e,t,n){var s=function(e,t,n){var s=800;return t.messageWidth>s&&(s=t.messageWidth),`\n <div id="gist-embed">\n <style>\n #x-gist-floating-top, #x-gist-floating-top-left, #x-gist-floating-top-right {\n position: fixed;\n top: 0px;\n z-index: 1000000;\n }\n #x-gist-floating-bottom, #x-gist-floating-bottom-left, #x-gist-floating-bottom-right {\n position: fixed;\n bottom: 0px;\n z-index: 1000000;\n }\n #x-gist-bottom, #x-gist-top, #x-gist-floating-top, #x-gist-floating-bottom {\n left: 50%;\n transform: translate(-50%, 0%);\n }\n #x-gist-floating-top-right, #x-gist-floating-bottom-right {\n right: 0px;\n }\n #gist-embed {\n position: relative;\n height: 100%;\n width: 100%;\n }\n #gist-embed-container {\n position: relative;\n height: 100%;\n width: 100%;\n }\n #gist-embed-container .gist-frame {\n height: 100%;\n width: 100%;\n border: none;\n }\n #x-gist-top.${e},\n #x-gist-bottom.${e},\n #x-gist-floating-top.${e},\n #x-gist-floating-bottom.${e},\n #x-gist-floating-top-left.${e},\n #x-gist-floating-top-right.${e},\n #x-gist-floating-bottom-left.${e},\n #x-gist-floating-bottom-right.${e} {\n transition: height 0.1s ease-in-out;\n }\n @media (max-width: ${s}px) {\n #x-gist-top.${e},\n #x-gist-bottom.${e},\n #x-gist-floating-top.${e},\n #x-gist-floating-bottom.${e},\n #x-gist-floating-top-left.${e},\n #x-gist-floating-top-right.${e},\n #x-gist-floating-bottom-left.${e},\n #x-gist-floating-bottom-right.${e} {\n width: 100% !important;\n }\n }\n </style>\n <div id="gist-embed-container">\n <iframe id="${e}" class="gist-frame" src="${n}"></iframe>\n </div>\n </div>`}(B(t.instanceId),n,e);return s}(t,n,r),z(o,s)}else i(`Message could not be embedded, elementId ${e} not found.`)}(t,s,e,n)):function(e,t,n){document.body.insertAdjacentHTML("afterbegin",function(e,t){var n=_(t),s=function(e,t,n){var s=600;return t.messageWidth>s&&(s=t.messageWidth),`\n <div id="gist-embed-message">\n <style>\n #gist-overlay.gist-background {\n position: fixed;\n z-index: 9999999998;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n background-color: ${t.overlayColor};\n visibility: hidden;\n }\n #gist-overlay.gist-background.gist-visible {\n visibility: visible;\n }\n .gist-message {\n width: ${t.messageWidth}px;\n position: absolute;\n border: none;\n opacity: 0;\n transition: opacity 0.3s ease-in-out, height 0.1s ease-in-out;\n z-index: 9999999999;\n left: 50%;\n transform: translateX(-50%);\n }\n .gist-message.gist-visible {\n opacity: 1;\n pointer-events: auto;\n }\n .gist-message.gist-center {\n transform: translate(-50%, -50%);\n top: 50%;\n }\n .gist-message.gist-bottom {\n bottom: 0;\n }\n .gist-message.gist-top {\n top: 0;\n }\n @media (max-width: ${s}px) {\n .gist-message {\n width: 100%;\n }\n }\n </style>\n <div id="gist-overlay" class="gist-background">\n <iframe id="${e}" class="gist-message" src="${n}"></iframe>\n </div>\n </div>`}(B(t.instanceId),n,e);return s}(e,t)),z(B(t.instanceId),n)}(s,e,n),e}async function we(e){i(`Message shown, logging view for: ${e.messageId}`);var t={};null!=e.queueId?(await Ee(e),t=await async function(e){try{return await x().post(`/api/v1/logs/queue/${e}`)}catch(e){return e.response}}(e.queueId)):t=await async function(e){try{return await x().post(`/api/v1/logs/message/${e}`)}catch(e){return e.response}}(e.messageId),200===t.status?i("Message view logged"):i(`Problem logging message: ${t.status}`)}function ve(e){return Re.currentMessages.find((t=>t.instanceId===e))}function ye(e){Re.currentMessages=Re.currentMessages.filter((t=>t.instanceId!==e))}function be(e,t){ye(e),Re.currentMessages.push(t)}function Se(){}async function Ie(e){if(e.data.gist&&e.origin===$.RENDERER_HOST){var t=e.data.gist.instanceId,n=ve(t);if(!n)return;var s=_(n);switch(e.data.gist.method){case"routeLoaded":var a=.001*((new Date).getTime()-n.renderStartTime);i(`Engine render for message: ${n.messageId} timer elapsed in ${a.toFixed(3)} seconds`),async function(e){const t=await ue(e);if(!t)return!1;w(t)}(n.queueId),n.currentRoute=e.data.gist.parameters.route,n.firstLoad&&(n.overlay?function(e){var t=_(e),n=document.querySelector("#gist-overlay");if(n){n.classList.add("gist-visible");var s=document.querySelector(".gist-message");e.position?s.classList.add("gist-"+e.position):s.classList.add("gist-center"),setTimeout(Q,100),t.exitClick&&setTimeout((()=>function(e){var t=document.querySelector("#gist-overlay");t&&t.addEventListener("click",(function(){Re.dismissMessage(e)}))}(e.instanceId)),1e3)}else F()}(n):(g=J(n.elementId))&&g.classList.add("gist-visible"),Re.messageShown(n),s.persistent?i("Persistent message shown, skipping logging view"):await we(n),n.firstLoad=!1),be(t,n);break;case"tap":var o=e.data.gist.parameters.action,r=e.data.gist.parameters.name;if(Re.messageAction(n,o,r),e.data.gist.parameters.system&&!s.persistent){await le(n);break}try{var c=new URL(o);if(c&&"gist:"===c.protocol)switch(c.href.replace("gist://","").split("?")[0]){case"close":await le(n),await me(n),await $e(n),await Ce();break;case"showMessage":var u=c.searchParams.get("messageId"),d=c.searchParams.get("properties");u&&(d&&(d=JSON.parse(atob(d))),await Re.showMessage({messageId:u,properties:d}));break;case"loadPage":(c=c.href.substring(c.href.indexOf("?url=")+5))&&(c.startsWith("mailto:")||c.startsWith("https://")||c.startsWith("http://")||c.startsWith("/")?window.location.href=c:window.location.href=window.location+c)}}catch{}break;case"routeChanged":n.currentRoute=e.data.gist.parameters.route,n.renderStartTime=(new Date).getTime(),be(t,n),i(`Route changed to: ${n.currentRoute}`);break;case"sizeChanged":i(`Size Changed Width: ${e.data.gist.parameters.width} - Height: ${e.data.gist.parameters.height}`),n.elementId&&!n.shouldResizeHeight||function(e,t){var n=J(e.elementId?e.elementId:B(e.instanceId));if(n){var s=n.style;if(t.height>0)if(t.height>window.innerHeight){var i=1-(t.height/window.innerHeight-1);e.shouldScale&&i>=.4?(s.height=`${t.height}px`,s.transform=`translateX(-50%) translateY(-50%) scale(${i})`):s.height=`${window.innerHeight}px`}else s.height=`${t.height}px`}}(n,e.data.gist.parameters);break;case"titleChanged":i(`Overlay title changed to: ${e.data.gist.parameters.title}`),function(e,t){var n=J(B(e));n&&(n.title=t)}(t,e.data.gist.parameters.title);break;case"eventDispatched":Re.events.dispatch("eventDispatched",{name:e.data.gist.parameters.name,payload:e.data.gist.parameters.payload});break;case"error":case"routeError":Re.messageError(n),Re.overlayInstanceId?he(!1,n):fe(n)}}var g}async function Ee(e){i(`Logging user message view locally for: ${e.queueId}`),ee(e)?await async function(e){i(`Marking broadcast ${e} as seen.`);const t=await te();if(!t)return;const n=await Z(t,e);if(!n)return;const{broadcast:s}=n.properties.gist,a=ne(t,e),o=se(t,e);let r=p(a)||0;if(h(a,r+1),1===s.frequency.count)h(o,!1),i(`Marked broadcast ${e} as seen.`);else{let t=new Date;t.setSeconds(t.getSeconds()+s.frequency.delay),h(o,!1,t),i(`Marked broadcast ${e} as seen, broadcast was seen ${r+1} times, next show date is ${t}.`)}}(e.queueId):await async function(e){const t=await ce();if(!t)return;const n=p(t)??[];n.push(e),h(t,n)}(e.queueId)}async function $e(e){ee(e)&&(i(`Logging broadcast dismissed locally for: ${e.queueId}`),await async function(e){i(`Marking broadcast ${e} as dismissed.`);const t=await te();if(!t)return;const n=await Z(t,e);if(!n)return;const{broadcast:s}=n.properties.gist;!0!==s.frequency.ignoreDismiss?(h(se(t,e),!1),i(`Marked broadcast ${e} as dismissed and will not show again.`)):i(`Broadcast ${e} is set to ignore dismiss.`)}(e.queueId))}var xe=(e,t)=>e().then((e=>new Promise((t=>setTimeout(t,e))))(t).then((()=>xe(e,t)))),Te=!1;let De=null;async function ke(){Te?await Ce():N()?(i("Queue watcher started"),Te=!0,xe((()=>new Promise((()=>async function(){if($.hasActiveSSEConnection())return!$.isSSEConnectionManagedBySDK()&&De&&(i("Not the main instance, closing our SSE connection."),Pe()),void await Ce();De&&(i("SSE connection not active, closing it."),Pe()),!$.useSSE()||A()?await qe():await async function(){Pe();const e=null===(t=O())?(i("No user token available for SSE endpoint."),null):$.GIST_QUEUE_REALTIME_API_ENDPOINT[Re.config.env]+`/api/v3/sse?userToken=${t}&siteId=${Re.config.siteId}&sessionId=${q()}`;var t;if(null===e)return i("SSE endpoint not available, falling back to polling."),void await qe();i(`Starting SSE queue listener on ${e}`),De=new EventSource(e),$.setActiveSSEConnection(),De.addEventListener("connected",(async e=>{try{i("SSE connection received:"),$.setUseSSEFlag(!0);var t=JSON.parse(e.data);t.heartbeat&&($.setSSEHeartbeat(t.heartbeat),i(`SSE heartbeat set to ${t.heartbeat} seconds`)),$.setActiveSSEConnection()}catch(e){i(`Failed to parse SSE settings: ${e}`)}w(C),await qe()})),De.addEventListener("messages",(async e=>{try{var t=JSON.parse(e.data);i("SSE message received:"),await oe(t),await Y(t),await Ce()}catch(e){i("Failed to parse SSE message"),Pe()}})),De.addEventListener("error",(async e=>{i("SSE error received:"),Pe()})),De.addEventListener("heartbeat",(async e=>{i("SSE heartbeat received:"),$.setActiveSSEConnection(),$.setUseSSEFlag(!0)}))}()}()))),1e3)):i("User token not setup, queue not started.")}async function Ce(){var e=await async function(){const e=await te();return e?(p(e)??[]).filter((t=>{const{broadcast:n}=t.properties.gist,s=p(se(e,t.queueId))??!0,i=p(ne(e,t.queueId))||0,a=0===n.frequency.count;return s&&(a||i<n.frequency.count)})):[]}(),t=await async function(){const e=await re();if(!e)return[];const t=p(e)??[],n=await async function(){const e=await ce();return e?p(e)??[]:[]}();return t.filter((e=>!n.includes(e.queueId)))}(),n=e.concat(t);i(`Messages in local queue: ${n.length}`);var s=n.sort(((e,t)=>e.priority-t.priority));for(const e of s)await Me(e)}async function Me(e){var t=_(e);if(t.hasRouteRule){var n=Re.currentRoute;null==n&&(n=new URL(window.location.href).pathname);var s=t.routeRule;if(i(`Verifying route ${n} against rule: ${s}`),!new RegExp(s).test(n))return i(`Route ${n} does not match rule.`),!1}if(t.hasPosition&&(e.position=t.position),t.persistent||function(e){if(!ee(e))return!1;const{broadcast:t}=e.properties.gist;return 0===t.frequency.delay&&0===t.frequency.count}(e)||!await async function(e){const t=await ue(e);return!!t&&null!==p(t)}(e.queueId)){var a;return(a=t.isEmbedded?await ge(e,t.elementId):await de(e))&&async function(e){const t=await ue(e);if(!t)return!1;h(t,!0,new Date(Date.now()+5e3))}(e.queueId),a}return i(`Not showing message with queueId ${e.queueId} because its already loading.`),!1}async function qe(){if(N())if(Re.isDocumentVisible)if(null===p(C)){var e=await async function(){var e;try{if(!k){k=!0;var t={"X-Gist-User-Anonymous":A(),"Content-Language":null!==p(T)?p(T):navigator.language};e=await x().post(`/api/v3/users?sessionId=${q()}`,{},{headers:t})}}catch(t){t.response?e=t.response:i(`Error getting user queue: ${t}`)}finally{k=!1,function(e){if(e&&e.headers){var t=e.headers["x-gist-queue-polling-interval"];t&&t>0&&(D=t)}var n=new Date((new Date).getTime()+1e3*D);h(C,D,n)}(e),function(e){const t="true"===e?.headers?.["x-cio-use-sse"]?.toLowerCase();$.setUseSSEFlag(t)}(e)}return e}(),t=[];e?(200===e.status||204===e.status?(i("200 response, updating local store."),oe(t=e.data),Y(t)):304===e.status&&i("304 response, using local store."),await Ce()):i("There was an error while checking message queue.")}else i("Next queue pull scheduled for later.");else i("Document not visible, skipping queue check.");else i("User token reset, skipping queue check.")}function Pe(e=!1){e&&$.removeActiveSSEConnection(),(e||$.isSSEConnectionManagedBySDK())&&$.setUseSSEFlag(!1),De&&(i("Stopping SSE queue listener..."),De.close(),De=null)}const Re=class{static async setup(e){this.events=new s,this.config={useAnonymousSession:void 0!==e.useAnonymousSession&&e.useAnonymousSession,siteId:e.siteId,dataCenter:e.dataCenter,env:void 0===e.env?"prod":e.env,logging:void 0!==e.logging&&e.logging,experiments:void 0!==e.experiments&&e.experiments},this.currentMessages=[],this.overlayInstanceId=null,this.currentRoute=null,this.isDocumentVisible=!0,this.config.isPreviewSession=function(){const e=new URLSearchParams(window.location.search).get("cioPreviewId");return e&&(sessionStorage.setItem(f,!1),Re.setUserToken(e),i(`Preview mode enabled with user token: ${e}`)),!v()}(),i(`Setup complete on ${this.config.env} environment.`),!this.config.isPreviewSession&&this.config.useAnonymousSession&&U(),await ke(),document.addEventListener("visibilitychange",(async()=>{"hidden"===document.visibilityState?this.isDocumentVisible=!1:(this.isDocumentVisible=!0,await Ce())}),!1)}static async setCurrentRoute(e){this.currentRoute=e,i(`Current route set to: ${e}`),await Ce()}static async setUserToken(e,t){this.config.isPreviewSession||(function(e,t){void 0===t&&(t=new Date).setDate(t.getDate()+30),h(P,e,t),A()&&(w(C),w(R)),i(`Set user token "${e}" with expiry date set to ${t}`)}(e,t),Pe(!0),await ke())}static setUserLocale(e){var t;h(T,t=e),i(`Set user locate to "${t}"`)}static async clearUserToken(){this.config.isPreviewSession||(w(P),i("Cleared user token"),this.config.useAnonymousSession&&U(),Pe(!0),await ke())}static async dismissMessage(e){var t=ve(e);await le(t),await me(t),await $e(t),await Ce()}static async embedMessage(e,t){var n=await ge(e,t);return n?n.instanceId:null}static async showMessage(e){var t=await de(e);return t?t.instanceId:null}static messageShown(e){i(`Message shown: ${e.messageId}`),this.events.dispatch("messageShown",e)}static messageDismissed(e){null!==e&&(i(`Message dismissed: ${e.messageId}`),this.events.dispatch("messageDismissed",e))}static messageError(e){i(`Message error: ${e.messageId}`),this.events.dispatch("messageError",e)}static messageAction(e,t,n){i(`Message action: ${e.currentRoute}, ${t} with name ${n} on ${e.instanceId}`),this.events.dispatch("messageAction",{message:e,action:t,name:n})}}},44:(e,t,n)=>{const s=n(548).A;e.exports=s}},t={};function n(s){var i=t[s];if(void 0!==i)return i.exports;var a=t[s]={exports:{}};return e[s](a,a.exports,n),a.exports}return n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n(44)})()));