customerio-gist-web 3.20.1 → 3.20.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gist.min.js +1 -1
- package/dist/types/gist.d.ts +4 -4
- package/dist/types/managers/custom-attribute-manager.d.ts +5 -5
- package/dist/types/managers/gist-properties-manager.d.ts +2 -15
- package/dist/types/managers/inbox-message-manager.d.ts +15 -5
- package/dist/types/managers/locale-manager.d.ts +2 -2
- package/dist/types/managers/message-broadcast-manager.d.ts +7 -6
- package/dist/types/managers/message-component-manager.d.ts +29 -12
- package/dist/types/managers/message-manager.d.ts +7 -6
- package/dist/types/managers/message-user-queue-manager.d.ts +10 -9
- package/dist/types/managers/page-component-manager.d.ts +2 -2
- package/dist/types/managers/queue-manager.d.ts +5 -5
- package/dist/types/managers/user-manager.d.ts +8 -8
- package/package.json +1 -1
package/dist/gist.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!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,()=>(()=>{"use strict";var e={d:(t,s)=>{for(var n in s)e.o(s,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:s[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{default:()=>Ke});class s{constructor(){this.callbacks={}}on(e,t){const s=this.callbacks[e];s?s.push(t):this.callbacks[e]=[t]}off(e,t){const s=this.callbacks[e];if(!s)return;if(!t)return void delete this.callbacks[e];const n=s.indexOf(t);-1!==n&&s.splice(n,1),0===s.length&&delete this.callbacks[e]}dispatch(e,t){const s=this.callbacks[e];s&&s.forEach(e=>e(t))}}function n(e){Ke.config&&Ke.config.logging&&console.log(`Gist: ${e}`)}const i="gist.web.isPersistingSession";function a(e,t,s=null){let n=s;n||(n=new Date,n.setDate(n.getDate()+365));const i={value:t,expiry:n};u().setItem(e,JSON.stringify(i))}function o(e){return l(e)}function r(e){u().removeItem(e)}function c(){const e=sessionStorage.getItem(i);return null===e?(sessionStorage.setItem(i,"true"),!0):"true"===e}function u(){return c()?localStorage:sessionStorage}function l(e){if(!e)return null;try{const t=u().getItem(e);if(!t)return null;const s=JSON.parse(t);if(!s.expiry)return s.value;const n=new Date,i=new Date(s.expiry),a=e.startsWith("gist.web.message.broadcasts")&&!e.endsWith("shouldShow")&&!e.endsWith("numberOfTimesShown")||e.startsWith("gist.web.message.user")&&!e.endsWith("seen")&&!e.endsWith("state"),o=new Date(n.getTime()+366e4);return a&&i.getTime()>o.getTime()||n.getTime()>i.getTime()?(r(e),null):s.value}catch(t){n(`Error checking key ${e} for expiry: ${t}`)}return null}var d,g=new Uint8Array(16);function m(){if(!d&&!(d="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 d(g)}const p=/^(?:[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 f=[],h=0;h<256;++h)f.push((h+256).toString(16).substr(1));const y=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,s=(f[e[t+0]]+f[e[t+1]]+f[e[t+2]]+f[e[t+3]]+"-"+f[e[t+4]]+f[e[t+5]]+"-"+f[e[t+6]]+f[e[t+7]]+"-"+f[e[t+8]]+f[e[t+9]]+"-"+f[e[t+10]]+f[e[t+11]]+f[e[t+12]]+f[e[t+13]]+f[e[t+14]]+f[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&p.test(e)}(s))throw TypeError("Stringified UUID is invalid");return s},w=function(e,t,s){var n=(e=e||{}).random||(e.rng||m)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){s=s||0;for(var i=0;i<16;++i)t[s+i]=n[i];return t}return y(n)},v="gist.web.userQueueUseSSE",b="gist.web.activeSSEConnection";let S,I=30;const x={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:()=>(S||(S=w()),S),useSSE:()=>o(v)??!1,setUseSSEFlag(e){a(v,e,new Date((new Date).getTime()+6e4)),n(`Set user uses SSE to "${e}"`)},removeActiveSSEConnection(){r(b)},setActiveSSEConnection(){a(b,x.getSdkId(),new Date((new Date).getTime()+x.getSSEHeartbeat()))},hasActiveSSEConnection:()=>o(b)??!1,isSSEConnectionManagedBySDK:()=>o(b)===x.getSdkId(),getSSEHeartbeat:()=>1e3*(I+5),setSSEHeartbeat(e){e&&e>0&&(I=e)}};function $(e){return null!==e&&"object"==typeof e&&"response"in e}function E(e){return $(e)?e.response:void 0}function C(){const e=x.GIST_QUEUE_API_ENDPOINT[Ke.config.env??"prod"],t={"X-CIO-Site-Id":Ke.config.siteId,"X-CIO-Client-Platform":"web"},s=_();async function n(s,n={}){const i=e+s,a=new AbortController,o=setTimeout(()=>a.abort(),5e3);try{const e=await fetch(i,{method:n.method||"GET",headers:{...t,...n.headers||{}},body:n.method&&"GET"!==n.method.toUpperCase()?n.body:void 0,signal:a.signal});clearTimeout(o);const s=e.headers.get("content-type")?.includes("application/json"),r=s?await e.json():await e.text(),c=Object.fromEntries(e.headers.entries());if(e.status<200||e.status>=400)throw function(e){return Object.assign(new Error,{response:e})}({status:e.status,data:r,headers:c});return{status:e.status,headers:c,data:r}}catch(e){if(clearTimeout(o),$(e))throw e;if(e instanceof Error)throw Object.assign(e,{response:{status:0,data:e.message||"Unknown error",headers:{}}});throw e}}return null!=s&&(t["X-Gist-Encoded-User-Token"]=s),n.post=(e,t={},s={})=>n(e,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",...s.headers||{}}}),n}const D="gist.web.userLocale";let k=600,T=!1;const M="gist.web.userQueueNextPullCheck",q="gist.web.sessionId";function R(){let e=o(q);return e||(e=w()),a(q,e,new Date((new Date).getTime()+18e5)),String(e)}const P="gist.web.userToken",N="gist.web.usingGuestUserToken",L="gist.web.guestUserToken";function W(){return null!==o(N)}function A(){return o(P)}function O(){if(null===A()){var e=o(L);null==e&&(e=w(),a(L,e),n(`Set guest user token "${e}" with expiry date set to 1 year from today`)),a(P,e),a(N,!0),n(`Using anonymous session with token: "${e}"`)}}async function U(){var e=A();return null===e?null:await async function(e){const t=(new TextEncoder).encode(e),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(e=>e.toString(16).padStart(2,"0")).join("")}(e)}function _(){var e=A();return null===e?null:btoa(e)}async function j(e){try{return await C().post(`/api/v1/logs/queue/${e}`)}catch(e){return E(e)}}function H(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},s=e?.properties?.gist;return s?{isEmbedded:!!s.elementId,elementId:s.elementId||"",hasRouteRule:!!s.routeRuleWeb,routeRule:s.routeRuleWeb||"",position:s.position||"",hasPosition:!!s.position,shouldScale:!!s.scale,campaignId:s.campaignId??null,messageWidth:s.messageWidth>0?s.messageWidth:t.messageWidth,hasCustomWidth:s.messageWidth>0,overlayColor:s.overlayColor||t.overlayColor,persistent:!!s.persistent,exitClick:!!s.exitClick}:t}var z=["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 G(e){if(document.getElementById(e))return;const t=document.createElement("div");t.id=e,"x-gist-top"===e?document.body.insertBefore(t,document.body.firstChild):document.body.insertAdjacentElement("beforeend",t),n("Top & bottom elements injected into page")}const V=["x-gist-top","x-gist-bottom","x-gist-floating-top","x-gist-floating-bottom"];function F(e){return Ke.currentMessages.find(t=>t.instanceId===e)}function B(e){return!!e&&Ke.currentMessages.some(t=>t.queueId===e)}function J(e){return e?Ke.currentMessages.find(t=>t.elementId===e)??null:null}function Q(e){Ke.currentMessages=Ke.currentMessages.filter(t=>t.instanceId!==e)}function X(e,t){Q(e),Ke.currentMessages.push(t)}function K(e){const t={topLeft:"x-gist-floating-top-left",topCenter:"x-gist-floating-top",topRight:"x-gist-floating-top-right",bottomLeft:"x-gist-floating-bottom-left",bottomCenter:"x-gist-floating-bottom",bottomRight:"x-gist-floating-bottom-right"};return e&&t[e]?t[e]:(n(`Invalid overlay position "${e}", defaulting to "topCenter"`),t.topCenter)}function Y(e,t){if(e.properties||(e.properties={}),e.properties.gist||(e.properties.gist={}),"modal"===t.displayType)e.overlay=!0,e.elementId=null,e.properties.gist.elementId=null,e.position=t.modalPosition||"center",e.properties.gist.position=t.modalPosition||"center";else if("overlay"===t.displayType){e.overlay=!1;const s=K(t.overlayPosition);e.elementId=s,e.properties.gist.elementId=s,e.position=null,e.properties.gist.position=null}else"inline"===t.displayType&&(e.overlay=!1,e.elementId=t.elementSelector,e.properties.gist.elementId=t.elementSelector,e.position=null,e.properties.gist.position=null);e.elementId&&V.includes(e.elementId)?delete e.properties.gist.messageWidth:void 0!==t.maxWidth&&t.maxWidth>0?e.properties.gist.messageWidth=t.maxWidth:delete e.properties.gist.messageWidth,void 0!==t.overlayColor?e.properties.gist.overlayColor=t.overlayColor:delete e.properties.gist.overlayColor,void 0!==t.dismissOutsideClick?e.properties.gist.exitClick=t.dismissOutsideClick:delete e.properties.gist.exitClick}function Z(e){var t=ce(e);t&&(t.classList.remove("gist-visible"),Array.from(t.classList).filter(e=>e.startsWith("gist-")).forEach(e=>t.classList.remove(e)),t.style.removeProperty("height"),t.style.removeProperty("width"),t.innerHTML="")}function ee(e){var t=ce(e);if(t)return t.style&&t.style.height&&"0px"!=t.style.height}function te(e,t,s=null){const n=document.getElementById(e);n&&(n.onload=function(){!function(e,t,s=null){const n=document.getElementById(e);if(n&&n.contentWindow){const e={options:t,capabilities:se};s&&(t.stepId=s),n.contentWindow.postMessage(e,"*")}}(e,t,s)})}const se=["MultiStepDisplayTypes"];function ne(e){if(!e.displaySettings)return;const t=oe(e.instanceId),s=document.getElementById(t);s&&s.contentWindow&&s.contentWindow.postMessage({action:"updateDisplaySettings",displaySettings:e.displaySettings},"*")}async function ie(){var e=document.querySelector(".gist-message");e&&(e.classList.remove("gist-visible"),await new Promise(e=>setTimeout(e,300))),ae()}function ae(){var e=document.querySelector("#gist-embed-message");e&&e.parentNode.removeChild(e)}function oe(e){return`gist-${e}`}function re(){var e=document.querySelector(".gist-message");e&&e.classList.add("gist-visible")}function ce(e){try{return document.querySelector(`#${e}`)||null}catch{return null}}const ue="gist.web.customAttributes";let le=new Map;function de(){const e=Array.from(le.entries()),t=new Date;t.setDate(t.getDate()+30),a(ue,e,t),n(`Saved ${le.size} custom attributes to storage with TTL of 30 days`)}async function ge(e){const t=await he();if(!t)return;const s=new Date;s.setMinutes(s.getMinutes()+60),a(t,e.filter(pe),s)}async function me(e,t){return o(e).find(e=>e.queueId===t)}function pe(e){return e.properties&&e.properties.gist&&e.properties.gist.broadcast}function fe(e){if(!pe(e))return!1;const{broadcast:t}=e.properties.gist;return 0===t.frequency.delay&&0===t.frequency.count}async function he(){const e=await U();return e?`gist.web.message.broadcasts.${e}`:null}function ye(e,t){return`${e}.${t}.numberOfTimesShown`}function we(e,t){return`${e}.${t}.shouldShow`}!function(){const e=o(ue);if(e)try{le=new Map(e)}catch{le=new Map}else le=new Map}();const ve="gist.web.message.user";async function be(e){const t=await Se();if(!t)return;const s=e.filter(e=>!(e.properties&&e.properties.gist&&e.properties.gist.broadcast)),n=new Date;n.setMinutes(n.getMinutes()+60),a(t,s,n)}async function Se(){const e=await U();return e?`${ve}.${e}`:null}async function Ie(){const e=await U();return e?`${ve}.${e}.seen`:null}async function xe(e){const t=await U();return t?`${ve}.${t}.message.${e}.loading`:null}async function $e(e){const t=await U();return t?`${ve}.${t}.message.${e}.state`:null}async function Ee(e){const t=await $e(e);t&&(r(t),n(`Cleared message state for queueId: ${e}`))}async function Ce(e){if(Ke.isDocumentVisible){if(B(e.queueId))return n(`Message with queueId ${e.queueId} is already showing.`),null;if(Ke.overlayInstanceId)return n(`Message ${Ke.overlayInstanceId} already showing.`),null;var t=H(e);return e.instanceId=w(),e.overlay=!0,e.firstLoad=!0,e.shouldResizeHeight=!0,e.shouldScale=t.shouldScale,e.renderStartTime=(new Date).getTime(),Ke.overlayInstanceId=e.instanceId,Ke.currentMessages.push(e),Pe(e,null,e.savedStepName||null)}return n("Document hidden, not showing message now."),null}function De(e,t){return Ke.isDocumentVisible?B(e.queueId)?(n(`Message with queueId ${e.queueId} is already showing.`),null):J(t)?(n(`Message with elementId ${t} already has a message.`),null):(e.instanceId=w(),e.overlay=!1,e.firstLoad=!0,e.shouldScale=!1,e.elementId=t,e.shouldResizeHeight=!ee(t),e.renderStartTime=(new Date).getTime(),Ke.currentMessages.push(e),Pe(e,t,e.savedStepName||null)):(n("Document hidden, not showing message now."),null)}async function ke(e){e?(Ke.messageDismissed(e),await Te(e)):n(`Message with instance id: ${e.instanceId} not found`)}async function Te(e){e.overlay?await Re(!0,e):qe(e)}async function Me(e){var t=H(e);e?t.persistent&&(n("Persistent message dismissed, logging view"),await Ae(e),await Ne(e),await Ee(e.queueId)):n(`Message with instance id: ${e.instanceId} not found`)}function qe(e){Q(e.instanceId),Z(e.elementId)}async function Re(e,t){e?await ie():ae(),0==Ke.currentMessages.length&&(window.removeEventListener("message",We),window.removeEventListener("touchstart",Le)),Q(t.instanceId),Ke.overlayInstanceId=null}function Pe(e,t=null,s=null){var i={endpoint:x.ENGINE_API_ENDPOINT[Ke.config.env],siteId:Ke.config.siteId,dataCenter:Ke.config.dataCenter,messageId:e.messageId,instanceId:e.instanceId,livePreview:!1,properties:e.properties,customAttributes:Object.fromEntries(new Map(le))},a=`${x.GIST_VIEW_ENDPOINT[Ke.config.env]}/index.html`;return window.addEventListener("message",We),window.addEventListener("touchstart",Le),t?(z.includes(t)&&G(t),function(e,t,s,i,a=null){var o=ce(e);if(o){var r=oe(s.instanceId);o.classList.add(r);var c=H(s),u=c.messageWidth+"px";V.includes(e)&&!c.hasCustomWidth&&(u="100%"),z.includes(e)&&(o.style.width=u),ee(e)||(o.style.height="0px"),o.innerHTML=function(e,t,s){var n=function(e,t,s){let n=800;return t.messageWidth>n&&(n=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: ${n}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="${s}"></iframe>\n </div>\n </div>`}(oe(t.instanceId),s,e);return n}(t,s,c),te(r,i,a)}else n(`Message could not be embedded, elementId ${e} not found.`)}(t,a,e,i,s)):function(e,t,s,n=null){document.querySelectorAll("#gist-embed-message").forEach(function(e){e.parentNode.removeChild(e)}),document.body.insertAdjacentHTML("afterbegin",function(e,t){var s=H(t),n=function(e,t,s){let n=600;return t.messageWidth>n&&(n=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: ${n}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="${s}"></iframe>\n </div>\n </div>`}(oe(t.instanceId),s,e);return n}(e,t)),te(oe(t.instanceId),s,n)}(a,e,i,s),e}async function Ne(e){n(`Message shown, logging view for: ${e.messageId}`);var t={};null!=e.queueId?(await Ae(e),t=await j(e.queueId)):t=await async function(e){try{return await C().post(`/api/v1/logs/message/${e}`)}catch(e){return E(e)}}(e.messageId),200===t.status?n("Message view logged"):n(`Problem logging message: ${t.status}`)}function Le(){}async function We(e){if(e.data.gist&&e.origin===x.RENDERER_HOST){var t=e.data.gist.instanceId,s=F(t);if(!s)return;var i=H(s);switch(e.data.gist.method){case"routeLoaded":var c=.001*((new Date).getTime()-s.renderStartTime);n(`Engine render for message: ${s.messageId} timer elapsed in ${c.toFixed(3)} seconds`),async function(e){const t=await xe(e);if(!t)return!1;r(t)}(s.queueId),s.currentRoute=e.data.gist.parameters.route,e.data.gist.parameters.fullDisplaySettings&&!s.displaySettings?s.displaySettings=e.data.gist.parameters.fullDisplaySettings:s.displaySettings&&(n("SDK already has display settings state, sending it to iframe"),ne(s)),(s.firstLoad||s.isDisplayChange)&&(s.overlay?function(e){var t=H(e),s=document.querySelector("#gist-overlay");if(s){s.classList.add("gist-visible");var n=document.querySelector(".gist-message");e.position?n.classList.add("gist-"+e.position):n.classList.add("gist-center"),setTimeout(re,100),t.exitClick&&setTimeout(()=>function(e){var t=document.querySelector("#gist-overlay");t&&t.addEventListener("click",function(){Ke.dismissMessage(e)})}(e.instanceId),1e3)}else ae()}(s):(h=ce(s.elementId))&&h.classList.add("gist-visible"),s.firstLoad&&!s.isDisplayChange&&(Ke.messageShown(s),i.persistent?n("Persistent message shown, skipping logging view"):await Ne(s)),s.firstLoad=!1,s.isDisplayChange=!1),X(t,s);break;case"tap":var u=e.data.gist.parameters.action,l=e.data.gist.parameters.name;if(Ke.messageAction(s,u,l),e.data.gist.parameters.system&&!i.persistent){await ke(s);break}try{var d=new URL(u);if(d&&"gist:"===d.protocol)switch(d.href.replace("gist://","").split("?")[0]){case"close":await ke(s),await Me(s),await Oe(s),await Be();break;case"showMessage":var g=d.searchParams.get("messageId"),m=d.searchParams.get("properties");g&&(m&&(m=JSON.parse(atob(m))),await Ke.showMessage({messageId:g,properties:m}));break;case"loadPage":(d=d.href.substring(d.href.indexOf("?url=")+5))&&(d.startsWith("mailto:")||d.startsWith("https://")||d.startsWith("http://")||d.startsWith("/")?window.location.href=d:window.location.href=window.location+d)}}catch{}break;case"changeMessageStep":var p=e.data.gist.parameters.displaySettings,f=e.data.gist.parameters.messageStepName;(i.persistent||fe(s))&&await async function(e,t,s){const i=await $e(e);if(!i)return;const r=o(i)||{},c={stepName:void 0!==t?t:r.stepName,displaySettings:void 0!==s?s:r.displaySettings},u=new Date;u.setDate(u.getDate()+30),a(i,c,u),n(`Saved message state for queueId: ${e}`)}(s.queueId,f,p),p&&function(e,t){const s=(n=e).overlay?"modal":n.elementId&&z.includes(n.elementId)?"overlay":n.elementId?"inline":"modal";var n;const i=t.displayType;if(void 0===i)return!1;if(s!==i)return!0;const a=H(e);switch(i){case"modal":if((e.position||"center")!==(t.modalPosition||"center"))return!0;if(void 0!==t.dismissOutsideClick&&a.exitClick!==t.dismissOutsideClick)return!0;if(void 0!==t.overlayColor&&a.overlayColor!==t.overlayColor)return!0;break;case"overlay":{const s=K(t.overlayPosition);if(e.elementId!==s)return!0;break}case"inline":if(e.elementId!==t.elementSelector)return!0}return void 0!==t.maxWidth&&a.messageWidth!==t.maxWidth}(s,p)&&(n("Display settings changed, reloading message"),await async function(e){e.overlay?await ie():Z(e.elementId)}(s),Y(s,p),await async function(e,t){e.isDisplayChange=!0,e.renderStartTime=(new Date).getTime();var s=e.elementId||null;if(s){const t=J(s);t&&t.instanceId!==e.instanceId&&(n(`Dismissing existing message at ${s} to make room for multi-step message`),await ke(t))}if(e.overlay){Ke.overlayInstanceId=e.instanceId;var i=H(e);e.shouldScale=i.shouldScale,e.shouldResizeHeight=!0}else Ke.overlayInstanceId=null,e.shouldScale=!1,e.shouldResizeHeight=!ee(s);s&&z.includes(s)&&G(s),Pe(e,s,t)}(s,f));break;case"routeChanged":s.currentRoute=e.data.gist.parameters.route,s.renderStartTime=(new Date).getTime(),X(t,s),n(`Route changed to: ${s.currentRoute}`);break;case"sizeChanged":n(`Size Changed Width: ${e.data.gist.parameters.width} - Height: ${e.data.gist.parameters.height}`),s.elementId&&!s.shouldResizeHeight||function(e,t){var s=ce(e.elementId?e.elementId:oe(e.instanceId));if(s){var n=s.style;if(t.height>0)if(t.height>window.innerHeight){var i=1-(t.height/window.innerHeight-1);e.shouldScale&&i>=.4?(n.height=`${t.height}px`,n.transform=`translateX(-50%) translateY(-50%) scale(${i})`):n.height=`${window.innerHeight}px`}else n.height=`${t.height}px`}}(s,e.data.gist.parameters);break;case"titleChanged":n(`Overlay title changed to: ${e.data.gist.parameters.title}`),function(e,t){var s=ce(oe(e));s&&(s.title=t)}(t,e.data.gist.parameters.title);break;case"eventDispatched":Ke.events.dispatch("eventDispatched",{name:e.data.gist.parameters.name,payload:e.data.gist.parameters.payload});break;case"error":case"routeError":Ke.messageError(s),Ke.overlayInstanceId?Re(!1,s):qe(s)}}var h}async function Ae(e){n(`Logging user message view locally for: ${e.queueId}`),pe(e)?await async function(e){n(`Marking broadcast ${e} as seen.`);const t=await he();if(!t)return;const s=await me(t,e);if(!s)return;const{broadcast:i}=s.properties.gist,r=ye(t,e),c=we(t,e);let u=o(r)||0;if(a(r,u+1),1===i.frequency.count)a(c,!1),n(`Marked broadcast ${e} as seen.`);else{let t=new Date;t.setSeconds(t.getSeconds()+i.frequency.delay),a(c,!1,t),n(`Marked broadcast ${e} as seen, broadcast was seen ${u+1} times, next show date is ${t}.`)}}(e.queueId):await async function(e){const t=await Ie();if(!t)return;const s=o(t)??[];s.push(e),a(t,s)}(e.queueId)}async function Oe(e){pe(e)&&(n(`Logging broadcast dismissed locally for: ${e.queueId}`),await async function(e){n(`Marking broadcast ${e} as dismissed.`);const t=await he();if(!t)return;const s=await me(t,e);if(!s)return;const{broadcast:i}=s.properties.gist;!0!==i.frequency.ignoreDismiss?(a(we(t,e),!1),n(`Marked broadcast ${e} as dismissed and will not show again.`)):n(`Broadcast ${e} is set to ignore dismiss.`)}(e.queueId),await Ee(e.queueId))}const Ue="messageInboxUpdated";async function _e(e){const t=await He();if(!t)return;const s=new Date;s.setMinutes(s.getMinutes()+60),a(t,e,s),Ke.events.dispatch(Ue,e)}async function je(){const e=await He();if(!e)return[];const t=o(e)??[],s=new Date;return t.filter(e=>!e.expiry||new Date(e.expiry)>s)}async function He(){const e=await U();return e?`gist.web.inbox.messages.${e}`:null}var ze=(e,t)=>e().then((e=>new Promise(t=>setTimeout(t,e)))(t).then(()=>ze(e,t))),Ge=!1;let Ve=null;async function Fe(){Ge?await Be():A()?(n("Queue watcher started"),Ge=!0,ze(()=>new Promise(()=>async function(){if(x.hasActiveSSEConnection())return!x.isSSEConnectionManagedBySDK()&&Ve&&(n("Not the main instance, closing our SSE connection."),Xe()),void await Be();Ve&&(n("SSE connection not active, closing it."),Xe()),!x.useSSE()||W()?await Qe():await async function(){Xe();const e=function(){const e=_();return null===e?(n("No user token available for SSE endpoint."),null):x.GIST_QUEUE_REALTIME_API_ENDPOINT[Ke.config.env??"prod"]+`/api/v3/sse?userToken=${e}&siteId=${Ke.config.siteId}&sessionId=${R()}`}();if(null===e)return n("SSE endpoint not available, falling back to polling."),void await Qe();n(`Starting SSE queue listener on ${e}`),Ve=new EventSource(e),x.setActiveSSEConnection(),Ve.addEventListener("connected",async e=>{try{n("SSE connection received:"),x.setUseSSEFlag(!0);var t=JSON.parse(e.data);t.heartbeat&&(x.setSSEHeartbeat(t.heartbeat),n(`SSE heartbeat set to ${t.heartbeat} seconds`)),x.setActiveSSEConnection()}catch(e){n(`Failed to parse SSE settings: ${e}`)}r(M),await Qe()}),Ve.addEventListener("messages",async e=>{try{var t=JSON.parse(e.data);n("SSE message received:"),await be(t),await ge(t),await Be()}catch(e){n("Failed to parse SSE message"),Xe()}}),Ve.addEventListener("inbox_messages",async e=>{try{var t=JSON.parse(e.data);n("SSE inbox messages received:"),await _e(t)}catch(e){n("Failed to parse SSE inbox messages")}}),Ve.addEventListener("error",async e=>{n("SSE error received:"),Xe()}),Ve.addEventListener("heartbeat",async e=>{n("SSE heartbeat received:"),x.setActiveSSEConnection(),x.setUseSSEFlag(!0)})}()}()),1e3)):n("User token not setup, queue not started.")}async function Be(){var e=await async function(){const e=await he();return e?(o(e)??[]).filter(t=>{const{broadcast:s}=t.properties.gist,n=o(we(e,t.queueId))??!0,i=o(ye(e,t.queueId))||0,a=0===s.frequency.count;return n&&(a||i<s.frequency.count)}):[]}(),t=await async function(){const e=await Se();if(!e)return[];const t=o(e)??[],s=await async function(){const e=await Ie();return e?o(e)??[]:[]}();return t.filter(e=>!s.includes(e.queueId))}(),s=e.concat(t);n(`Messages in local queue: ${s.length}`);var i=s.sort((e,t)=>e.priority-t.priority);for(const e of i)await Je(e)}async function Je(e){var t=H(e);if(t.hasRouteRule){var s=Ke.currentRoute;null==s&&(s=new URL(window.location.href).pathname);var i=t.routeRule;if(n(`Verifying route ${s} against rule: ${i}`),!new RegExp(i).test(s))return n(`Route ${s} does not match rule.`),!1}if(t.hasPosition&&(e.position=t.position),t.persistent||fe(e)){const s=await async function(e){const t=await $e(e);return t?o(t):null}(e.queueId);s&&(n(`Restoring saved state for queueId ${e.queueId}`),s.displaySettings&&(Y(e,s.displaySettings),t=H(e)),e.savedStepName=s.stepName)}if(t.persistent||fe(e)||!await async function(e){const t=await xe(e);return!!t&&null!==o(t)}(e.queueId)){var r;return(r=t.isEmbedded?De(e,t.elementId):await Ce(e))&&async function(e){const t=await xe(e);if(!t)return!1;a(t,!0,new Date(Date.now()+5e3))}(e.queueId),r}return n(`Not showing message with queueId ${e.queueId} because its already loading.`),!1}async function Qe(){if(A())if(Ke.isDocumentVisible)if(null===o(M)){var e=await async function(){const e=A();let t;try{if(!T){T=!0;const e={"X-Gist-User-Anonymous":String(W()),"Content-Language":String(null!==o(D)?o(D):navigator.language)};t=await C().post(`/api/v4/users?sessionId=${R()}`,{},{headers:e})}}catch(e){const s=E(e);s?t=s:n(`Error getting user queue: ${e}`)}finally{T=!1}return e!==A()?(n("User token changed, clearing queue next pull check."),void r(M)):(function(e){if(e?.headers){const t=e.headers["x-gist-queue-polling-interval"];t&&Number(t)>0&&(k=Number(t))}const t=new Date((new Date).getTime()+1e3*k);a(M,k,t)}(t),function(e){const t="true"===e?.headers?.["x-cio-use-sse"]?.toLowerCase();x.setUseSSEFlag(t)}(t),t)}();if(e){if(200===e.status||204===e.status){n("200 response, updating local store.");var t=e.data?.inAppMessages||[],s=e.data?.inboxMessages||[];be(t),ge(t),_e(s)}else 304===e.status&&n("304 response, using local store.");await Be()}else n("No response object returned while checking message queue.")}else n("Next queue pull scheduled for later.");else n("Document not visible, skipping queue check.");else n("User token reset, skipping queue check.")}function Xe(e=!1){e&&x.removeActiveSSEConnection(),(e||x.isSSEConnectionManagedBySDK())&&x.setUseSSEFlag(!1),Ve&&(n("Stopping SSE queue listener..."),Ve.close(),Ve=null)}const Ke=class{static events;static config;static initialized;static currentMessages;static overlayInstanceId;static currentRoute;static isDocumentVisible;static async setup(e){this.initialized?n("Gist SDK already initialized, skipping setup."):(this.initialized=!0,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(i,String(!1)),Ke.setUserToken(e),n(`Preview mode enabled with user token: ${e}`)),!c()}(),function(){const e=u();for(let t=e.length-1;t>=0;t--)l(e.key(t))}(),n(`Setup complete on ${this.config.env} environment.`),this.config.isPreviewSession||!this.config.useAnonymousSession||new URLSearchParams(location.search).has("ajs_uid")||O(),await Fe(),document.addEventListener("visibilitychange",async()=>{"hidden"===document.visibilityState?this.isDocumentVisible=!1:(this.isDocumentVisible=!0,await Be())},!1))}static async setCurrentRoute(e){this.currentRoute=e,n(`Current route set to: ${e}`),await async function(){if(0!==Ke.currentMessages.length)for(const e of[...Ke.currentMessages])null==document.querySelector(`#gist-${e.instanceId}`)&&(n(`Removing active message ${e.instanceId} that no longer exists after route change`),await Te(e))}(),await Be()}static async setUserToken(e,t){this.config.isPreviewSession||(function(e,t){void 0===t&&(t=new Date).setDate(t.getDate()+30),a(P,e,t),W()&&(r(M),r(N)),n(`Set user token "${e}" with expiry date set to ${t}`)}(e,t),Xe(!0),await Fe())}static setUserLocale(e){var t;a(D,t=e),n(`Set user locate to "${t}"`)}static setCustomAttribute(e,t){return function(e,t){return e&&"string"==typeof e?(le.set(e,t),de(),n(`Set custom attribute "${e}" to "${t}"`),!0):(n(`Invalid key for custom attribute: ${e}`),!1)}(e,t)}static clearCustomAttributes(){le.clear(),r(ue),n("Cleared all custom attributes")}static removeCustomAttribute(e){return function(e){if(!e||"string"!=typeof e)return n(`Invalid key for custom attribute: ${e}`),!1;const t=le.has(e);return le.delete(e),le.size>0?de():r(ue),n(`Removed custom attribute "${e}"`),t}(e)}static async clearUserToken(){this.config.isPreviewSession||(r(P),n("Cleared user token"),this.config.useAnonymousSession&&O(),Xe(!0),await Fe())}static async dismissMessage(e){var t=F(e);await ke(t),await Me(t),await Oe(t),await Be()}static async embedMessage(e,t){var s=De(e,t);return s?s.instanceId:null}static async showMessage(e){var t=await Ce(e);return t?t.instanceId:null}static updateMessageDisplaySettings(e,t){var s=F(e);return!!s&&(s.displaySettings=t,ne(s),!0)}static messageShown(e){n(`Message shown: ${e.messageId}`),this.events.dispatch("messageShown",e)}static messageDismissed(e){null!==e&&(n(`Message dismissed: ${e.messageId}`),this.events.dispatch("messageDismissed",e))}static messageError(e){n(`Message error: ${e.messageId}`),this.events.dispatch("messageError",e)}static messageAction(e,t,s){n(`Message action: ${e.currentRoute}, ${t} with name ${s} on ${e.instanceId}`),this.events.dispatch("messageAction",{message:e,action:t,name:s})}static async getInboxUnopenedCount(){return(await je()).filter(e=>!e.opened).length}static async getInboxMessages(){return await je()}static async updateInboxMessageOpenState(e,t){return await async function(e,t){const s=await He();if(!s)return;const i=await async function(e,t){try{return await C()(`/api/v1/messages/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})}catch(e){return E(e)}}(e,{opened:t});if(!i||i.status<200||i.status>=300){const e=`Failed to mark inbox message opened: ${i?.status||"unknown error"}`;throw n(e),new Error(e)}const o=await je();let r=null;const c=o.map(s=>s.queueId===e?(s.opened=t,r=s,{...s}):s),u=new Date;if(u.setMinutes(u.getMinutes()+60),a(s,c,u),r){const e=t?"opened":"unopened";Ke.events.dispatch("inboxMessageAction",{message:r,action:e})}Ke.events.dispatch(Ue,await je())}(e,t)}static async removeInboxMessage(e){return await async function(e){const t=await He();if(!t)return;const s=await j(e);if(!s||s.status<200||s.status>=300){const e=`Failed to remove inbox message: ${s?.status||"unknown error"}`;throw n(e),new Error(e)}const i=(await je()).filter(t=>t.queueId!==e),o=new Date;o.setMinutes(o.getMinutes()+60),a(t,i,o),Ke.events.dispatch(Ue,await je())}(e)}};return t.default})());
|
|
1
|
+
!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,()=>(()=>{"use strict";var e={d:(t,s)=>{for(var n in s)e.o(s,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:s[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{default:()=>Ye});class s{constructor(){this.callbacks={}}on(e,t){const s=this.callbacks[e];s?s.push(t):this.callbacks[e]=[t]}off(e,t){const s=this.callbacks[e];if(!s)return;if(!t)return void delete this.callbacks[e];const n=s.indexOf(t);-1!==n&&s.splice(n,1),0===s.length&&delete this.callbacks[e]}dispatch(e,t){const s=this.callbacks[e];s&&s.forEach(e=>e(t))}}function n(e){Ye.config&&Ye.config.logging&&console.log(`Gist: ${e}`)}const i="gist.web.isPersistingSession";function a(e,t,s=null){let n=s;n||(n=new Date,n.setDate(n.getDate()+365));const i={value:t,expiry:n};u().setItem(e,JSON.stringify(i))}function o(e){return l(e)}function r(e){u().removeItem(e)}function c(){const e=sessionStorage.getItem(i);return null===e?(sessionStorage.setItem(i,"true"),!0):"true"===e}function u(){return c()?localStorage:sessionStorage}function l(e){if(!e)return null;try{const t=u().getItem(e);if(!t)return null;const s=JSON.parse(t);if(!s.expiry)return s.value;const n=new Date,i=new Date(s.expiry),a=e.startsWith("gist.web.message.broadcasts")&&!e.endsWith("shouldShow")&&!e.endsWith("numberOfTimesShown")||e.startsWith("gist.web.message.user")&&!e.endsWith("seen")&&!e.endsWith("state"),o=new Date(n.getTime()+366e4);return a&&i.getTime()>o.getTime()||n.getTime()>i.getTime()?(r(e),null):s.value}catch(t){n(`Error checking key ${e} for expiry: ${t}`)}return null}var d,g=new Uint8Array(16);function m(){if(!d&&!(d="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 d(g)}const p=/^(?:[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 f=[],h=0;h<256;++h)f.push((h+256).toString(16).substr(1));const y=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,s=(f[e[t+0]]+f[e[t+1]]+f[e[t+2]]+f[e[t+3]]+"-"+f[e[t+4]]+f[e[t+5]]+"-"+f[e[t+6]]+f[e[t+7]]+"-"+f[e[t+8]]+f[e[t+9]]+"-"+f[e[t+10]]+f[e[t+11]]+f[e[t+12]]+f[e[t+13]]+f[e[t+14]]+f[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&p.test(e)}(s))throw TypeError("Stringified UUID is invalid");return s},w=function(e,t,s){var n=(e=e||{}).random||(e.rng||m)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){s=s||0;for(var i=0;i<16;++i)t[s+i]=n[i];return t}return y(n)},b="gist.web.userQueueUseSSE",v="gist.web.activeSSEConnection";let S,I=30;const x={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:()=>(S||(S=w()),S),useSSE:()=>o(b)??!1,setUseSSEFlag(e){a(b,e,new Date((new Date).getTime()+6e4)),n(`Set user uses SSE to "${e}"`)},removeActiveSSEConnection(){r(v)},setActiveSSEConnection(){a(v,x.getSdkId(),new Date((new Date).getTime()+x.getSSEHeartbeat()))},hasActiveSSEConnection:()=>o(v)??!1,isSSEConnectionManagedBySDK:()=>o(v)===x.getSdkId(),getSSEHeartbeat:()=>1e3*(I+5),setSSEHeartbeat(e){e&&e>0&&(I=e)}};function $(e){return null!==e&&"object"==typeof e&&"response"in e}function E(e){return $(e)?e.response:void 0}function C(){const e=x.GIST_QUEUE_API_ENDPOINT[Ye.config.env??"prod"],t={"X-CIO-Site-Id":Ye.config.siteId,"X-CIO-Client-Platform":"web"},s=j();async function n(s,n={}){const i=e+s,a=new AbortController,o=setTimeout(()=>a.abort(),5e3);try{const e=await fetch(i,{method:n.method||"GET",headers:{...t,...n.headers||{}},body:n.method&&"GET"!==n.method.toUpperCase()?n.body:void 0,signal:a.signal});clearTimeout(o);const s=e.headers.get("content-type")?.includes("application/json"),r=s?await e.json():await e.text(),c=Object.fromEntries(e.headers.entries());if(e.status<200||e.status>=400)throw function(e){return Object.assign(new Error,{response:e})}({status:e.status,data:r,headers:c});return{status:e.status,headers:c,data:r}}catch(e){if(clearTimeout(o),$(e))throw e;if(e instanceof Error)throw Object.assign(e,{response:{status:0,data:e.message||"Unknown error",headers:{}}});throw e}}return null!=s&&(t["X-Gist-Encoded-User-Token"]=s),n.post=(e,t={},s={})=>n(e,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",...s.headers||{}}}),n}const k="gist.web.userLocale";function D(){const e=o(k);return null!==e?e:navigator.language}let T=600,M=!1;const q="gist.web.userQueueNextPullCheck",R="gist.web.sessionId";function P(){let e=o(R);return e||(e=w()),a(R,e,new Date((new Date).getTime()+18e5)),String(e)}const L="gist.web.userToken",N="gist.web.usingGuestUserToken",W="gist.web.guestUserToken";function A(){return null!==o(N)}function O(){return o(L)}function U(){if(null===O()){let e=o(W);null==e&&(e=w(),a(W,e),n(`Set guest user token "${e}" with expiry date set to 1 year from today`)),a(L,e),a(N,!0),n(`Using anonymous session with token: "${e}"`)}}async function _(){const e=O();return null===e?null:await async function(e){const t=(new TextEncoder).encode(e),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(e=>e.toString(16).padStart(2,"0")).join("")}(e)}function j(){const e=O();return null===e?null:btoa(e)}async function H(e){try{return await C().post(`/api/v1/logs/queue/${e}`)}catch(e){return E(e)}}function z(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},s=e?.properties?.gist;return s?{isEmbedded:!!s.elementId,elementId:s.elementId||"",hasRouteRule:!!s.routeRuleWeb,routeRule:s.routeRuleWeb||"",position:s.position||"",hasPosition:!!s.position,shouldScale:!!s.scale,campaignId:s.campaignId??null,messageWidth:null!=s.messageWidth&&s.messageWidth>0?s.messageWidth:t.messageWidth,hasCustomWidth:(s.messageWidth??0)>0,overlayColor:s.overlayColor||t.overlayColor,persistent:!!s.persistent,exitClick:!!s.exitClick}:t}const G=["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 V(e){if(document.getElementById(e))return;const t=document.createElement("div");t.id=e,"x-gist-top"===e?document.body.insertBefore(t,document.body.firstChild):document.body.insertAdjacentElement("beforeend",t),n("Top & bottom elements injected into page")}const F=["x-gist-top","x-gist-bottom","x-gist-floating-top","x-gist-floating-bottom"];function B(e){return Ye.currentMessages.find(t=>t.instanceId===e)}function J(e){return!!e&&Ye.currentMessages.some(t=>t.queueId===e)}function Q(e){return e?Ye.currentMessages.find(t=>t.elementId===e)??null:null}function X(e){Ye.currentMessages=Ye.currentMessages.filter(t=>t.instanceId!==e)}function K(e,t){X(e),Ye.currentMessages.push(t)}function Y(e){const t={topLeft:"x-gist-floating-top-left",topCenter:"x-gist-floating-top",topRight:"x-gist-floating-top-right",bottomLeft:"x-gist-floating-bottom-left",bottomCenter:"x-gist-floating-bottom",bottomRight:"x-gist-floating-bottom-right"};return e&&t[e]?t[e]:(n(`Invalid overlay position "${e}", defaulting to "topCenter"`),t.topCenter)}function Z(e,t){if(e.properties||(e.properties={}),e.properties.gist||(e.properties.gist={}),"modal"===t.displayType)e.overlay=!0,e.elementId=null,e.properties.gist.elementId=null,e.position=t.modalPosition||"center",e.properties.gist.position=t.modalPosition||"center";else if("overlay"===t.displayType){e.overlay=!1;const s=Y(t.overlayPosition);e.elementId=s,e.properties.gist.elementId=s,e.position=null,e.properties.gist.position=null}else"inline"===t.displayType&&(e.overlay=!1,e.elementId=t.elementSelector,e.properties.gist.elementId=t.elementSelector,e.position=null,e.properties.gist.position=null);e.elementId&&F.includes(e.elementId)?delete e.properties.gist.messageWidth:void 0!==t.maxWidth&&t.maxWidth>0?e.properties.gist.messageWidth=t.maxWidth:delete e.properties.gist.messageWidth,void 0!==t.overlayColor?e.properties.gist.overlayColor=t.overlayColor:delete e.properties.gist.overlayColor,void 0!==t.dismissOutsideClick?e.properties.gist.exitClick=t.dismissOutsideClick:delete e.properties.gist.exitClick}function ee(e){const t=ue(e);t&&(t.classList.remove("gist-visible"),Array.from(t.classList).filter(e=>e.startsWith("gist-")).forEach(e=>t.classList.remove(e)),t.style.removeProperty("height"),t.style.removeProperty("width"),t.innerHTML="")}function te(e){const t=ue(e);if(t)return!(!t.style||!t.style.height||"0px"===t.style.height)}function se(e,t,s=null){const n=document.getElementById(e);n&&(n.onload=()=>{!function(e,t,s=null){const n=document.getElementById(e);if(n?.contentWindow){const e={options:t,capabilities:ne};s&&(t.stepId=s),n.contentWindow.postMessage(e,"*")}}(e,t,s)})}const ne=["MultiStepDisplayTypes"];function ie(e){if(!e.displaySettings)return;const t=re(e.instanceId??""),s=document.getElementById(t);s?.contentWindow&&s.contentWindow.postMessage({action:"updateDisplaySettings",displaySettings:e.displaySettings},"*")}async function ae(){const e=document.querySelector(".gist-message");e&&(e.classList.remove("gist-visible"),await new Promise(e=>setTimeout(e,300))),oe()}function oe(){const e=document.querySelector("#gist-embed-message");e&&e.parentNode?.removeChild(e)}function re(e){return`gist-${e}`}function ce(){const e=document.querySelector(".gist-message");e&&e.classList.add("gist-visible")}function ue(e){try{const t=document.querySelector(`#${e}`);return t instanceof HTMLElement?t:null}catch{return null}}const le="gist.web.customAttributes";let de=new Map;function ge(){const e=Array.from(de.entries()),t=new Date;t.setDate(t.getDate()+30),a(le,e,t),n(`Saved ${de.size} custom attributes to storage with TTL of 30 days`)}async function me(e){const t=await ye();if(!t)return;const s=new Date;s.setMinutes(s.getMinutes()+60),a(t,e.filter(fe),s)}async function pe(e,t){const s=o(e);return s?.find(e=>e.queueId===t)}function fe(e){return!(!e.properties?.gist||!e.properties.gist.broadcast)}function he(e){if(!fe(e))return!1;const t=e.properties.gist.broadcast;return 0===t.frequency.delay&&0===t.frequency.count}async function ye(){const e=await _();return e?`gist.web.message.broadcasts.${e}`:null}function we(e,t){return`${e}.${t}.numberOfTimesShown`}function be(e,t){return`${e}.${t}.shouldShow`}!function(){const e=o(le);if(e)try{de=new Map(e)}catch{de=new Map}else de=new Map}();const ve="gist.web.message.user";async function Se(e){const t=await Ie();if(!t)return;const s=e.filter(e=>!(e.properties&&e.properties.gist&&e.properties.gist.broadcast)),n=new Date;n.setMinutes(n.getMinutes()+60),a(t,s,n)}async function Ie(){const e=await _();return e?`${ve}.${e}`:null}async function xe(){const e=await _();return e?`${ve}.${e}.seen`:null}async function $e(e){const t=await _();return t?`${ve}.${t}.message.${e}.loading`:null}async function Ee(e){const t=await _();return t?`${ve}.${t}.message.${e}.state`:null}async function Ce(e){const t=await Ee(e);t&&(r(t),n(`Cleared message state for queueId: ${e}`))}async function ke(e){if(Ye.isDocumentVisible){if(J(e.queueId))return n(`Message with queueId ${e.queueId} is already showing.`),null;if(Ye.overlayInstanceId)return n(`Message ${Ye.overlayInstanceId} already showing.`),null;{const t=z(e);return e.instanceId=w(),e.overlay=!0,e.firstLoad=!0,e.shouldResizeHeight=!0,e.shouldScale=t.shouldScale,e.renderStartTime=(new Date).getTime(),Ye.overlayInstanceId=e.instanceId,Ye.currentMessages.push(e),Le(e,null,e.savedStepName||null)}}return n("Document hidden, not showing message now."),null}function De(e,t){return Ye.isDocumentVisible?J(e.queueId)?(n(`Message with queueId ${e.queueId} is already showing.`),null):Q(t)?(n(`Message with elementId ${t} already has a message.`),null):(e.instanceId=w(),e.overlay=!1,e.firstLoad=!0,e.shouldScale=!1,e.elementId=t,e.shouldResizeHeight=!te(t),e.renderStartTime=(new Date).getTime(),Ye.currentMessages.push(e),Le(e,t,e.savedStepName||null)):(n("Document hidden, not showing message now."),null)}async function Te(e){e?(Ye.messageDismissed(e),await Me(e)):n("Message not found")}async function Me(e){e.overlay?await Pe(!0,e):Re(e)}async function qe(e){e?z(e).persistent&&(n("Persistent message dismissed, logging view"),await Oe(e),await Ne(e),await Ce(e.queueId??"")):n("Message not found")}function Re(e){e.instanceId&&X(e.instanceId),e.elementId&&ee(e.elementId)}async function Pe(e,t){e?await ae():oe(),0===Ye.currentMessages.length&&(window.removeEventListener("message",Ae),window.removeEventListener("touchstart",We)),t.instanceId&&X(t.instanceId),Ye.overlayInstanceId=null}function Le(e,t=null,s=null){const i=Ye.config.env,a={endpoint:x.ENGINE_API_ENDPOINT[i],siteId:Ye.config.siteId,dataCenter:Ye.config.dataCenter,messageId:e.messageId,instanceId:e.instanceId??"",livePreview:!1,properties:e.properties,customAttributes:Object.fromEntries(new Map(de))},o=`${x.GIST_VIEW_ENDPOINT[i]}/index.html`;return window.addEventListener("message",Ae),window.addEventListener("touchstart",We),t?(G.includes(t)&&V(t),function(e,t,s,i,a=null){const o=ue(e);if(o){const n=re(s.instanceId??"");o.classList.add(n);const r=z(s);let c=r.messageWidth+"px";F.includes(e)&&!r.hasCustomWidth&&(c="100%"),G.includes(e)&&(o.style.width=c),te(e)||(o.style.height="0px"),o.innerHTML=function(e,t,s){return function(e,t,s){let n=800;return t.messageWidth>n&&(n=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: ${n}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="${s}"></iframe>\n </div>\n </div>`}(re(t.instanceId??""),s,e)}(t,s,r),se(n,i,a)}else n(`Message could not be embedded, elementId ${e} not found.`)}(t,o,e,a,s)):function(e,t,s,n=null){document.querySelectorAll("#gist-embed-message").forEach(e=>{e.parentNode?.removeChild(e)}),document.body.insertAdjacentHTML("afterbegin",function(e,t){const s=z(t);return function(e,t,s){let n=600;return t.messageWidth>n&&(n=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: ${n}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="${s}"></iframe>\n </div>\n </div>`}(re(t.instanceId??""),s,e)}(e,t)),se(re(t.instanceId??""),s,n)}(o,e,a,s),e}async function Ne(e){let t;n(`Message shown, logging view for: ${e.messageId}`),null!=e.queueId?(await Oe(e),t=await H(e.queueId)):t=await async function(e){try{return await C().post(`/api/v1/logs/message/${e}`)}catch(e){return E(e)}}(e.messageId),n(200===t?.status?"Message view logged":`Problem logging message: ${t?.status}`)}function We(){}async function Ae(e){const t=e.data;if(t.gist&&e.origin===x.RENDERER_HOST){const e=t.gist.instanceId,s=B(e);if(!s)return;const i=z(s);switch(t.gist.method){case"routeLoaded":{const a=.001*((new Date).getTime()-(s.renderStartTime??0));n(`Engine render for message: ${s.messageId} timer elapsed in ${a.toFixed(3)} seconds`),async function(e){const t=await $e(e);t&&r(t)}(s.queueId??""),s.currentRoute=t.gist.parameters.route,t.gist.parameters.fullDisplaySettings&&!s.displaySettings?s.displaySettings=t.gist.parameters.fullDisplaySettings:s.displaySettings&&(n("SDK already has display settings state, sending it to iframe"),ie(s)),(s.firstLoad||s.isDisplayChange)&&(s.overlay?function(e){const t=z(e),s=document.querySelector("#gist-overlay");if(s){s.classList.add("gist-visible");const n=document.querySelector(".gist-message");n&&(e.position?n.classList.add("gist-"+e.position):n.classList.add("gist-center")),setTimeout(ce,100),t.exitClick&&setTimeout(()=>function(e){const t=document.querySelector("#gist-overlay");t&&t.addEventListener("click",()=>{Ye.dismissMessage(e)})}(e.instanceId??""),1e3)}else oe()}(s):function(e){const t=ue(e);t&&t.classList.add("gist-visible")}(s.elementId),s.firstLoad&&!s.isDisplayChange&&(Ye.messageShown(s),i.persistent?n("Persistent message shown, skipping logging view"):await Ne(s)),s.firstLoad=!1,s.isDisplayChange=!1),K(e,s);break}case"tap":{const e=t.gist.parameters.action,n=t.gist.parameters.name;if(Ye.messageAction(s,e,n),t.gist.parameters.system&&!i.persistent){await Te(s);break}try{const t=new URL(e);if(t&&"gist:"===t.protocol)switch(t.href.replace("gist://","").split("?")[0]){case"close":await Te(s),await qe(s),await Ue(s),await Je();break;case"showMessage":{const e=t.searchParams.get("messageId");let s=t.searchParams.get("properties");e&&(s&&(s=JSON.parse(atob(s))),await Ye.showMessage({messageId:e,properties:s}));break}case"loadPage":{const e=t.href.substring(t.href.indexOf("?url=")+5);e&&(e.startsWith("mailto:")||e.startsWith("https://")||e.startsWith("http://")||e.startsWith("/")?window.location.href=e:window.location.href=window.location+e);break}}}catch{}break}case"changeMessageStep":{const e=t.gist.parameters.displaySettings,r=t.gist.parameters.messageStepName;(i.persistent||he(s))&&await async function(e,t,s){const i=await Ee(e);if(!i)return;const r=o(i)||{},c={stepName:void 0!==t?t:r.stepName,displaySettings:void 0!==s?s:r.displaySettings},u=new Date;u.setDate(u.getDate()+30),a(i,c,u),n(`Saved message state for queueId: ${e}`)}(s.queueId??"",r,e),e&&function(e,t){const s=(n=e).overlay?"modal":n.elementId&&G.includes(n.elementId)?"overlay":n.elementId?"inline":"modal";var n;const i=t.displayType;if(void 0===i)return!1;if(s!==i)return!0;const a=z(e);switch(i){case"modal":if((e.position||"center")!==(t.modalPosition||"center"))return!0;if(void 0!==t.dismissOutsideClick&&a.exitClick!==t.dismissOutsideClick)return!0;if(void 0!==t.overlayColor&&a.overlayColor!==t.overlayColor)return!0;break;case"overlay":{const s=Y(t.overlayPosition);if(e.elementId!==s)return!0;break}case"inline":if(e.elementId!==t.elementSelector)return!0}return void 0!==t.maxWidth&&a.messageWidth!==t.maxWidth}(s,e)&&(n("Display settings changed, reloading message"),await async function(e){e.overlay?await ae():e.elementId&&ee(e.elementId)}(s),Z(s,e),await async function(e,t){e.isDisplayChange=!0,e.renderStartTime=(new Date).getTime();const s=e.elementId||null;if(s){const t=Q(s);t&&t.instanceId!==e.instanceId&&(n(`Dismissing existing message at ${s} to make room for multi-step message`),await Te(t))}if(e.overlay){Ye.overlayInstanceId=e.instanceId??null;const t=z(e);e.shouldScale=t.shouldScale,e.shouldResizeHeight=!0}else Ye.overlayInstanceId=null,e.shouldScale=!1,e.shouldResizeHeight=!te(s??"");s&&G.includes(s)&&V(s),Le(e,s,t)}(s,r??null));break}case"routeChanged":s.currentRoute=t.gist.parameters.route,s.renderStartTime=(new Date).getTime(),K(e,s),n(`Route changed to: ${s.currentRoute}`);break;case"sizeChanged":n(`Size Changed Width: ${t.gist.parameters.width} - Height: ${t.gist.parameters.height}`),s.elementId&&!s.shouldResizeHeight||function(e,t){const s=ue(e.elementId?e.elementId:re(e.instanceId??""));if(s){const n=s.style;if(t.height>0)if(t.height>window.innerHeight){const s=1-(t.height/window.innerHeight-1);e.shouldScale&&s>=.4?(n.height=`${t.height}px`,n.transform=`translateX(-50%) translateY(-50%) scale(${s})`):n.height=`${window.innerHeight}px`}else n.height=`${t.height}px`}}(s,t.gist.parameters);break;case"titleChanged":n(`Overlay title changed to: ${t.gist.parameters.title}`),function(e,t){const s=ue(re(e));s&&(s.title=t)}(e,t.gist.parameters.title);break;case"eventDispatched":Ye.events.dispatch("eventDispatched",{name:t.gist.parameters.name,payload:t.gist.parameters.payload});break;case"error":case"routeError":Ye.messageError(s),Ye.overlayInstanceId?await Pe(!1,s):Re(s)}}}async function Oe(e){n(`Logging user message view locally for: ${e.queueId}`),fe(e)?await async function(e){n(`Marking broadcast ${e} as seen.`);const t=await ye();if(!t)return;const s=await pe(t,e);if(!s)return;const i=s.properties.gist.broadcast,{frequency:r}=i,c=we(t,e),u=be(t,e),l=o(c)||0;if(a(c,l+1),1===r.count)a(u,!1),n(`Marked broadcast ${e} as seen.`);else{const t=new Date;t.setSeconds(t.getSeconds()+r.delay),a(u,!1,t),n(`Marked broadcast ${e} as seen, broadcast was seen ${l+1} times, next show date is ${t}.`)}}(e.queueId??""):await async function(e){const t=await xe();if(!t)return;const s=o(t)??[];s.push(e),a(t,s)}(e.queueId??"")}async function Ue(e){fe(e)&&(n(`Logging broadcast dismissed locally for: ${e.queueId}`),await async function(e){n(`Marking broadcast ${e} as dismissed.`);const t=await ye();if(!t)return;const s=await pe(t,e);s&&(!0!==s.properties.gist.broadcast.frequency.ignoreDismiss?(a(be(t,e),!1),n(`Marked broadcast ${e} as dismissed and will not show again.`)):n(`Broadcast ${e} is set to ignore dismiss.`))}(e.queueId??""),await Ce(e.queueId??""))}const _e="messageInboxUpdated";async function je(e){const t=await ze();if(!t)return;const s=new Date;s.setMinutes(s.getMinutes()+60),a(t,e,s),Ye.events.dispatch(_e,e)}async function He(){const e=await ze();if(!e)return[];const t=o(e)??[],s=new Date;return t.filter(e=>!e.expiry||new Date(e.expiry)>s)}async function ze(){const e=await _();return e?`gist.web.inbox.messages.${e}`:null}const Ge=(e,t)=>e().then((e=>new Promise(t=>setTimeout(t,e)))(t).then(()=>Ge(e,t)));let Ve=!1,Fe=null;async function Be(){Ve?await Je():O()?(n("Queue watcher started"),Ve=!0,Ge(()=>new Promise(()=>{!async function(){if(x.hasActiveSSEConnection())return!x.isSSEConnectionManagedBySDK()&&Fe&&(n("Not the main instance, closing our SSE connection."),Ke()),void await Je();Fe&&(n("SSE connection not active, closing it."),Ke()),!x.useSSE()||A()?await Xe():await async function(){Ke();const e=function(){const e=j();return null===e?(n("No user token available for SSE endpoint."),null):x.GIST_QUEUE_REALTIME_API_ENDPOINT[Ye.config.env??"prod"]+`/api/v3/sse?userToken=${e}&siteId=${Ye.config.siteId}&sessionId=${P()}`}();if(null===e)return n("SSE endpoint not available, falling back to polling."),void await Xe();n(`Starting SSE queue listener on ${e}`),Fe=new EventSource(e),x.setActiveSSEConnection(),Fe.addEventListener("connected",async e=>{try{n("SSE connection received"),x.setUseSSEFlag(!0);const t=JSON.parse(e.data);t.heartbeat&&(x.setSSEHeartbeat(t.heartbeat),n(`SSE heartbeat set to ${t.heartbeat} seconds`)),x.setActiveSSEConnection()}catch(e){n(`Failed to parse SSE settings: ${e}`)}r(q),await Xe()}),Fe.addEventListener("messages",async e=>{try{const t=JSON.parse(e.data);n("SSE message received"),await Se(t),await me(t),await Je()}catch(e){n(`Failed to parse SSE message: ${e}`),Ke()}}),Fe.addEventListener("inbox_messages",async e=>{try{const t=JSON.parse(e.data);n("SSE inbox messages received"),await je(t)}catch(e){n(`Failed to parse SSE inbox messages: ${e}`)}}),Fe.addEventListener("error",async()=>{n("SSE error received"),Ke()}),Fe.addEventListener("heartbeat",async()=>{n("SSE heartbeat received"),x.setActiveSSEConnection(),x.setUseSSEFlag(!0)})}()}()}),1e3)):n("User token not setup, queue not started.")}async function Je(){const e=await async function(){const e=await ye();return e?(o(e)??[]).filter(t=>{const s=t.properties.gist.broadcast,{frequency:n}=s,i=o(be(e,t.queueId))??!0,a=o(we(e,t.queueId))||0,r=0===n.count;return i&&(r||a<n.count)}):[]}(),t=await async function(){const e=await Ie();if(!e)return[];const t=o(e)??[],s=await async function(){const e=await xe();return e?o(e)??[]:[]}();return t.filter(e=>!s.includes(e.queueId??""))}(),s=e.concat(t);n(`Messages in local queue: ${s.length}`);const i=s.sort((e,t)=>e.priority-t.priority);for(const e of i)await Qe(e)}async function Qe(e){let t=z(e);if(t.hasRouteRule){let e=Ye.currentRoute;null==e&&(e=new URL(window.location.href).pathname);const s=t.routeRule;if(n(`Verifying route ${e} against rule: ${s}`),!new RegExp(s).test(e))return n(`Route ${e} does not match rule.`),!1}if(t.hasPosition&&(e.position=t.position),t.persistent||he(e)){const s=await async function(e){const t=await Ee(e);return t?o(t):null}(e.queueId??"");s&&(n(`Restoring saved state for queueId ${e.queueId}`),s.displaySettings&&(Z(e,s.displaySettings),t=z(e)),e.savedStepName=s.stepName??null)}if(t.persistent||he(e)||!await async function(e){const t=await $e(e);return!!t&&null!==o(t)}(e.queueId??"")){let s=null;return s=t.isEmbedded?De(e,t.elementId):await ke(e),s&&async function(e){const t=await $e(e);t&&a(t,!0,new Date(Date.now()+5e3))}(e.queueId??""),null!==s}return n(`Not showing message with queueId ${e.queueId} because its already loading.`),!1}async function Xe(){if(O())if(Ye.isDocumentVisible)if(null===o(q)){const e=await async function(){const e=O();let t;try{if(!M){M=!0;const e={"X-Gist-User-Anonymous":String(A()),"Content-Language":String(D())};t=await C().post(`/api/v4/users?sessionId=${P()}`,{},{headers:e})}}catch(e){const s=E(e);s?t=s:n(`Error getting user queue: ${e}`)}finally{M=!1}return e!==O()?(n("User token changed, clearing queue next pull check."),void r(q)):(function(e){if(e?.headers){const t=e.headers["x-gist-queue-polling-interval"];t&&Number(t)>0&&(T=Number(t))}const t=new Date((new Date).getTime()+1e3*T);a(q,T,t)}(t),function(e){const t="true"===e?.headers?.["x-cio-use-sse"]?.toLowerCase();x.setUseSSEFlag(t)}(t),t)}();if(e){if(200===e.status||204===e.status){n("200 response, updating local store.");const t=e.data,s=t?.inAppMessages??[],i=t?.inboxMessages??[];Se(s),me(s),je(i)}else 304===e.status&&n("304 response, using local store.");await Je()}else n("No response object returned while checking message queue.")}else n("Next queue pull scheduled for later.");else n("Document not visible, skipping queue check.");else n("User token reset, skipping queue check.")}function Ke(e=!1){e&&x.removeActiveSSEConnection(),(e||x.isSSEConnectionManagedBySDK())&&x.setUseSSEFlag(!1),Fe&&(n("Stopping SSE queue listener..."),Fe.close(),Fe=null)}const Ye=class{static events;static config;static initialized;static currentMessages;static overlayInstanceId;static currentRoute;static isDocumentVisible;static async setup(e){this.initialized?n("Gist SDK already initialized, skipping setup."):(this.initialized=!0,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(i,String(!1)),Ye.setUserToken(e),n(`Preview mode enabled with user token: ${e}`)),!c()}(),function(){const e=u();for(let t=e.length-1;t>=0;t--)l(e.key(t))}(),n(`Setup complete on ${this.config.env} environment.`),this.config.isPreviewSession||!this.config.useAnonymousSession||new URLSearchParams(location.search).has("ajs_uid")||U(),await Be(),document.addEventListener("visibilitychange",async()=>{"hidden"===document.visibilityState?this.isDocumentVisible=!1:(this.isDocumentVisible=!0,await Je())},!1))}static async setCurrentRoute(e){this.currentRoute=e,n(`Current route set to: ${e}`),await async function(){if(0!==Ye.currentMessages.length)for(const e of[...Ye.currentMessages])null==document.querySelector(`#gist-${e.instanceId}`)&&(n(`Removing active message ${e.instanceId} that no longer exists after route change`),await Me(e))}(),await Je()}static async setUserToken(e,t){this.config.isPreviewSession||(function(e,t){void 0===t&&(t=new Date).setDate(t.getDate()+30),a(L,e,t),A()&&(r(q),r(N)),n(`Set user token "${e}" with expiry date set to ${t}`)}(e,t),Ke(!0),await Be())}static setUserLocale(e){var t;a(k,t=e),n(`Set user locate to "${t}"`)}static setCustomAttribute(e,t){return function(e,t){return e&&"string"==typeof e?(de.set(e,t),ge(),n(`Set custom attribute "${e}" to "${t}"`),!0):(n(`Invalid key for custom attribute: ${e}`),!1)}(e,t)}static clearCustomAttributes(){de.clear(),r(le),n("Cleared all custom attributes")}static removeCustomAttribute(e){return function(e){if(!e||"string"!=typeof e)return n(`Invalid key for custom attribute: ${e}`),!1;const t=de.has(e);return de.delete(e),de.size>0?ge():r(le),n(`Removed custom attribute "${e}"`),t}(e)}static async clearUserToken(){this.config.isPreviewSession||(r(L),n("Cleared user token"),this.config.useAnonymousSession&&U(),Ke(!0),await Be())}static async dismissMessage(e){var t=B(e);await Te(t),await qe(t),await Ue(t),await Je()}static async embedMessage(e,t){var s=De(e,t);return s?s.instanceId:null}static async showMessage(e){var t=await ke(e);return t?t.instanceId:null}static updateMessageDisplaySettings(e,t){var s=B(e);return!!s&&(s.displaySettings=t,ie(s),!0)}static messageShown(e){n(`Message shown: ${e.messageId}`),this.events.dispatch("messageShown",e)}static messageDismissed(e){null!==e&&(n(`Message dismissed: ${e.messageId}`),this.events.dispatch("messageDismissed",e))}static messageError(e){n(`Message error: ${e.messageId}`),this.events.dispatch("messageError",e)}static messageAction(e,t,s){n(`Message action: ${e.currentRoute}, ${t} with name ${s} on ${e.instanceId}`),this.events.dispatch("messageAction",{message:e,action:t,name:s})}static async getInboxUnopenedCount(){return(await He()).filter(e=>!e.opened).length}static async getInboxMessages(){return await He()}static async updateInboxMessageOpenState(e,t){return await async function(e,t){const s=await ze();if(!s)return;const i=await async function(e,t){try{return await C()(`/api/v1/messages/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})}catch(e){return E(e)}}(e,{opened:t});if(!i||i.status<200||i.status>=300){const e=`Failed to mark inbox message opened: ${i?.status??"unknown error"}`;throw n(e),new Error(e)}const o=await He();let r=null;const c=o.map(s=>{if(s.queueId===e){const e={...s,opened:t};return r=e,e}return s}),u=new Date;if(u.setMinutes(u.getMinutes()+60),a(s,c,u),r){const e=t?"opened":"unopened";Ye.events.dispatch("inboxMessageAction",{message:r,action:e})}Ye.events.dispatch(_e,await He())}(e,t)}static async removeInboxMessage(e){return await async function(e){const t=await ze();if(!t)return;const s=await H(e);if(!s||s.status<200||s.status>=300){const e=`Failed to remove inbox message: ${s?.status??"unknown error"}`;throw n(e),new Error(e)}const i=(await He()).filter(t=>t.queueId!==e),o=new Date;o.setMinutes(o.getMinutes()+60),a(t,i,o),Ye.events.dispatch(_e,await He())}(e)}};return t.default})());
|
package/dist/types/gist.d.ts
CHANGED
|
@@ -23,15 +23,15 @@ export default class _default {
|
|
|
23
23
|
static removeCustomAttribute(key: any): boolean;
|
|
24
24
|
static clearUserToken(): Promise<void>;
|
|
25
25
|
static dismissMessage(instanceId: any): Promise<void>;
|
|
26
|
-
static embedMessage(message: any, elementId: any): Promise<
|
|
27
|
-
static showMessage(message: any): Promise<
|
|
26
|
+
static embedMessage(message: any, elementId: any): Promise<string | null | undefined>;
|
|
27
|
+
static showMessage(message: any): Promise<string | null | undefined>;
|
|
28
28
|
static updateMessageDisplaySettings(instanceId: any, displaySettings: any): boolean;
|
|
29
29
|
static messageShown(message: any): void;
|
|
30
30
|
static messageDismissed(message: any): void;
|
|
31
31
|
static messageError(message: any): void;
|
|
32
32
|
static messageAction(message: any, action: any, name: any): void;
|
|
33
|
-
static getInboxUnopenedCount(): Promise<
|
|
34
|
-
static getInboxMessages(): Promise<
|
|
33
|
+
static getInboxUnopenedCount(): Promise<number>;
|
|
34
|
+
static getInboxMessages(): Promise<import("./managers/inbox-message-manager").InboxMessage[]>;
|
|
35
35
|
static updateInboxMessageOpenState(queueId: any, opened: any): Promise<void>;
|
|
36
36
|
static removeInboxMessage(queueId: any): Promise<void>;
|
|
37
37
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export function setCustomAttribute(key:
|
|
2
|
-
export function getCustomAttribute(key:
|
|
3
|
-
export function getAllCustomAttributes(): Map<
|
|
4
|
-
export function clearCustomAttributes(): void;
|
|
5
|
-
export function removeCustomAttribute(key:
|
|
1
|
+
export declare function setCustomAttribute(key: string, value: unknown): boolean;
|
|
2
|
+
export declare function getCustomAttribute(key: string): unknown | null;
|
|
3
|
+
export declare function getAllCustomAttributes(): Map<string, unknown>;
|
|
4
|
+
export declare function clearCustomAttributes(): void;
|
|
5
|
+
export declare function removeCustomAttribute(key: string): boolean;
|
|
@@ -1,15 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
elementId: any;
|
|
4
|
-
hasRouteRule: boolean;
|
|
5
|
-
routeRule: any;
|
|
6
|
-
position: any;
|
|
7
|
-
hasPosition: boolean;
|
|
8
|
-
shouldScale: boolean;
|
|
9
|
-
campaignId: any;
|
|
10
|
-
messageWidth: any;
|
|
11
|
-
hasCustomWidth: boolean;
|
|
12
|
-
overlayColor: any;
|
|
13
|
-
persistent: boolean;
|
|
14
|
-
exitClick: boolean;
|
|
15
|
-
};
|
|
1
|
+
import type { GistMessage, ResolvedMessageProperties } from "../types";
|
|
2
|
+
export declare function resolveMessageProperties(message: GistMessage): ResolvedMessageProperties;
|
|
@@ -1,5 +1,15 @@
|
|
|
1
|
-
|
|
2
|
-
export
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import type { MessageProperties } from "../types";
|
|
2
|
+
export interface InboxMessage {
|
|
3
|
+
messageId: string;
|
|
4
|
+
queueId?: string;
|
|
5
|
+
opened?: boolean;
|
|
6
|
+
expiry?: string;
|
|
7
|
+
topics?: string[];
|
|
8
|
+
properties?: MessageProperties;
|
|
9
|
+
[key: string]: unknown;
|
|
10
|
+
}
|
|
11
|
+
export declare function updateInboxMessagesLocalStore(messages: InboxMessage[]): Promise<void>;
|
|
12
|
+
export declare function getInboxMessagesFromLocalStore(): Promise<InboxMessage[]>;
|
|
13
|
+
export declare function getInboxMessagesByTopic(topic: string | null): Promise<InboxMessage[]>;
|
|
14
|
+
export declare function updateInboxMessageOpenState(queueId: string, opened: boolean): Promise<void>;
|
|
15
|
+
export declare function removeInboxMessage(queueId: string): Promise<void>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export function getUserLocale():
|
|
2
|
-
export function setUserLocale(locale:
|
|
1
|
+
export declare function getUserLocale(): string;
|
|
2
|
+
export declare function setUserLocale(locale: string): void;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
export function
|
|
3
|
-
export function
|
|
4
|
-
export function
|
|
5
|
-
export function
|
|
6
|
-
export function
|
|
1
|
+
import type { GistMessage } from "../types";
|
|
2
|
+
export declare function updateBroadcastsLocalStore(messages: GistMessage[]): Promise<void>;
|
|
3
|
+
export declare function getEligibleBroadcasts(): Promise<GistMessage[]>;
|
|
4
|
+
export declare function markBroadcastAsSeen(broadcastId: string): Promise<void>;
|
|
5
|
+
export declare function markBroadcastAsDismissed(broadcastId: string): Promise<void>;
|
|
6
|
+
export declare function isMessageBroadcast(message: GistMessage): boolean;
|
|
7
|
+
export declare function isShowAlwaysBroadcast(message: GistMessage): boolean;
|
|
@@ -1,12 +1,29 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
1
|
+
import type { GistMessage } from "../types";
|
|
2
|
+
interface MessageOptions {
|
|
3
|
+
endpoint: string;
|
|
4
|
+
siteId: string;
|
|
5
|
+
dataCenter: string;
|
|
6
|
+
messageId: string;
|
|
7
|
+
instanceId: string;
|
|
8
|
+
livePreview: boolean;
|
|
9
|
+
properties?: unknown;
|
|
10
|
+
customAttributes?: Record<string, unknown>;
|
|
11
|
+
stepId?: string;
|
|
12
|
+
[key: string]: unknown;
|
|
13
|
+
}
|
|
14
|
+
export declare function loadEmbedComponent(elementId: string, url: string, message: GistMessage, options: MessageOptions, stepName?: string | null): void;
|
|
15
|
+
export declare function showEmbedComponent(elementId: string): void;
|
|
16
|
+
export declare function hideEmbedComponent(elementId: string): void;
|
|
17
|
+
export declare function elementHasHeight(elementId: string): boolean | undefined;
|
|
18
|
+
export declare function resizeComponent(message: GistMessage, size: {
|
|
19
|
+
width: number;
|
|
20
|
+
height: number;
|
|
21
|
+
}): void;
|
|
22
|
+
export declare function loadOverlayComponent(url: string, message: GistMessage, options: MessageOptions, stepName?: string | null): void;
|
|
23
|
+
export declare function sendOptionsToIframe(iframeId: string, options: MessageOptions, stepName?: string | null): void;
|
|
24
|
+
export declare function sendDisplaySettingsToIframe(message: GistMessage): void;
|
|
25
|
+
export declare function showOverlayComponent(message: GistMessage): void;
|
|
26
|
+
export declare function hideOverlayComponent(): Promise<void>;
|
|
27
|
+
export declare function removeOverlayComponent(): void;
|
|
28
|
+
export declare function changeOverlayTitle(instanceId: string, title: string): void;
|
|
29
|
+
export {};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
export function
|
|
3
|
-
export function
|
|
4
|
-
export function
|
|
5
|
-
export function
|
|
6
|
-
export function
|
|
1
|
+
import type { GistMessage } from "../types";
|
|
2
|
+
export declare function showMessage(message: GistMessage): Promise<GistMessage | null>;
|
|
3
|
+
export declare function embedMessage(message: GistMessage, elementId: string): GistMessage | null;
|
|
4
|
+
export declare function hideMessage(message: GistMessage): Promise<void>;
|
|
5
|
+
export declare function resetMessage(message: GistMessage): Promise<void>;
|
|
6
|
+
export declare function removePersistentMessage(message: GistMessage): Promise<void>;
|
|
7
|
+
export declare function logBroadcastDismissedLocally(message: GistMessage): Promise<void>;
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
|
|
2
|
-
export function
|
|
3
|
-
export function
|
|
4
|
-
export function
|
|
5
|
-
export function
|
|
6
|
-
export function
|
|
7
|
-
export function
|
|
8
|
-
export function
|
|
9
|
-
export function
|
|
1
|
+
import type { GistMessage, DisplaySettings } from "../types";
|
|
2
|
+
export declare function updateQueueLocalStore(messages: GistMessage[]): Promise<void>;
|
|
3
|
+
export declare function getMessagesFromLocalStore(): Promise<GistMessage[]>;
|
|
4
|
+
export declare function markUserQueueMessageAsSeen(queueId: string): Promise<void>;
|
|
5
|
+
export declare function isMessageLoading(queueId: string): Promise<boolean>;
|
|
6
|
+
export declare function setMessageLoading(queueId: string): Promise<void>;
|
|
7
|
+
export declare function setMessageLoaded(queueId: string): Promise<void>;
|
|
8
|
+
export declare function saveMessageState(queueId: string, stepName: string | undefined, displaySettings: DisplaySettings | undefined): Promise<void>;
|
|
9
|
+
export declare function getSavedMessageState(queueId: string): Promise<unknown>;
|
|
10
|
+
export declare function clearMessageState(queueId: string): Promise<void>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
export
|
|
1
|
+
export declare const positions: readonly string[];
|
|
2
|
+
export declare function addPageElement(position: string): void;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export function startQueueListener(): Promise<void>;
|
|
2
|
-
export function checkMessageQueue(): Promise<void>;
|
|
3
|
-
export function checkCurrentMessagesAfterRouteChange(): Promise<void>;
|
|
4
|
-
export function pullMessagesFromQueue(): Promise<void>;
|
|
5
|
-
export function stopSSEListener(disconnectGlobally?: boolean): void;
|
|
1
|
+
export declare function startQueueListener(): Promise<void>;
|
|
2
|
+
export declare function checkMessageQueue(): Promise<void>;
|
|
3
|
+
export declare function checkCurrentMessagesAfterRouteChange(): Promise<void>;
|
|
4
|
+
export declare function pullMessagesFromQueue(): Promise<void>;
|
|
5
|
+
export declare function stopSSEListener(disconnectGlobally?: boolean): void;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export function isUsingGuestUserToken(): boolean;
|
|
2
|
-
export function getUserToken():
|
|
3
|
-
export function setUserToken(userToken:
|
|
4
|
-
export function useGuestSession(): void;
|
|
5
|
-
export function isAnonymousUser(): boolean;
|
|
6
|
-
export function getHashedUserToken(): Promise<string | null>;
|
|
7
|
-
export function getEncodedUserToken(): string | null;
|
|
8
|
-
export function clearUserToken(): void;
|
|
1
|
+
export declare function isUsingGuestUserToken(): boolean;
|
|
2
|
+
export declare function getUserToken(): string | null;
|
|
3
|
+
export declare function setUserToken(userToken: string, expiryDate?: Date): void;
|
|
4
|
+
export declare function useGuestSession(): void;
|
|
5
|
+
export declare function isAnonymousUser(): boolean;
|
|
6
|
+
export declare function getHashedUserToken(): Promise<string | null>;
|
|
7
|
+
export declare function getEncodedUserToken(): string | null;
|
|
8
|
+
export declare function clearUserToken(): void;
|