import{aJ as q,aK as O}from"./index-DPpyTdg2.js";import{d as Ke,g as Ye}from"./react-DJqlvk1W.js";import{v as B}from"./utils-Jo7XZaji.js";import"./vendors-DPMU6Zta.js";import"./analytics-BRpNfSMK.js";import"./dateTime-Cton7xtx.js";import"./ui-DY4hnbsq.js";import"./media-BiyCxrPz.js";import"./icons-t4gaE5mF.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},t=new Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="553a438a-9832-4941-8a7c-e32443cdd164",e._sentryDebugIdIdentifier="sentry-dbid-553a438a-9832-4941-8a7c-e32443cdd164")}catch{}})();var E;(function(e){e.MessageOpened="in-app:message-opened",e.MessageDismissed="in-app:message-dismissed",e.MessageError="in-app:message-error",e.MessageAction="in-app:message-action"})(E||(E={}));var ge=Object.values(E),I;(function(e){e.Metric="Report Delivery Event",e.Content="Report Content Event",e.Opened="opened",e.Clicked="clicked",e.ViewedContent="viewed_content",e.ClickedContent="clicked_content"})(I||(I={}));var ve="in_app_content";function X(e,t){return new CustomEvent(e,{detail:t})}function Ze(e){switch(e){case"messageShown":return E.MessageOpened;case"messageDismissed":return E.MessageDismissed;case"messageError":return E.MessageError;case"messageAction":return E.MessageAction;default:return""}}class et{on(t,i){var s=this[t];s?s.push(i):this[t]=[i]}dispatch(t,i){var s=this[t];s&&s.forEach(a=>a(i))}}function o(e){u.config.logging&&console.log(`Gist: ${e}`)}const tt=365,ee="gist.web.isPersistingSession";function it(e){sessionStorage.setItem(ee,e)}function p(e,t,i=null){var s=i;s||(s=new Date,s.setDate(s.getDate()+tt));const a={value:t,expiry:s};ne().setItem(e,JSON.stringify(a))}function h(e){const t=ne().getItem(e);if(!t)return null;const i=JSON.parse(t);return new Date().getTime()>new Date(i.expiry).getTime()?(M(e),null):i.value}function M(e){ne().removeItem(e)}function Le(){const e=sessionStorage.getItem(ee);return e===null?(sessionStorage.setItem(ee,"true"),!0):e==="true"}function ne(){return Le()?localStorage:sessionStorage}const he="gist.web.userQueueVersion",me="gist.web.userQueueUseSSE",pe="gist.web.activeSSEConnection",f={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://gist-queue-consumer-api.cloud.gist.build",dev:"https://gist-queue-consumer-api.cloud.dev.gist.build",local:"http://api.local.gist.build:86"},GIST_QUEUE_V3_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"},getQueueAPIVersion:function(){return h(he)??"2"},setQueueAPIVersion:function(e){p(he,e,new Date(new Date().getTime()+18e5)),o(`Set user queue version to "${e}"`)},useSSE:function(){return h(me)??!1},setUseSSEFlag:function(e){p(me,e,new Date(new Date().getTime()+6e4)),o(`Set user uses SSE to "${e}"`)},setActiveSSEConnection:function(){p(pe,!0,new Date(new Date().getTime()+31e3))},hasActiveSSEConnection:function(){return h(pe)??!1}};function V(){const e=f.getQueueAPIVersion()==="3"?f.GIST_QUEUE_V3_API_ENDPOINT[u.config.env]:f.GIST_QUEUE_API_ENDPOINT[u.config.env],t={"X-CIO-Site-Id":u.config.siteId,"X-CIO-Client-Platform":"web"},i=Te();i!=null&&(t["X-Gist-Encoded-User-Token"]=i);async function s(a,r={}){const m=e+a,d=new AbortController,C=setTimeout(()=>d.abort(),5e3);try{const g=await fetch(m,{method:r.method||"GET",headers:{...t,...r.headers||{}},body:r.method&&r.method.toUpperCase()!=="GET"?r.body:void 0,signal:d.signal});clearTimeout(C);const n=g.headers.get("content-type")?.includes("application/json")?await g.json():await g.text(),c=Object.fromEntries(g.headers.entries());if(g.status<200||g.status>=400)throw{response:{status:g.status,data:n,headers:c}};return{status:g.status,headers:c,data:n}}catch(g){throw clearTimeout(C),g.response||(g.response={status:0,data:g.message||"Unknown error"}),g}}return s.post=(a,r={},m={})=>s(a,{method:"POST",body:JSON.stringify(r),headers:{"Content-Type":"application/json",...m.headers||{}}}),s}const te="gist.web.userLocale";function st(){return h(te)!==null?h(te):navigator.language}function nt(e){p(te,e),o(`Set user locate to "${e}"`)}const ot=600;var J=ot,K=!1;const G="gist.web.userQueueNextPullCheck",we="gist.web.sessionId";async function at(){var e;try{if(!K){K=!0;var t={"X-Gist-User-Anonymous":ae(),"Content-Language":st()};if(f.getQueueAPIVersion()==="3")e=await V().post(`/api/v3/users?sessionId=${$e()}`,{},{headers:t});else{var i=new Date().getTime();e=await V().post(`/api/v2/users?timestamp=${i}`,{},{headers:t})}}}catch(s){s.response?e=s.response:o(`Error getting user queue: ${s}`)}finally{K=!1,ct(e),rt(e),ut(e)}return e}function rt(e){if(e&&e.headers){var t=e.headers["x-cio-queue-version"];t&&f.setQueueAPIVersion(t)}}function ut(e){const t=e?.headers?.["x-cio-use-sse"]?.toLowerCase()==="true";f.setUseSSEFlag(t)}function $e(){var e=h(we);return e||(e=B()),p(we,e,new Date(new Date().getTime()+18e5)),e}function ct(e){if(e&&e.headers){var t=e.headers["x-gist-queue-polling-interval"];t&&t>0&&(J=t)}var i=new Date(new Date().getTime()+J*1e3);p(G,J,i)}function dt(){var e=Te();return e===null?(o("No user token available for SSE endpoint."),null):f.GIST_QUEUE_REALTIME_API_ENDPOINT[u.config.env]+`/api/v3/sse?userToken=${e}&siteId=${u.config.siteId}&sessionId=${$e()}`}const H="gist.web.userToken",oe="gist.web.usingGuestUserToken",Se="gist.web.guestUserToken",lt=30;function ae(){return h(oe)!==null}function R(){return h(H)}function ft(e,t){t===void 0&&(t=new Date,t.setDate(t.getDate()+lt)),p(H,e,t),ae()&&(M(G),M(oe)),o(`Set user token "${e}" with expiry date set to ${t}`)}function ye(){if(R()===null){var e=h(Se);e==null&&(e=B(),p(Se,e),o(`Set guest user token "${e}" with expiry date set to 1 year from today`)),p(H,e),p(oe,!0),o(`Using anonymous session with token: "${e}"`)}}function gt(){return ae()}async function F(){var e=R();return e===null?null:await ht(e)}function Te(){var e=R();return e===null?null:btoa(e)}function vt(){M(H),o("Cleared user token")}async function ht(e){const i=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(s)).map(m=>m.toString(16).padStart(2,"0")).join("")}async function mt(e){try{var t=await V().post(`/api/v1/logs/queue/${e}`);return t}catch(i){return i.response}}async function pt(e){try{var t=await V().post(`/api/v1/logs/message/${e}`);return t}catch(i){return i.response}}function D(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},i=e?.properties?.gist;return i?{isEmbedded:!!i.elementId,elementId:i.elementId||"",hasRouteRule:!!i.routeRuleWeb,routeRule:i.routeRuleWeb||"",position:i.position||"",hasPosition:!!i.position,shouldScale:!!i.scale,campaignId:i.campaignId??null,messageWidth:i.messageWidth>0?i.messageWidth:t.messageWidth,hasCustomWidth:i.messageWidth>0,overlayColor:i.overlayColor||t.overlayColor,persistent:!!i.persistent,exitClick:!!i.exitClick}:t}function wt(e,t,i){var s=800;t.messageWidth>s&&(s=t.messageWidth);var a=`
    <div id="gist-embed">
        <style>
            #x-gist-floating-top, #x-gist-floating-top-left, #x-gist-floating-top-right {
                position: fixed;
                top: 0px;
                z-index: 1000000;
            }
            #x-gist-floating-bottom, #x-gist-floating-bottom-left, #x-gist-floating-bottom-right {
                position: fixed;
                bottom: 0px;
                z-index: 1000000;
            }
            #x-gist-bottom, #x-gist-top, #x-gist-floating-top, #x-gist-floating-bottom {
                left: 50%;
                transform: translate(-50%, 0%);
            }
            #x-gist-floating-top-right, #x-gist-floating-bottom-right {
                right: 0px;
            }
            #gist-embed {
                position: relative;
                height: 100%;
                width: 100%;
            }
            #gist-embed-container {
                position: relative;
                height: 100%;
                width: 100%;
            }
            #gist-embed-container .gist-frame {
                height: 100%;
                width: 100%;
                border: none;
            }
            #x-gist-top.${e},
            #x-gist-bottom.${e},
            #x-gist-floating-top.${e},
            #x-gist-floating-bottom.${e},
            #x-gist-floating-top-left.${e},
            #x-gist-floating-top-right.${e},
            #x-gist-floating-bottom-left.${e},
            #x-gist-floating-bottom-right.${e} {
                transition: height 0.1s ease-in-out;
            }
            @media (max-width: ${s}px) {
                #x-gist-top.${e},
                #x-gist-bottom.${e},
                #x-gist-floating-top.${e},
                #x-gist-floating-bottom.${e},
                #x-gist-floating-top-left.${e},
                #x-gist-floating-top-right.${e},
                #x-gist-floating-bottom-left.${e},
                #x-gist-floating-bottom-right.${e} {
                    width: 100% !important;
                }
            }
        </style>
        <div id="gist-embed-container">
            <iframe id="${e}" class="gist-frame" src="${i}"></iframe>
        </div>
    </div>`;return a}function St(e,t,i){var s=600;t.messageWidth>s&&(s=t.messageWidth);var a=`
    <div id="gist-embed-message">
        <style>
            #gist-overlay.gist-background {
                position: fixed;
                z-index: 9999999998;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                background-color: ${t.overlayColor};
                visibility: hidden;
            }
            #gist-overlay.gist-background.gist-visible {
                visibility: visible;
            }
            .gist-message {
                width: ${t.messageWidth}px;
                position: absolute;
                border: none;
                opacity: 0;
                transition: opacity 0.3s ease-in-out, height 0.1s ease-in-out;
                z-index: 9999999999;
                left: 50%;
                transform: translateX(-50%);
            }
            .gist-message.gist-visible {
                opacity: 1;
                pointer-events: auto;
            }
            .gist-message.gist-center {
                transform: translate(-50%, -50%);
                top: 50%;
            }
            .gist-message.gist-bottom {
                bottom: 0;
            }
            .gist-message.gist-top {
                top: 0;
            }
            @media (max-width: ${s}px) {
                .gist-message {
                    width: 100%;
                }
            }
        </style>
        <div id="gist-overlay" class="gist-background">
            <iframe id="${e}" class="gist-message" src="${i}"></iframe>
        </div>
    </div>`;return a}var xe=["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"];function yt(e){const t=document.createElement("div");switch(t.id=e,e){case"x-gist-top":document.body.insertBefore(t,document.body.firstChild);break;default:document.body.insertAdjacentElement("beforeend",t);break}o("Top & bottom elements injected into page")}const bt=e=>new Promise(t=>setTimeout(t,e)),It=["x-gist-top","x-gist-bottom","x-gist-floating-top","x-gist-floating-bottom"];function Et(e){var t=N(e);return!!(t&&t.classList.contains("gist-visible"))}function Lt(e,t,i,s){var a=N(e);if(a){var r=U(i.instanceId);a.classList.add(r);var m=D(i),d=m.messageWidth+"px";It.includes(e)&&!m.hasCustomWidth&&(d="100%"),xe.includes(e)&&(a.style.width=d),ke(e)||(a.style.height="0px"),a.innerHTML=Ut(t,i,m),_e(r,s)}else o(`Message could not be embedded, elementId ${e} not found.`)}function $t(e){var t=N(e);t&&t.classList.add("gist-visible")}function Tt(e){var t=N(e);t&&(t.classList.remove("gist-visible"),t.style.removeProperty("height"),t.innerHTML="")}function ke(e){var t=N(e);if(t)return t.style&&t.style.height&&t.style.height!="0px"}function xt(e,t){var i=e.elementId?e.elementId:U(e.instanceId),s=N(i);if(s){var a=s.style;if(t.height>0)if(t.height>window.innerHeight){var r=1-(t.height/window.innerHeight-1);e.shouldScale&&r>=.4?(a.height=`${t.height}px`,a.transform=`translateX(-50%) translateY(-50%) scale(${r})`):a.height=`${window.innerHeight}px`}else a.height=`${t.height}px`}}function kt(e,t,i){document.body.insertAdjacentHTML("afterbegin",At(e,t)),_e(U(t.instanceId),i)}function _e(e,t){const i=document.getElementById(e);i&&(i.onload=function(){_t(e,t)})}function _t(e,t){const i=document.getElementById(e);i&&i.contentWindow&&i.contentWindow.postMessage({options:t},"*")}function Dt(e){var t=D(e),i=document.querySelector("#gist-overlay");if(i){i.classList.add("gist-visible");var s=document.querySelector(".gist-message");e.position?s.classList.add("gist-"+e.position):s.classList.add("gist-center"),setTimeout(Mt,100),t.exitClick&&setTimeout(()=>Nt(e.instanceId),1e3)}else re()}function Nt(e){var t=document.querySelector("#gist-overlay");t&&t.addEventListener("click",function(){u.dismissMessage(e)})}async function Ct(){var e=document.querySelector(".gist-message");e&&(e.classList.remove("gist-visible"),await bt(300)),re()}function re(){var e=document.querySelector("#gist-embed-message");e&&e.parentNode.removeChild(e)}function Pt(e,t){var i=N(U(e));i&&(i.title=t)}function U(e){return`gist-${e}`}function Mt(){var e=document.querySelector(".gist-message");e&&e.classList.add("gist-visible")}function Ut(e,t,i){var s=wt(U(t.instanceId),i,e);return s}function At(e,t){var i=D(t),s=St(U(t.instanceId),i,e);return s}function N(e){try{var t=document.querySelector(`#${e}`);return t||null}catch{return null}}const qt="gist.web.message.broadcasts",Ot=30;async function De(e){const t=await z();if(!t)return;const i=new Date;i.setDate(i.getDate()+Ot);const s=e.filter(j);p(t,s,i)}async function Rt(){const e=await z();return e?(h(e)??[]).filter(i=>{const{broadcast:s}=i.properties.gist,a=h(ue(e,i.queueId))??!0,r=h(Ce(e,i.queueId))||0,m=s.frequency.count===0;return a&&(m||r<s.frequency.count)}):[]}async function Qt(e){o(`Marking broadcast ${e} as seen.`);const t=await z();if(!t)return;const i=await Ne(t,e);if(!i)return;const{broadcast:s}=i.properties.gist,a=Ce(t,e),r=ue(t,e);let m=h(a)||0;if(p(a,m+1),s.frequency.count===1)p(r,!1),o(`Marked broadcast ${e} as seen.`);else{let d=new Date;d.setSeconds(d.getSeconds()+s.frequency.delay),p(r,!1,d),o(`Marked broadcast ${e} as seen, broadcast was seen ${m+1} times, next show date is ${d}.`)}}async function Vt(e){o(`Marking broadcast ${e} as dismissed.`);const t=await z();if(!t)return;const i=await Ne(t,e);if(!i)return;const{broadcast:s}=i.properties.gist;if(s.frequency.ignoreDismiss===!0){o(`Broadcast ${e} is set to ignore dismiss.`);return}const r=ue(t,e);p(r,!1),o(`Marked broadcast ${e} as dismissed and will not show again.`)}async function Ne(e,t){return h(e).find(s=>s.queueId===t)}function j(e){return e.properties&&e.properties.gist&&e.properties.gist.broadcast}function Wt(e){if(!j(e))return!1;const{broadcast:t}=e.properties.gist;return t.frequency.delay===0&&t.frequency.count===0}async function z(){const e=await F();return e?`${qt}.${e}`:null}function Ce(e,t){return`${e}.${t}.numberOfTimesShown`}function ue(e,t){return`${e}.${t}.shouldShow`}const ce="gist.web.message.user",Bt=6e4*60;async function Pe(e){const t=await Me();if(!t)return;const i=e.filter(a=>!(a.properties&&a.properties.gist&&a.properties.gist.broadcast)),s=new Date(Date.now()+Bt);p(t,i,s)}async function Gt(){const e=await Me();if(!e)return[];const t=h(e)??[],i=await Xt();return t.filter(s=>!i.includes(s.queueId))}async function Ht(e){const t=await Ue();if(!t)return;const i=h(t)??[];i.push(e),p(t,i)}async function Ft(e){const t=await de(e);return t?h(t)!==null:!1}async function jt(e){const t=await de(e);if(!t)return!1;p(t,!0,new Date(Date.now()+5e3))}async function zt(e){const t=await de(e);if(!t)return!1;M(t)}async function Xt(){const e=await Ue();return e?h(e)??[]:[]}async function Me(){const e=await F();return e?`${ce}.${e}`:null}async function Ue(){const e=await F();return e?`${ce}.${e}.seen`:null}async function de(e){const t=await F();return t?`${ce}.${t}.message.${e}.loading`:null}async function Ae(e){if(u.isDocumentVisible){if(u.overlayInstanceId)return o(`Message ${u.overlayInstanceId} already showing.`),null;var t=D(e);return e.instanceId=B(),e.overlay=!0,e.firstLoad=!0,e.shouldResizeHeight=!0,e.shouldScale=t.shouldScale,e.renderStartTime=new Date().getTime(),u.overlayInstanceId=e.instanceId,u.currentMessages.push(e),Ve(e)}else return o("Document hidden, not showing message now."),null}async function qe(e,t){return u.isDocumentVisible?(e.instanceId=B(),e.overlay=!1,e.firstLoad=!0,e.shouldScale=!1,e.elementId=t,e.shouldResizeHeight=!ke(t),e.renderStartTime=new Date().getTime(),u.currentMessages.push(e),Ve(e,t)):(o("Document hidden, not showing message now."),null)}async function ie(e){e?(u.messageDismissed(e),e.overlay?await Qe(!0,e):Re(e)):o(`Message with instance id: ${e.instanceId} not found`)}async function Oe(e){var t=D(e);e?t.persistent&&(o("Persistent message dismissed, logging view"),await Fe(e),await We(e)):o(`Message with instance id: ${e.instanceId} not found`)}function Re(e){le(e.instanceId),Tt(e.elementId)}async function Qe(e,t){e?await Ct():re(),u.currentMessages.length==0&&(window.removeEventListener("message",He),window.removeEventListener("touchstart",Ge)),le(t.instanceId),u.overlayInstanceId=null}function Ve(e,t=null){if(t&&Et(t))return o(`Message ${e.messageId} already showing in element ${t}.`),null;var i={endpoint:f.ENGINE_API_ENDPOINT[u.config.env],siteId:u.config.siteId,dataCenter:u.config.dataCenter,messageId:e.messageId,instanceId:e.instanceId,livePreview:!1,properties:e.properties},s=`${f.GIST_VIEW_ENDPOINT[u.config.env]}/index.html`;return window.addEventListener("message",He),window.addEventListener("touchstart",Ge),t?(xe.includes(t)&&yt(t),Lt(t,s,e,i)):kt(s,e,i),e}async function We(e){o(`Message shown, logging view for: ${e.messageId}`);var t={};e.queueId!=null?(await Fe(e),t=await mt(e.queueId)):t=await pt(e.messageId),t.status===200?o("Message view logged"):o(`Problem logging message: ${t.status}`)}function Be(e){return u.currentMessages.find(t=>t.instanceId===e)}function le(e){u.currentMessages=u.currentMessages.filter(t=>t.instanceId!==e)}function be(e,t){le(e),u.currentMessages.push(t)}function Ge(){}async function He(e){if(e.data.gist&&e.origin===f.RENDERER_HOST){var t=e.data.gist.instanceId,i=Be(t);if(!i)return;var s=D(i);switch(e.data.gist.method){case"routeLoaded":{var a=(new Date().getTime()-i.renderStartTime)*.001;o(`Engine render for message: ${i.messageId} timer elapsed in ${a.toFixed(3)} seconds`),zt(i.queueId),i.currentRoute=e.data.gist.parameters.route,i.firstLoad&&(i.overlay?Dt(i):$t(i.elementId),u.messageShown(i),s.persistent?o("Persistent message shown, skipping logging view"):await We(i),i.firstLoad=!1),be(t,i);break}case"tap":{var r=e.data.gist.parameters.action,m=e.data.gist.parameters.name;if(u.messageAction(i,r,m),e.data.gist.parameters.system&&!s.persistent){await ie(i);break}try{var d=new URL(r);if(d&&d.protocol==="gist:"){var C=d.href.replace("gist://","").split("?")[0];switch(C){case"close":await ie(i),await Oe(i),await je(i),await x();break;case"showMessage":var g=d.searchParams.get("messageId"),k=d.searchParams.get("properties");g&&(k&&(k=JSON.parse(atob(k))),await u.showMessage({messageId:g,properties:k}));break;case"loadPage":d=d.href.substring(d.href.indexOf("?url=")+5),d&&(d.startsWith("mailto:")||d.startsWith("https://")||d.startsWith("http://")||d.startsWith("/")?window.location.href=d:window.location.href=window.location+d);break}}}catch{}break}case"routeChanged":{i.currentRoute=e.data.gist.parameters.route,i.renderStartTime=new Date().getTime(),be(t,i),o(`Route changed to: ${i.currentRoute}`);break}case"sizeChanged":{o(`Size Changed Width: ${e.data.gist.parameters.width} - Height: ${e.data.gist.parameters.height}`),(!i.elementId||i.shouldResizeHeight)&&xt(i,e.data.gist.parameters);break}case"titleChanged":{o(`Overlay title changed to: ${e.data.gist.parameters.title}`),Pt(t,e.data.gist.parameters.title);break}case"eventDispatched":{u.events.dispatch("eventDispatched",{name:e.data.gist.parameters.name,payload:e.data.gist.parameters.payload});break}case"error":case"routeError":{u.messageError(i),u.overlayInstanceId?Qe(!1,i):Re(i);break}}}}async function Fe(e){o(`Logging user message view locally for: ${e.queueId}`),j(e)?await Qt(e.queueId):await Ht(e.queueId)}async function je(e){j(e)&&(o(`Logging broadcast dismissed locally for: ${e.queueId}`),await Vt(e.queueId))}var Jt=e=>new Promise(t=>setTimeout(t,e)),ze=(e,t)=>e().then(Jt(t).then(()=>ze(e,t))),Ie=!1;let T=null;async function Y(){Ie?await x():R()?(o("Queue watcher started"),Ie=!0,ze(()=>new Promise(()=>Yt()),1e3)):o("User token not setup, queue not started.")}async function x(){var e=await Rt(),t=await Gt(),i=e.concat(t);o(`Messages in local queue: ${i.length}`);var s=i.sort((a,r)=>a.priority-r.priority);for(const a of s)await Kt(a)}async function Kt(e){var t=D(e);if(t.hasRouteRule){var i=u.currentRoute;i==null&&(i=new URL(window.location.href).pathname);var s=t.routeRule;o(`Verifying route ${i} against rule: ${s}`);var a=new RegExp(s);if(!a.test(i))return o(`Route ${i} does not match rule.`),!1}if(t.hasPosition&&(e.position=t.position),!t.persistent&&!Wt(e)&&await Ft(e.queueId))return o(`Not showing message with queueId ${e.queueId} because its already loading.`),!1;var r=!1;return t.isEmbedded?r=await qe(e,t.elementId):r=await Ae(e),r&&jt(e.queueId),r}async function Yt(){if(f.hasActiveSSEConnection()){await x();return}if(f.useSSE()&&!gt()){await Xe();return}await se()}async function se(){if(R())if(u.isDocumentVisible)if(h(G)===null){var e=await at(),t=[];e?(e.status===200||e.status===204?(o("200 response, updating local store."),t=e.data,Pe(t),De(t)):e.status===304&&o("304 response, using local store."),await x()):o("There was an error while checking message queue.")}else o("Next queue pull scheduled for later.");else o("Document not visible, skipping queue check.");else o("User token reset, skipping queue check.")}async function Xe(){const e=dt();if(e===null){o("SSE endpoint not available, falling back to polling."),await se();return}o(`Starting SSE queue listener on ${e}`),T=new EventSource(e),f.setActiveSSEConnection(),T.addEventListener("connected",async t=>{o("SSE connection received:"),f.setActiveSSEConnection(),f.setUseSSEFlag(!0),M(G),await se()}),T.addEventListener("messages",async t=>{try{var i=JSON.parse(t.data);o("SSE message received:",i),await Pe(i),await De(i),await x()}catch{o("Failed to parse SSE message"),W()}}),T.addEventListener("error",async t=>{o("SSE error received:"),W()}),T.addEventListener("heartbeat",async t=>{o("SSE heartbeat received:"),f.setActiveSSEConnection(),f.setUseSSEFlag(!0)})}function W(){T&&(o("Stopping SSE queue listener..."),T.close(),T=null,f.setUseSSEFlag(!1))}const Zt="cioPreviewId";function ei(){const e=ti();return e&&(it(!1),u.setUserToken(e),o(`Preview mode enabled with user token: ${e}`)),!Le()}function ti(){return new URLSearchParams(window.location.search).get(Zt)}class u{static async setup(t){this.events=new et,this.config={useAnonymousSession:t.useAnonymousSession===void 0?!1:t.useAnonymousSession,siteId:t.siteId,dataCenter:t.dataCenter,env:t.env===void 0?"prod":t.env,logging:t.logging===void 0?!1:t.logging,experiments:t.experiments===void 0?!1:t.experiments},this.currentMessages=[],this.overlayInstanceId=null,this.currentRoute=null,this.isDocumentVisible=!0,this.config.isPreviewSession=ei(),o(`Setup complete on ${this.config.env} environment.`),!this.config.isPreviewSession&&this.config.useAnonymousSession&&ye(),await Y(),document.addEventListener("visibilitychange",async()=>{document.visibilityState==="hidden"?this.isDocumentVisible=!1:(this.isDocumentVisible=!0,await x())},!1)}static async setCurrentRoute(t){this.currentRoute=t,o(`Current route set to: ${t}`),await x()}static async setUserToken(t,i){if(this.config.isPreviewSession)return;const s=f.hasActiveSSEConnection();W(),ft(t,i),s&&(f.setUseSSEFlag(!0),await Xe()),await Y()}static setUserLocale(t){nt(t)}static async clearUserToken(){this.config.isPreviewSession||(vt(),this.config.useAnonymousSession&&ye(),W(),await Y())}static async dismissMessage(t){var i=Be(t);await ie(i),await Oe(i),await je(i),await x()}static async embedMessage(t,i){var s=await qe(t,i);return s?s.instanceId:null}static async showMessage(t){var i=await Ae(t);return i?i.instanceId:null}static messageShown(t){o(`Message shown: ${t.messageId}`),this.events.dispatch("messageShown",t)}static messageDismissed(t){t!==null&&(o(`Message dismissed: ${t.messageId}`),this.events.dispatch("messageDismissed",t))}static messageError(t){o(`Message error: ${t.messageId}`),this.events.dispatch("messageError",t)}static messageAction(t,i,s){o(`Message action: ${t.currentRoute}, ${i} with name ${s} on ${t.instanceId}`),this.events.dispatch("messageAction",{message:t,action:i,name:s})}}const ii=Object.freeze(Object.defineProperty({__proto__:null,default:u},Symbol.toStringTag,{value:"Module"})),si=Ke(ii);var Z,Ee;function ni(){return Ee||(Ee=1,Z=si.default),Z}var oi=ni();const b=Ye(oi);function mi(e){var t=this,i,s=!1,a=!1,r=new EventTarget;function m(){!s||a||(i.on("reset",C),e.events&&(ge.forEach(function(n){r.addEventListener(n,e?.events)}),["messageDismissed","messageError"].forEach(function(n){b.events.on(n,function(c){var l,v;r.dispatchEvent(X(Ze(n),{messageId:c.messageId,deliveryId:(v=(l=c.properties)===null||l===void 0?void 0:l.gist)===null||v===void 0?void 0:v.campaignId}))})})),b.events.on("messageShown",function(n){var c,l,v,w,y,S,L,_,$=(l=(c=n?.properties)===null||c===void 0?void 0:c.gist)===null||l===void 0?void 0:l.campaignId;if(e.events&&r.dispatchEvent(X(E.MessageOpened,{messageId:n?.messageId,deliveryId:$,message:{dismiss:function(){b.dismissMessage(n?.instanceId)}}})),typeof $<"u"&&$!=""){i.track(I.Metric,{deliveryId:$,metric:I.Opened});return}var P=(y=(w=(v=n?.properties)===null||v===void 0?void 0:v.gist)===null||w===void 0?void 0:w.broadcast)===null||y===void 0?void 0:y.broadcastIdInt;if(P){var A=(_=(L=(S=n?.properties)===null||S===void 0?void 0:S.gist)===null||L===void 0?void 0:L.broadcast)===null||_===void 0?void 0:_.templateId;i.track(I.Content,{actionType:I.ViewedContent,contentId:P,templateId:A,contentType:ve})}}),b.events.on("messageAction",function(n){var c,l,v,w,y,S,L,_,$,P,A,Q=(v=(l=(c=n?.message)===null||c===void 0?void 0:c.properties)===null||l===void 0?void 0:l.gist)===null||v===void 0?void 0:v.campaignId;if(e.events&&r.dispatchEvent(X(E.MessageAction,{messageId:n.message.messageId,deliveryId:Q,action:n.action,name:n.name,actionName:n.name,actionValue:n.action,message:{dismiss:function(){b.dismissMessage(n.message.instanceId)}}})),n.action!="gist://close"){if(typeof Q<"u"&&Q!=""){i.track(I.Metric,{deliveryId:Q,metric:I.Clicked,actionName:n.name,actionValue:n.action});return}var fe=(L=(S=(y=(w=n?.message)===null||w===void 0?void 0:w.properties)===null||y===void 0?void 0:y.gist)===null||S===void 0?void 0:S.broadcast)===null||L===void 0?void 0:L.broadcastIdInt;if(fe){var Je=(A=(P=($=(_=n?.message)===null||_===void 0?void 0:_.properties)===null||$===void 0?void 0:$.gist)===null||P===void 0?void 0:P.broadcast)===null||A===void 0?void 0:A.templateId;i.track(I.Content,{actionType:I.ClickedContent,contentId:fe,templateId:Je,contentType:ve,actionName:n.name,actionValue:n.action})}}}),b.events.on("eventDispatched",function(n){var c,l,v;if(n.name=="analytics:track"){var w=(c=n.payload)===null||c===void 0?void 0:c.event;if(typeof w>"u"||w=="")return;i.track(w,(l=n.payload)===null||l===void 0?void 0:l.properties,(v=n.payload)===null||v===void 0?void 0:v.options)}}))}function d(n){var c,l,v,w,y;return q(this,void 0,void 0,function(){var S;return O(this,function(L){return a?(S=(v=(l=(c=n.event)===null||c===void 0?void 0:c.properties)===null||l===void 0?void 0:l.name)!==null&&v!==void 0?v:(y=(w=n.event)===null||w===void 0?void 0:w.properties)===null||y===void 0?void 0:y.url,typeof S=="string"&&S.length>0&&b.setCurrentRoute(S),[2,n]):[2,n]})})}function C(n){return q(this,void 0,void 0,function(){return O(this,function(c){switch(c.label){case 0:return[4,b.clearUserToken()];case 1:return c.sent(),[2,n]}})})}function g(n){return q(this,void 0,void 0,function(){var c;return O(this,function(l){switch(l.label){case 0:return s?(c=i.user().id(),typeof c=="string"&&c.length>0?[4,b.setUserToken(c)]:[3,2]):[2,n];case 1:return l.sent(),[3,4];case 2:return[4,b.clearUserToken()];case 3:l.sent(),l.label=4;case 4:return[2,n]}})})}var k={name:"Customer.io In-App Plugin",type:"before",version:"0.0.1",isLoaded:function(){return a},load:function(n,c){return q(t,void 0,void 0,function(){return O(this,function(l){switch(l.label){case 0:return i=c,e.siteId==null||e.siteId==""?(ai("siteId is required. Can't initialize."),[2,n]):[4,b.setup({siteId:e.siteId,env:e._env?e._env:"prod",logging:e._logging,useAnonymousSession:e.anonymousInApp})];case 1:return l.sent(),s=!0,[4,g(n)];case 2:return l.sent(),m(),a=!0,[2,Promise.resolve()]}})})},identify:g,page:d,unload:function(){return q(t,void 0,void 0,function(){return O(this,function(n){return e.events&&ge.forEach(function(c){r.removeEventListener(c,e?.events)}),[2]})})}};return k}function ai(e){console.error("[Customer.io In-App Plugin] ".concat(e))}export{E as InAppEvents,mi as InAppPlugin};
//# sourceMappingURL=index-BFxCn7X3.js.map