@joryio/web-sdk 1.4.0-beta.5 → 1.4.0-beta.7

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.
@@ -1,7 +1,7 @@
1
1
  /**
2
- * Joryio Web SDK v1.4.0-beta.5
2
+ * Joryio Web SDK v1.4.0-beta.7
3
3
  * (c) 2026 Joryio. All rights reserved.
4
4
  * @license Commercial - see https://github.com/joryio/joryio-web-sdk/blob/main/LICENSE
5
5
  */
6
- var JoryioSDK=function(t){"use strict";const i=16777619;function e(t){let e=2166136261;for(let s=0;s<t.length;s++){const n=t.charCodeAt(s);e^=255&n,e=Math.imul(e,i),e^=n>>>8&255,e=Math.imul(e,i)}return s=e>>>0,s=Math.imul(s^=s>>>16,2246822507),s=Math.imul(s^=s>>>13,3266489909),(s^=s>>>16)>>>0;var s}const s="1.4.0",n="X-Joryio-SDK",r="X-Joryio-SDK-Version";function o(){return{[n]:"web",[r]:s}}function h(t){const i=(t||"").trim();if(!i)return"https://api-eu1.joryio.com/api";const e=(/^https?:\/\//i.test(i)?i:"https://"+i).replace(/\/+$/,"");try{const t=new URL(e);if(""===t.pathname||"/"===t.pathname)return e+"/api"}catch(t){}return e}const a={allowHtmlJsInAppMessages:"inApp",evaluationMode:"inApp",syncInterval:"inApp",displayOptions:"inApp"};const l=["source","medium","campaign","term","content"],u=["page_view","exit_intent","scroll_depth","time_on_page"],c="page_context",d=/^[A-Za-z_$][A-Za-z0-9_$.-]{0,63}$/;function f(t){const i=(t||"/").toLowerCase();return i.length>1&&i.endsWith("/")?i.slice(0,-1):i}function p(t,i){var e;const s=/^(https?:\/\/[^/]+)(.*)$/i.exec(i);if(!s)return!1;const n=s[1].toLowerCase(),r=s[2]||"/";let o=((null!==(e=t.value)&&void 0!==e?e:"")+"").trim();const h="contains"===t.op?n+r:r,a="contains"===t.op?null:/^(https?:\/\/[^/?#]+)([^?#]*)/i.exec(o);if(a){if(a[1].toLowerCase()!==n)return!1;o=a[2]||"/"}switch(t.op){case"equals":return f(o)===f(h);case"contains":return!!o&&h.toLowerCase().includes(o.toLowerCase());case"matches":return function(t,i){const e=f(t),s=f(i),n=[];for(let t=0;t<e.length;t++)if("*"===e[t])if("*"===e[t+1])for(n.push("**");"*"===e[t+1];)t++;else n.push("*");else n.push(e[t]);let r=Array(s.length+1).fill(!1);r[0]=!0;for(const t of n){const i=Array(s.length+1).fill(!1);if("*"===t||"**"===t)for(let e=0;e<=s.length;e++)(r[e]||e>0&&i[e-1]&&("**"===t||"/"!==s[e-1]))&&(i[e]=!0);else for(let e=1;e<=s.length;e++)i[e]=r[e-1]&&s[e-1]===t;r=i}return r[s.length]}(o,h);default:return!1}}function y(t){var i,e,s,n,r;return!(!t||!(null===(e=null===(i=t.urls)||void 0===i?void 0:i.include)||void 0===e?void 0:e.length)&&!(null===(n=null===(s=t.urls)||void 0===s?void 0:s.exclude)||void 0===n?void 0:n.length)&&!(null===(r=t.variables)||void 0===r?void 0:r.length))}const v=t=>!!t&&u.includes(t.type+"");function m(){try{const t="undefined"!=typeof window?window.location:void 0;return t&&t.origin&&"null"!==t.origin?`${t.origin}${t.pathname}`:null}catch(t){return null}}function b(t){return"string"==typeof t?t.slice(0,200):"number"==typeof t&&Number.isFinite(t)||"boolean"==typeof t?t:void 0}function g(t,i){let e=t;for(const t of i.split(".")){if(null===e||"object"!=typeof e||!Object.prototype.hasOwnProperty.call(e,t))return;e=e[t]}return e}class w{constructor(t={}){this.options=t,this.explicit={},this.listeners=new Set,this.url=m(),this.maxScrollPercent=0,this.visibleMs=0,this.visibleSince=null,this.exitFired=!1,this.timer=null,this.undo=[],this.started=!1,this.utmSource=null}setUtmSource(t){this.utmSource=t}utm(){let t=null;try{t=this.utmSource?this.utmSource():null}catch(t){return}if(!t)return;const i=t=>{if(!t||"object"!=typeof t)return;const i=t,e={};for(const t of l){const s=i["utm_"+t];"string"==typeof s&&s.trim()&&(e[t]=s.trim().slice(0,200))}return Object.keys(e).length?e:void 0},e=i(t.current),s=i(t.firstTouch);return e||s?Object.assign(Object.assign({},e?{session:e}:{}),s?{firstTouch:s}:{}):void 0}setPageVariables(t){const i={};let e=0;for(const[s,n]of Object.entries(t||{})){if(e>=20||!d.test(s))continue;const t=b(n);void 0!==t&&(i[s]=t,e++)}this.explicit=i}current(){const t=Object.assign({},this.explicit),i="undefined"!=typeof window?window:{};for(const e of(this.options.pageVariables||[]).slice(0,20)){if(Object.keys(t).length>=20)break;if(d.test(e)&&!(e in t))try{const s=b(g(i,e));void 0!==s&&(t[e]=s)}catch(t){}}const e={},s=(this.options.dataLayerVariables||[]).filter(t=>d.test(t)).slice(0,20);if(s.length)try{const t=i[this.options.dataLayerName||"dataLayer"];if(Array.isArray(t))for(let i=t.length-1;i>=0&&Object.keys(e).length<s.length;i--){const n=t[i];if(n&&"object"==typeof n&&!Array.isArray(n))for(const t of s){if(t in e)continue;const i=b(g(n,t));void 0!==i&&(e[t]=i)}}}catch(t){}const n=this.utm();return Object.assign({url:this.url,pageVariables:t,dataLayer:e},n?{utm:n}:{})}progress(){const t=null!==this.visibleSince?Date.now()-this.visibleSince:0;return{scrollPercent:this.maxScrollPercent,seconds:Math.floor((this.visibleMs+t)/1e3),exitIntent:this.exitFired}}onSignal(t){return this.listeners.add(t),()=>this.listeners.delete(t)}start(){if(this.started||"undefined"==typeof window||"undefined"==typeof document)return;this.started=!0,this.patchHistory();const t=(t,i,e,s)=>{t.addEventListener(i,e,s),this.undo.push(()=>t.removeEventListener(i,e,s))};t(window,"popstate",()=>this.checkRoute()),t(window,"scroll",()=>this.measureScroll(),{passive:!0}),t(document,"mouseout",t=>{this.exitFired||t.relatedTarget||t.toElement||"number"!=typeof t.clientY||t.clientY>0||(this.exitFired=!0,this.emit({type:"exit_intent"}))}),t(document,"visibilitychange",()=>this.visibilityChanged()),"hidden"!==document.visibilityState&&(this.visibleSince=Date.now()),this.timer=setInterval(()=>{const{seconds:t}=this.progress();null!==this.visibleSince&&this.emit({type:"time_on_page",seconds:t}),this.checkRoute()},1e3)}destroy(){this.timer&&clearInterval(this.timer),this.timer=null;for(const t of this.undo.splice(0).reverse())try{t()}catch(t){}this.listeners.clear(),this.started=!1}checkRoute(){const t=m();t!==this.url&&(this.url=t,this.maxScrollPercent=0,this.visibleMs=0,this.visibleSince="undefined"!=typeof document&&"hidden"===document.visibilityState?null:Date.now(),this.exitFired=!1,this.emit({type:"page_change",url:t}))}patchHistory(){const t="undefined"!=typeof history?history:null;if(t)for(const i of["pushState","replaceState"]){const e=t[i];if("function"!=typeof e)continue;const s=this,n=function(...t){const i=e.apply(this,t);try{s.checkRoute()}catch(t){}return i};t[i]=n,this.undo.push(()=>{t[i]===n&&(t[i]=e)})}}measureScroll(){var t;try{const i=document.documentElement,e=Math.max(i.scrollHeight,(null===(t=document.body)||void 0===t?void 0:t.scrollHeight)||0)-window.innerHeight,s=e>0?Math.min(100,Math.round((window.scrollY||i.scrollTop)/e*100)):100;s>this.maxScrollPercent&&(this.maxScrollPercent=s,this.emit({type:"scroll_depth",percent:s}))}catch(t){}}visibilityChanged(){"hidden"===document.visibilityState?(null!==this.visibleSince&&(this.visibleMs+=Date.now()-this.visibleSince),this.visibleSince=null):null===this.visibleSince&&(this.visibleSince=Date.now())}emit(t){for(const i of Array.from(this.listeners))try{i(t)}catch(t){}}}function k(t,i,e){const s=+t.value;switch(t.type){case"page_view":return"page_change"===i.type;case"exit_intent":return"exit_intent"===i.type;case"scroll_depth":return("scroll_depth"===i.type||"page_change"===i.type)&&Number.isFinite(s)&&s>0&&e.scrollPercent>=s;case"time_on_page":return"time_on_page"===i.type&&Number.isFinite(s)&&s>0&&e.seconds>=s;default:return!1}}const S=["before","after","prepend","append"],j=/^[a-z0-9][a-z0-9_]{0,63}$/,O="joryio-page-edits-anti-flicker",A="data-joryio-applied",I="data-joryio-orig",_="data-joryio-server-spot",T=(t,i)=>{var e,s,n,r,o,h;return t.id===i.id&&t.selector===i.selector&&t.operation===i.operation&&(null!==(e=t.value)&&void 0!==e?e:null)===(null!==(s=i.value)&&void 0!==s?s:null)&&(null!==(n=t.placementKey)&&void 0!==n?n:null)===(null!==(r=i.placementKey)&&void 0!==r?r:null)&&(null!==(o=t.position)&&void 0!==o?o:null)===(null!==(h=i.position)&&void 0!==h?h:null)&&!i.personalized};function $(t){if("string"!=typeof t||t.length>2048)return null;if(/[\u0000-\u001f\u007f]/.test(t))return null;const i=t.trim();return/^https?:\/\//i.test(i)?t:/^[a-z][a-z0-9+.-]*:/i.test(i)?null:t}const D=t=>"string"==typeof t&&t.split(",").every(t=>!t.trim()||null!==$(t.trim().split(/\s+/)[0]))?t:null,C=new Set(["A","ABBR","B","BDI","BDO","BR","CITE","CODE","DATA","DEL","DFN","EM","I","IMG","INS","KBD","MARK","Q","S","SAMP","SMALL","SPAN","STRONG","SUB","SUP","TIME","U","VAR","WBR"]),P=new Set(["class","id","title","lang","dir","alt","width","height","datetime","href","src","srcset","rel","target"]);function M(t){const i=document.createDocumentFragment();let e=500;const s=(t,i)=>{for(const n of Array.from(t.childNodes)){if(0>=e--)return;if(3===n.nodeType)i.appendChild(document.createTextNode(n.nodeValue||""));else if(1===n.nodeType){const t=n;if("http://www.w3.org/1999/xhtml"!==t.namespaceURI||!C.has(t.tagName)){/^(SCRIPT|STYLE|TEMPLATE|IFRAME|OBJECT|EMBED|NOSCRIPT|TEXTAREA|TITLE)$/.test(t.tagName)||s(t,i);continue}const e=document.createElement(t.tagName.toLowerCase());for(const i of Array.from(t.attributes)){const t=i.name.toLowerCase();if(P.has(t))if("href"===t||"src"===t){const s=$(i.value);null!==s&&e.setAttribute(t,s)}else if("srcset"===t){const s=D(i.value);null!==s&&e.setAttribute(t,s)}else e.setAttribute(t,i.value)}i.appendChild(e),s(t,e)}}};return s(t,i),i}const x=t=>(t.getAttribute(A)||"").split(/\s+/).filter(Boolean);function K(t){if("string"!=typeof t)return!1;const i=t.trim();if(!i||i.length>500)return!1;if(/[{};<@]/.test(i)||i.includes("/*")||i.includes("*/"))return!1;if(/[\u0000-\u001f\u007f]/.test(i))return!1;try{"undefined"!=typeof document&&document.createDocumentFragment().querySelector(i)}catch(t){return!1}return!0}function N(t){if(!t||"object"!=typeof t||"string"!=typeof t.id||!K(t.selector))return null;const i=Object.assign({id:t.id,selector:t.selector.trim()},!0===t.personalized?{personalized:!0}:{});switch(t.operation){case"hide":return Object.assign(Object.assign({},i),{operation:"hide"});case"replace_text":return"string"!=typeof t.value||t.value.length>2e3?null:Object.assign(Object.assign({},i),{operation:"replace_text",value:t.value});case"replace_image":case"replace_link":return function(t){if("string"!=typeof t)return!1;const i=t.trim();return!(!i||i.length>2048)&&!/[\u0000-\u001f\u007f\s]/.test(i)&&/^https?:\/\/[^/?#\s]+/i.test(i)}(t.value)?Object.assign(Object.assign({},i),{operation:t.operation,value:t.value.trim()}):null;case"insert_placement":return"string"==typeof t.placementKey&&j.test(t.placementKey)?Object.assign(Object.assign({},i),{operation:"insert_placement",placementKey:t.placementKey,position:S.includes(t.position)?t.position:"after"}):null;default:return null}}class F{constructor(t,i,s,n,r,o,h){this.apiEndpoint=t,this.sdkKey=i,this.identity=s,this.session=n,this.logger=r,this.runtime=o,this.auth=h,this.page=null,this.pageUnsubscribe=null,this.experiences=[],this.applied=[],this.reported=new Set,this.observer=null,this.scheduled=!1,this.flickerTimer=null,this.pageStartedAt=0,this.site=null,this.siteRequest=null,this.server=null,this.serverUrl=null,this.generation=0,this.started=!1,this.destroyed=!1,this.stores=(t=>{const i=e(t).toString(36);return{answers:"jry_page_edits_"+i,selectors:"jry_page_edit_selectors_"+i,site:"jry_page_edit_site_"+i}})(i);try{localStorage.removeItem("jry_page_edit_selectors"),sessionStorage.removeItem("jry_page_edits")}catch(t){}}setPageContext(t){var i;null===(i=this.pageUnsubscribe)||void 0===i||i.call(this),this.pageUnsubscribe=null,this.page=t,t&&(this.pageUnsubscribe=t.onSignal(t=>{"page_change"===t.type&&this.started&&this.loadPage()}))}start(){this.started||this.destroyed||"undefined"==typeof document||(this.started=!0,"undefined"!=typeof MutationObserver&&document.documentElement&&(this.observer=new MutationObserver(()=>this.schedule()),this.observer.observe(document.documentElement,{childList:!0,subtree:!0})),this.loadPage())}invalidate(t={}){this.generation++,this.reported.clear(),t.siteSettings&&this.forgetSite();try{sessionStorage.removeItem(this.stores.answers)}catch(t){}this.started&&this.loadPage()}destroy(){var t,i;this.destroyed=!0,null===(t=this.pageUnsubscribe)||void 0===t||t.call(this),null===(i=this.observer)||void 0===i||i.disconnect(),this.observer=null,this.revertAll(),this.showAll()}appliedCount(){return this.applied.length}serverAppliedCount(){return this.serverEdits().size}url(){return this.page?this.page.current().url:m()}loadPage(){const t=++this.generation;this.revertAll();const i=this.url();if(!i)return void(this.experiences=[]);this.pageStartedAt=Date.now();const e=this.serverEdits();null===this.serverUrl?this.serverUrl=i:i!==this.serverUrl&&e.size&&this.reconcileServer([]);const s=this.rememberedSelectors(i);this.hide(s),this.experiences=this.cachedExperiences(i),this.applyAll(),this.siteThenFetch(i,t,s.length>0)}async siteThenFetch(t,i,e){const s=this.storedSite();let n;if(s?(n=s.value,6e5>Date.now()-s.at||this.requestSite().then(e=>{!(e&&e.enabled&&e.active)||n.enabled&&n.active||i!==this.generation||this.destroyed||this.fetch(t,i)})):n=await this.siteSettings(),i===this.generation&&!this.destroyed){if(n&&(!n.enabled||!n.active))return this.revertAll(),this.reconcileServer([]),this.experiences=[],void this.showAll();n&&!e&&n.antiFlickerSelectors.length&&this.hide(n.antiFlickerSelectors),await this.fetch(t,i)}}siteSettings(){const t=this.storedSite();return t&&6e5>Date.now()-t.at?Promise.resolve(t.value):this.requestSite()}storedSite(){const t=this.session.getSessionId();if(!t)return null;if(this.site&&this.site.sid===t)return this.site;this.site=null;try{const i=JSON.parse(sessionStorage.getItem(this.stores.site)||"null"),e=null==i?void 0:i.value;i&&i.sid===t&&"number"==typeof i.at&&i.at<=Date.now()&&e&&"object"==typeof e?this.site={sid:t,at:i.at,value:{enabled:!1!==e.enabled,active:!1!==e.active,antiFlickerSelectors:(Array.isArray(e.antiFlickerSelectors)?e.antiFlickerSelectors:[]).filter(K).slice(0,200)}}:i&&sessionStorage.removeItem(this.stores.site)}catch(t){}return this.site}forgetSite(){this.site=null;try{sessionStorage.removeItem(this.stores.site)}catch(t){}}requestSite(){if(this.siteRequest)return this.siteRequest;const t=(async()=>{var t,i;const e=this.session.getSessionId();try{const s=await fetch(`${this.apiEndpoint}/v1/in-app/site-settings?sdkKey=${encodeURIComponent(this.sdkKey)}`,{method:"GET",credentials:"omit"});if(!s.ok)return null===(i=(t=this.runtime).noteStatus)||void 0===i||i.call(t,s.status,null),this.forgetSite(),null;const n=await s.json(),r=null==n?void 0:n.pageEdits;if(!r||"object"!=typeof r)return this.forgetSite(),null;const o={enabled:!1!==r.enabled,active:!1!==r.active,antiFlickerSelectors:(Array.isArray(r.antiFlickerSelectors)?r.antiFlickerSelectors:[]).filter(K).slice(0,200)};if(e){this.site={sid:e,at:Date.now(),value:o};try{sessionStorage.setItem(this.stores.site,JSON.stringify(this.site))}catch(t){}}return o}catch(t){return this.logger.debug("Site settings request failed",t),this.forgetSite(),null}finally{this.siteRequest=null}})();return this.siteRequest=t,t}async fetch(t,i){var e,s,n,r;const h=this.runtime.consent();if(null===h||this.destroyed)return void this.showAll();const a="granted"===h,l=a?this.identity.getUserId():null,u=a?this.identity.getAnonymousId():null,d=Object.assign(Object.assign(Object.assign(Object.assign({},l?{userId:l}:{}),u?{anonymousId:u}:{}),a?{sessionId:this.session.getSessionId()}:{}),{deviceType:"web",locale:"undefined"!=typeof navigator?navigator.language:void 0,capabilities:[c,"page_edits"],trackingConsent:h,context:this.page?this.page.current():{url:t,pageVariables:{},dataLayer:{}}}),f="undefined"!=typeof AbortController?new AbortController:null,p=setTimeout(()=>null==f?void 0:f.abort(),null!==(e=this.runtime.requestTimeoutMs)&&void 0!==e?e:1e4);try{const e=await fetch(this.apiEndpoint+"/v1/in-app/page-edits",Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),a&&(null===(s=this.auth)||void 0===s?void 0:s.getSdkAuthHeaders(l,l?null:u))||{}),body:JSON.stringify(d)},f?{signal:f.signal}:{}));if(i!==this.generation)return;if(!e.ok)return void(null===(r=(n=this.runtime).noteStatus)||void 0===r||r.call(n,e.status,null));const h=await e.json();if(i!==this.generation||!h||!1===h.success||!Array.isArray(h.experiences))return;const c=h.experiences.filter(t=>t&&"string"==typeof t.id).map(t=>({wire:t,edits:(Array.isArray(t.edits)?t.edits:[]).map(N).filter(t=>!!t)}));this.revertAll(),this.experiences=c,this.reconcileServer(c),this.remember(t,c,h.ttlSeconds),this.applyAll()}catch(t){this.logger.debug("Page edits request failed",t)}finally{clearTimeout(p),i===this.generation&&this.showAll()}}schedule(){if(this.scheduled||this.destroyed)return;this.scheduled=!0;const t=()=>{this.scheduled=!1,this.applyAll()};"function"==typeof queueMicrotask?queueMicrotask(t):Promise.resolve().then(t)}applyAll(){var t,i;if(!this.destroyed&&"undefined"!=typeof document){null===(t=this.observer)||void 0===t||t.disconnect();try{for(const t of this.experiences){if(t.wire.isControl){(t.wire.selectors||[]).some(t=>K(t)&&this.query(t).length>0)&&this.reportControl(t.wire);continue}let e=!1;for(const s of t.edits){const n=`${t.wire.id}:${s.id}`,r=this.serverEdits().get(n),o=!!r&&r.variantId===(null!==(i=t.wire.variantId)&&void 0!==i?i:null)&&T(r.edit,s);for(const t of this.query(s.selector)){if(this.applied.some(i=>i.el===t&&i.editId===s.id)){e=!0;continue}if(o&&x(t).includes(n)){e=!0;continue}const i=this.applyOne(t,s);i&&(this.applied.push({el:t,editId:s.id,undo:i}),e=!0)}}e&&this.reportDisplayed(t.wire)}}finally{this.observer&&document.documentElement&&this.observer.observe(document.documentElement,{childList:!0,subtree:!0})}}}query(t){try{return Array.from(document.querySelectorAll(t)).filter(t=>{var i,e;return!(null===(e=(i=t).closest)||void 0===e?void 0:e.call(i,"[data-joryio-editor]"))})}catch(t){return[]}}applyOne(t,i){var e;const s=t;switch(i.operation){case"replace_text":{const s=Array.from(t.childNodes);return t.textContent=null!==(e=i.value)&&void 0!==e?e:"",()=>{t.textContent="",s.forEach(i=>t.appendChild(i))}}case"replace_image":{if("IMG"!==t.tagName)return null;const e=t.getAttribute("src"),s=t.getAttribute("srcset");return t.setAttribute("src",i.value),t.removeAttribute("srcset"),()=>{null===e?t.removeAttribute("src"):t.setAttribute("src",e),null!==s&&t.setAttribute("srcset",s)}}case"replace_link":{if("A"!==t.tagName)return null;const e=t.getAttribute("href");return t.setAttribute("href",i.value),()=>null===e?t.removeAttribute("href"):t.setAttribute("href",e)}case"hide":{const t=s.style.getPropertyValue("display"),i=s.style.getPropertyPriority("display");return s.style.setProperty("display","none","important"),()=>t?s.style.setProperty("display",t,i):s.style.removeProperty("display")}case"insert_placement":{const e=document.createElement("div");e.setAttribute("data-joryio-placement",i.placementKey),e.setAttribute("data-joryio-edit",i.id);const s="before"===i.position?"beforebegin":"prepend"===i.position?"afterbegin":"append"===i.position?"beforeend":"afterend";return t.insertAdjacentElement(s,e),()=>e.remove()}default:return null}}revertAll(){var t;const i=this.applied.splice(0).reverse();if(i.length){null===(t=this.observer)||void 0===t||t.disconnect();try{for(const t of i)try{t.undo()}catch(t){}}finally{this.observer&&"undefined"!=typeof document&&document.documentElement&&this.observer.observe(document.documentElement,{childList:!0,subtree:!0})}}}hide(t){const i=t.filter(K);if(!i.length||"undefined"==typeof document)return;const e=300-(Date.now()-(this.pageStartedAt||Date.now()));if(0>=e)return;let s=document.getElementById(O);s||(s=document.createElement("style"),s.id=O,(document.head||document.documentElement).appendChild(s)),s.textContent=this.serverEdits().size?`:is(${i.join(",")}):not([${A}]){opacity:0 !important}`:i.join(",")+"{opacity:0 !important}",this.flickerTimer&&clearTimeout(this.flickerTimer),this.flickerTimer=setTimeout(()=>this.showAll(),e)}showAll(){var t;this.flickerTimer&&clearTimeout(this.flickerTimer),this.flickerTimer=null;try{null===(t=document.getElementById(O))||void 0===t||t.remove()}catch(t){}}subjectKey(){return`${this.identity.getUserId()||""}|${this.identity.getAnonymousId()}`}remember(t,i,e){const s=[...new Set(i.flatMap(t=>t.wire.isControl?[]:t.edits.map(t=>t.selector)))];try{const i=JSON.parse(localStorage.getItem(this.stores.selectors)||"{}")||{};delete i[t],s.length&&(i[t]=s.slice(0,50));const e=Object.keys(i);for(const t of e.slice(0,Math.max(0,e.length-50)))delete i[t];localStorage.setItem(this.stores.selectors,JSON.stringify(i))}catch(t){}try{const s=JSON.parse(sessionStorage.getItem(this.stores.answers)||"{}")||{},n=s.subject===this.subjectKey()&&s.pages?s.pages:{};n[t]={at:Date.now(),ttl:1e3*(e&&e>0?e:300),experiences:i.filter(t=>!t.wire.isControl).map(t=>Object.assign(Object.assign({},t.wire),{deliveryToken:null,edits:t.edits.filter(t=>!t.personalized)})).filter(t=>t.edits.length)},sessionStorage.setItem(this.stores.answers,JSON.stringify({subject:this.subjectKey(),pages:n}))}catch(t){}}rememberedSelectors(t){try{const i=JSON.parse(localStorage.getItem(this.stores.selectors)||"{}")||{};return Array.isArray(i[t])?i[t].filter(t=>"string"==typeof t):[]}catch(t){return[]}}cachedExperiences(t){var i;try{const e=JSON.parse(sessionStorage.getItem(this.stores.answers)||"{}")||{};if(e.subject!==this.subjectKey())return[];const s=null===(i=e.pages)||void 0===i?void 0:i[t];return!s||Date.now()-s.at>s.ttl?[]:(s.experiences||[]).map(t=>({wire:Object.assign(Object.assign({},t),{isControl:!1,deliveryToken:null}),edits:(t.edits||[]).map(N).filter(t=>!!t&&!t.personalized)}))}catch(t){return[]}}serverEdits(){if(this.server)return this.server;const t=new Map;if("undefined"==typeof document)return t;const i=function(){const t=document.head;if(!t)return null;for(const i of Array.from(t.children))if("joryio-server-page-edits"===i.id)return"SCRIPT"===i.tagName&&"application/json"===(i.getAttribute("type")||"").trim().toLowerCase()?i:null;return null}();if(!i)return"loading"!==document.readyState&&(this.server=t),t;try{const e=JSON.parse(i.textContent||"{}");if(e&&1===e.v&&Array.isArray(e.experiences))for(const i of e.experiences)if(i&&"string"==typeof i.id&&Array.isArray(i.edits))for(const e of i.edits){const s=N(e);s&&!s.personalized&&t.set(`${i.id}:${s.id}`,{experienceId:i.id,variantId:"string"==typeof i.variantId?i.variantId:null,edit:s})}}catch(t){}return this.server=t,t}reconcileServer(t){var i,e;const s=this.serverEdits();if(!s.size||"undefined"==typeof document)return;const n=new Set;for(const e of t)if(!e.wire.isControl)for(const t of e.edits){const r=`${e.wire.id}:${t.id}`,o=s.get(r);o&&o.variantId===(null!==(i=e.wire.variantId)&&void 0!==i?i:null)&&T(o.edit,t)&&n.add(r)}const r=[...s.keys()].filter(t=>!n.has(t));if(r.length){null===(e=this.observer)||void 0===e||e.disconnect();try{for(const t of r)this.undoServerEdit(t,s.get(t).edit),s.delete(t)}finally{this.observer&&document.documentElement&&this.observer.observe(document.documentElement,{childList:!0,subtree:!0})}}}undoServerEdit(t,i){var e;for(const s of Array.from(document.querySelectorAll(`[${A}]`))){const n=x(s);if(!n.includes(t))continue;let r={};try{r=JSON.parse(s.getAttribute(I)||"{}")||{}}catch(t){r={}}const o=r[t]||{};try{switch(i.operation){case"replace_text":{const e=Array.from(s.children).find(i=>"TEMPLATE"===i.tagName&&i.getAttribute(I)===t);if(e&&e.content&&s.textContent===i.value){const t=M(e.content);s.textContent="",s.appendChild(t)}break}case"replace_image":if("IMG"===s.tagName&&s.getAttribute("src")===i.value){const t=$(o.src),i=D(o.srcset);null===t?s.removeAttribute("src"):s.setAttribute("src",t),null!==i&&s.setAttribute("srcset",i)}break;case"replace_link":if("A"===s.tagName&&s.getAttribute("href")===i.value){const t=$(o.href);null===t?s.removeAttribute("href"):s.setAttribute("href",t)}break;case"hide":{const t=s.getAttribute("style")||"",i="string"==typeof o.style?o.style:null,n=null===i?"":i.trim().replace(/;+$/,"");t===(n?n+";":"")+"display:none !important"?null===i?s.removeAttribute("style"):s.setAttribute("style",i):"none"===(null===(e=s.style)||void 0===e?void 0:e.getPropertyValue("display"))&&s.style.removeProperty("display");break}}}catch(t){}const h=n.filter(i=>i!==t);h.length?s.setAttribute(A,h.join(" ")):s.removeAttribute(A),delete r[t],Object.keys(r).length?s.setAttribute(I,JSON.stringify(r)):s.removeAttribute(I)}if("insert_placement"===i.operation)for(const e of Array.from(document.querySelectorAll(`div[${_}][data-joryio-placement]`)))e.getAttribute(_)===t&&e.getAttribute("data-joryio-placement")===i.placementKey&&e.remove()}reportDisplayed(t){if(!t.deliveryToken||"granted"!==this.runtime.consent())return;const i="displayed:"+(t.deliveryId||t.deliveryToken);this.reported.has(i)||(this.reported.add(i),this.post(Object.assign(Object.assign({campaignId:t.id},t.variantId?{variantId:t.variantId}:{}),{deliveryToken:t.deliveryToken,action:"displayed",displayedAt:(new Date).toISOString()})))}reportControl(t){if(!t.controlToken||"granted"!==this.runtime.consent())return;const i="control:"+t.controlToken;this.reported.has(i)||(this.reported.add(i),this.post({action:"control_viewed",controlToken:t.controlToken,viewedAt:(new Date).toISOString()}))}post(t){var i;const e=this.identity.getUserId(),s=Object.assign(Object.assign(Object.assign({},t),e?{userId:e}:{}),{anonymousId:this.identity.getAnonymousId(),sessionId:this.session.getSessionId(),deviceType:"web"});fetch(this.apiEndpoint+"/v1/in-app/track",{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(i=this.auth)||void 0===i?void 0:i.getSdkAuthHeaders(e,e?null:this.identity.getAnonymousId()))||{}),body:JSON.stringify(s),keepalive:!0}).then(t=>{var i,e;t.ok||null===(e=(i=this.runtime).noteStatus)||void 0===e||e.call(i,t.status,null)}).catch(t=>this.logger.debug("Page edit report failed",t))}}const E="https://sdk.joryio.com",U=/\/joryio(?:\.umd)?(?:\.min)?\.js$/;function q(t){if(!t||"string"!=typeof t)return null;let i;try{i=new URL(t)}catch(t){return null}return"https:"===i.protocol&&U.test(i.pathname)?`${i.origin}${i.pathname.replace(/[^/]*$/,"")}`:null}const z=function(){if("undefined"==typeof document)return null;try{const t=document.currentScript,i=q(t&&t.src);if(i||t&&t.src)return i;const e=document.querySelectorAll("script[src]");for(let t=e.length-1;t>=0;t--){const i=q(e[t].src);if(i)return i}}catch(t){}return null}();function J(t,i,e=z){if(i)return[i];const n=`${E}/web/${s}/${t}`,r=`${E}/web/1/${t}`,o=e&&e!==E+"/web/1/"?[`${e}${t}`,n,r]:[n,r];return o.filter((t,i)=>o.indexOf(t)===i)}function R(t,i){return new Promise((e,s)=>{const n=document.createElement("script");n.src=t,n.async=!0,n.setAttribute(i,"bundle"),n.onload=()=>e(),n.onerror=()=>{n.remove(),s(Error("could not load "+t))},(document.head||document.documentElement).appendChild(n)})}const L="__joryioEditor";function H(){try{return"undefined"!=typeof window&&!!window.opener&&"1"===new URLSearchParams(window.location.search).get("joryio_editor")}catch(t){return!1}}function B(t){return R(t,"data-joryio-editor")}class V{constructor(t,i,e,s={}){this.apiEndpoint=t,this.sdkKey=i,this.logger=e,this.options=s,this.opener=null,this.dashboardOrigin=null,this.verifying=!1,this.session=null,this.off=null}start(){if(!H()||this.opener)return;this.opener=window.opener;const t=t=>{this.onMessage(t)};window.addEventListener("message",t),this.off=()=>window.removeEventListener("message",t);try{this.opener.postMessage({type:"joryio:editor-ready"},"*")}catch(t){}}isActive(){return!!this.session}stop(){var t;const i=this.session;this.session=null,null==i||i.stop(),null===(t=this.off)||void 0===t||t.call(this),this.off=null,this.dashboardOrigin=null,this.opener=null}async onMessage(t){var i;const e=t.data;if(e&&"string"==typeof e.type&&!this.dashboardOrigin&&"joryio:editor-token"===e.type&&t.source===this.opener&&"string"==typeof e.token&&!this.verifying){this.verifying=!0;try{const s=await fetch(this.apiEndpoint+"/v1/in-app/editor/verify",{method:"POST",headers:Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),body:JSON.stringify({token:e.token})}),n=s.ok?await s.json():null;if(!(null==n?void 0:n.valid)||"string"!=typeof n.dashboardOrigin||n.dashboardOrigin!==t.origin)return void this.logger.warn("Joryio editor: the editor token was not accepted for this site");this.dashboardOrigin=n.dashboardOrigin,null===(i=this.off)||void 0===i||i.call(this),this.off=null,await this.loadAndStart(n.dashboardOrigin)}catch(t){this.logger.debug("Joryio editor verification failed",t)}finally{this.verifying=!1}}}async loadAndStart(t){var i;const e=null!==(i=this.options.load)&&void 0!==i?i:B;let s=window[L];for(const t of s?[]:J("joryio-editor.min.js",this.options.scriptUrl))try{if(await e(t),s=window[L],s)break}catch(t){this.logger.debug("Joryio editor bundle failed to load",t)}s&&1===s.version&&"function"==typeof s.start&&this.opener?this.session=s.start({dashboardOrigin:t,opener:this.opener,logger:this.logger,onStop:()=>this.stop()}):this.logger.warn("Joryio editor: the editor could not be loaded (check that your Content-Security-Policy allows sdk.joryio.com)")}}class W{static hashKey(t){return e(t).toString(36)}constructor(t,i){this.memoryStore=new Map,this.prefix=`jry_${W.hashKey(t)}_`,this.logger=i,this.isLocalStorageAvailable=this.checkLocalStorageAvailable(),this.isLocalStorageAvailable||this.logger.warn("LocalStorage not available, using in-memory storage")}checkLocalStorageAvailable(){try{const t="__jry_test__";return localStorage.setItem(t,"test"),localStorage.removeItem(t),!0}catch(t){return!1}}getKey(t){return`${this.prefix}${t}`}storageKeyFor(t){return this.getKey(t)}set(t,i,e){const s={value:i,expiresAt:e?Date.now()+864e5*e:null};if(this.isLocalStorageAvailable)try{localStorage.setItem(this.getKey(t),JSON.stringify(s)),this.memoryStore.delete(t)}catch(i){this.logger.error("Failed to write to localStorage:",i);try{localStorage.removeItem(this.getKey(t))}catch(t){}this.memoryStore.set(t,s)}else this.memoryStore.set(t,s)}get(t){var i;let e=null;if(this.isLocalStorageAvailable)try{const i=localStorage.getItem(this.getKey(t));i&&(e=JSON.parse(i))}catch(i){this.logger.error("Failed to read from localStorage:",i);try{localStorage.removeItem(this.getKey(t))}catch(t){}}return e||(e=this.memoryStore.get(t)||null),e&&e.expiresAt&&e.expiresAt<Date.now()?(this.remove(t),null):null!==(i=null==e?void 0:e.value)&&void 0!==i?i:null}remove(t){if(this.isLocalStorageAvailable)try{localStorage.removeItem(this.getKey(t))}catch(t){this.logger.error("Failed to remove from localStorage:",t)}this.memoryStore.delete(t)}clear(){if(this.isLocalStorageAvailable)try{const t=[];for(let i=0;i<localStorage.length;i++){const e=localStorage.key(i);e&&e.startsWith(this.prefix)&&t.push(e)}t.forEach(t=>localStorage.removeItem(t))}catch(t){this.logger.error("Failed to clear localStorage:",t)}this.memoryStore.clear()}}function X(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const i=16*Math.random()|0;return("x"===t?i:3&i|8).toString(16)})}function G(){if("undefined"!=typeof crypto&&crypto.getRandomValues){const t=new Uint8Array(6);return crypto.getRandomValues(t),Date.now().toString(36)+Array.from(t,t=>t.toString(16).padStart(2,"0")).join("")}return Date.now().toString(36)+Math.random().toString(36).substr(2,9)}const Q="session_id",Z="session_start",Y="last_activity",tt=864e5;class it{constructor(t,i,e){this.currentSessionId=null,this.lastActivityAt=0,this.lastActivityPersistedAt=0,this.isNewSession=!1,this.onNewSessionCallback=null,this.boundVisibilityHandler=null,this.storage=t,this.logger=i,this.sessionTimeoutMs=e||18e5,this.initializeSession(),"undefined"!=typeof document&&(this.boundVisibilityHandler=()=>{"visible"===document.visibilityState&&this.checkAndRefreshSession()},document.addEventListener("visibilitychange",this.boundVisibilityHandler))}onNewSession(t){this.onNewSessionCallback=t}initializeSession(){const t=this.storage.get(Q),i=this.storage.get(Y),e=this.storage.get(Z);if(t&&i){const s=Date.now(),n=s-i,r=e?s-e:1/0;if(n<this.sessionTimeoutMs&&tt>r)return this.currentSessionId=t,this.isNewSession=!1,this.updateActivity(),void this.logger.debug("Resumed session: "+this.currentSessionId);tt>r?this.logger.debug(`Session expired (${n}ms since last activity)`):this.logger.debug(`Session too old (${Math.round(r/1e3/60/60)}h), creating new session`)}this.startNewSession()}startNewSession(){const t=this.currentSessionId;this.currentSessionId=G(),this.isNewSession=!0;const i=Date.now();this.storage.set(Q,this.currentSessionId),this.storage.set(Z,i),this.storage.set(Y,i),this.lastActivityAt=i,this.lastActivityPersistedAt=i,this.logger.debug("Started new session: "+this.currentSessionId),t&&this.onNewSessionCallback&&this.onNewSessionCallback()}checkAndRefreshSession(){const t=this.storage.get(Y),i=this.storage.get(Z);if(t&&i){const e=Date.now(),s=e-t,n=e-i;s<this.sessionTimeoutMs?tt>n||(this.logger.debug(`Session too old on tab focus (${Math.round(n/1e3/60/60)}h old)`),this.startNewSession()):(this.logger.debug(`Session expired on tab focus (${Math.round(s/1e3/60)} min inactive)`),this.startNewSession())}}refreshIfExpired(){if(!this.currentSessionId)return!1;const t=Date.now(),i=Math.max(this.lastActivityAt,this.storage.get(Y)||0)||t,e=this.storage.get(Z)||t;return t-i<this.sessionTimeoutMs?t-e>=tt&&(this.logger.debug("Session reached its maximum age"),this.startNewSession(),!0):(this.logger.debug(`Session expired (${Math.round((t-i)/1e3/60)} min inactive)`),this.startNewSession(),!0)}updateActivity(){if(!this.currentSessionId)return;const t=Date.now();this.lastActivityAt=t,3e4>t-this.lastActivityPersistedAt||(this.lastActivityPersistedAt=t,this.storage.set(Y,t))}getSessionInfo(){return{sessionId:this.currentSessionId||this.storage.get(Q)||"",sessionStart:this.storage.get(Z)||Date.now(),lastActivity:this.lastActivityAt||this.storage.get(Y)||Date.now(),isNewSession:this.isNewSession}}getSessionId(){return this.currentSessionId||this.storage.get(Q)||""}ensureSession(){if(this.currentSessionId)return this.currentSessionId;const t=this.storage.get(Q);if(t)return this.currentSessionId=t,t;this.currentSessionId=G(),this.isNewSession=!0;const i=Date.now();return this.storage.set(Q,this.currentSessionId),this.storage.set(Z,i),this.storage.set(Y,i),this.lastActivityAt=i,this.lastActivityPersistedAt=i,this.logger.debug("Started new session: "+this.currentSessionId),this.onNewSessionCallback&&this.onNewSessionCallback(),this.currentSessionId}followStoredSession(){const t=this.storage.get(Q);return t!==this.currentSessionId&&(this.currentSessionId=t||null,this.isNewSession=!1,this.lastActivityAt=t?this.storage.get(Y)||Date.now():0,this.lastActivityPersistedAt=this.lastActivityAt,this.logger.debug("Following the session another tab started: "+(t||"(none)")),!0)}renewSession(){this.updateActivity(),this.logger.debug("Session renewed: "+this.currentSessionId)}resetSession(){this.logger.debug(`Resetting session (was: ${this.currentSessionId})`),this.startNewSession()}clear(){this.currentSessionId=null,this.isNewSession=!1,this.lastActivityAt=0,this.lastActivityPersistedAt=0,this.storage.remove(Q),this.storage.remove(Z),this.storage.remove(Y)}destroy(){this.boundVisibilityHandler&&"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.boundVisibilityHandler=null)}}function et(t,i){return t&&i?t.anonymousId===i.anonymousId&&(t.userId||null)===(i.userId||null):!t&&!i}class st{constructor(t=500){this.maxEntries=t,this.entries=[]}add(t,i,e,s){if(!i)return;const n=s?Object.assign({},s):void 0;if("set"===t||"unset"===t)return this.entries=this.entries.filter(t=>t.key!==i||t.inFlight||!et(t.owner,n)),this.entries.push("set"===t?{key:i,kind:t,value:e,owner:n}:{key:i,kind:t,owner:n}),void this.trim();const r=this.lastFor(i);if(r&&!r.inFlight&&r.kind===t&&et(r.owner,n))if("increment"===t)r.value=(+r.value||0)+ +e;else for(const t of nt(e))rt(r.values,t)||r.values.push(t);else"increment"===t?this.entries.push({key:i,kind:t,value:+e,owner:n}):this.entries.push({key:i,kind:t,values:ot(nt(e)),owner:n}),this.trim()}mark(t,i){for(const[e,s]of Object.entries(t.attributes||{}))this.add("set",e,s,i);for(const e of t.unset||[])this.add("unset",e,void 0,i);for(const[e,s]of Object.entries(t.increment||{}))"number"==typeof s&&Number.isFinite(s)&&this.add("increment",e,s,i);for(const[e,s]of Object.entries(t.append||{}))this.add("append",e,s,i);for(const[e,s]of Object.entries(t.remove||{}))this.add("remove",e,s,i)}isEmpty(){return 0===this.entries.length}hasUnsent(){return this.entries.some(t=>!t.inFlight)}nextRequest(t){return this.build(!0,t)}peekRequest(t){return this.build(!1,t)}toOps(){var t,i;return null!==(i=null===(t=this.peekRequest())||void 0===t?void 0:t.ops)&&void 0!==i?i:null}acknowledge(t){const i=new Set(t);this.entries=this.entries.filter(t=>!i.has(t))}release(t,i){let e=0;const s=new Set(t);return this.entries=this.entries.filter(t=>!s.has(t)||(t.inFlight=!1,!i||"increment"!==t.kind||(e++,!1))),e}drop(t){this.acknowledge(t)}dropIncrements(t){const i=new Set(t.filter(t=>"increment"===t.kind));this.entries=this.entries.filter(t=>!i.has(t))}pending(t){const i={};for(const e of this.entries)t&&e.owner&&e.owner.anonymousId!==t||("set"===e.kind?i[e.key]=e.value:"unset"===e.kind&&delete i[e.key]);return i}serialize(){return this.entries.map(t=>{const i={key:t.key,kind:t.kind};return"set"!==t.kind&&"increment"!==t.kind||(i.value=t.value),t.values&&(i.values=[...t.values]),t.owner&&(i.owner=Object.assign({},t.owner)),t.attempts&&(i.attempts=t.attempts),i})}restore(t){if(Array.isArray(t))for(const i of t){if(!i||"object"!=typeof i||"string"!=typeof i.key)continue;const t=i.kind,e=i.owner&&"object"==typeof i.owner&&"string"==typeof i.owner.anonymousId?Object.assign({anonymousId:i.owner.anonymousId},"string"==typeof i.owner.userId?{userId:i.owner.userId}:{}):void 0,s=this.entries.length;"set"===t?this.add("set",i.key,i.value,e):"unset"===t?this.add("unset",i.key,void 0,e):"increment"===t&&"number"==typeof i.value&&Number.isFinite(i.value)?this.add("increment",i.key,i.value,e):"append"!==t&&"remove"!==t||!Array.isArray(i.values)||this.add(t,i.key,i.values,e);const n=this.entries.length>s?this.entries[this.entries.length-1]:void 0;n&&Number.isInteger(i.attempts)&&i.attempts>0&&(n.attempts=i.attempts)}}pinOwner(t,i){for(const e of this.entries)e.owner&&(e.owner.anonymousId!==t||e.owner.userId)||(e.owner={anonymousId:t,userId:i})}clear(){this.entries=[]}build(t,i=t=>t){var e,s,n,r,o;const h=new Set(this.entries.filter(t=>t.inFlight).map(t=>t.key)),a=new Set,l={},u=[];let c,d=!1;for(const t of this.entries){if(t.inFlight||h.has(t.key)||a.has(t.key)){a.add(t.key);continue}const f=i(t.owner);if(!d||et(f,c))switch(d||(d=!0,c=f),a.add(t.key),u.push(t),t.kind){case"set":(null!==(e=l.attributes)&&void 0!==e?e:l.attributes={})[t.key]=t.value;break;case"unset":(null!==(s=l.unset)&&void 0!==s?s:l.unset=[]).push(t.key);break;case"increment":(null!==(n=l.increment)&&void 0!==n?n:l.increment={})[t.key]=t.value;break;case"append":(null!==(r=l.append)&&void 0!==r?r:l.append={})[t.key]=[...t.values];break;case"remove":(null!==(o=l.remove)&&void 0!==o?o:l.remove={})[t.key]=[...t.values]}else a.add(t.key)}if(!u.length)return null;if(t)for(const t of u)t.inFlight=!0;return Object.assign({ops:l,entries:u},c?{owner:Object.assign({},c)}:{})}lastFor(t){for(let i=this.entries.length-1;i>=0;i--)if(this.entries[i].key===t)return this.entries[i]}trim(){for(;this.entries.length>this.maxEntries;){const t=this.entries.findIndex(t=>!t.inFlight);if(0>t)break;this.entries.splice(t,1)}}}function nt(t){return Array.isArray(t)?[...t]:[t]}function rt(t,i){if(null!==i&&"object"==typeof i){const e=ht(i);return t.some(t=>null!==t&&"object"==typeof t&&ht(t)===e)}return t.some(t=>Object.is(t,i))}function ot(t){const i=[];for(const e of t)rt(i,e)||i.push(e);return i}function ht(t){try{return JSON.stringify(t)}catch(i){return t+""}}const at="user_id",lt="anonymous_id",ut="user_attributes";class ct{constructor(t,i,e,s){this.pending=new st,this.userId=null,this.attributes={},this.storage=t,this.logger=i,this.anonymousId=s||this.storage.get(lt)||X(),this.storage.get(lt)||(this.storage.set(lt,this.anonymousId),this.logger.debug("Generated new anonymous ID: "+this.anonymousId)),this.userId=e||this.storage.get(at)||null,this.userId&&this.logger.debug("Loaded user ID: "+this.userId),this.attributes={},this.storage.remove(ut)}identify(t,i){const e=this.userId;this.userId=t,this.storage.set(at,t),i&&this.setAttributes(i),e!==t&&this.logger.info(`User identified: ${t} (was: ${e||"anonymous"})`)}reset(t){this.logger.debug(`Resetting identity (was: ${this.userId||"anonymous"})`),this.userId=null,this.attributes={},this.anonymousId=t||X(),this.storage.remove(at),this.storage.remove(ut),this.storage.set(lt,this.anonymousId),this.logger.debug("New anonymous ID: "+this.anonymousId)}adopt(t,i){t!==this.anonymousId&&(this.attributes={}),this.anonymousId=t,this.userId=i}setAttributes(t){t&&"object"==typeof t&&!Array.isArray(t)?(this.attributes=Object.assign(Object.assign({},this.attributes),t),this.logger.debug("Updated user attributes:",this.attributes)):this.logger.error("setAttributes requires a plain object")}setAttribute(t,i){this.attributes[t]=i,this.logger.debug(`Set attribute: ${t} = ${i}`)}incrementAttribute(t,i=1){const e=this.attributes[t],s="number"==typeof e?e:0;this.setAttribute(t,s+i),this.logger.debug(`Incremented attribute: ${t} by ${i} (now: ${this.attributes[t]})`)}unsetAttribute(t){delete this.attributes[t],this.logger.debug("Unset attribute: "+t)}addToArray(t,i){const e=this.attributes[t];let s=[];Array.isArray(e)?s=[...e]:null!=e&&(this.logger.warn(`Attribute ${t} is not an array, converting to array`),s=[e]),s.includes(i)?this.logger.debug(`Value already exists in array: ${t} = ${i}`):(s.push(i),this.setAttribute(t,s),this.logger.debug(`Added to array: ${t} = ${i}`))}removeFromArray(t,i){const e=this.attributes[t];if(!Array.isArray(e))return void this.logger.warn(`Attribute ${t} is not an array, cannot remove value`);const s=e.filter(t=>t!==i);s.length!==e.length?(this.setAttribute(t,s),this.logger.debug(`Removed from array: ${t} = ${i}`)):this.logger.debug(`Value not found in array: ${t} = ${i}`)}getIdentity(){return{userId:this.userId,anonymousId:this.anonymousId,attributes:Object.assign({},this.attributes)}}getUserId(){return this.userId}getAnonymousId(){return this.anonymousId}getAttributes(){return Object.assign({},this.attributes)}getAttribute(t){return this.attributes[t]}isIdentified(){return null!==this.userId}}function dt(t){return!!t&&"object"==typeof t&&!Array.isArray(t)&&!1===t.success}function ft(t){return{userId:t.userId,anonymousId:t.anonymousId,attributes:t.attributes||{}}}function pt(t){let i=0;for(let e=0;e<t.length;e++){const s=t.charCodeAt(e);128>s?i+=1:2048>s?i+=2:55296>s||s>56319?i+=3:(i+=4,e++)}return i}function yt(t,i=Date.now()){if(!t)return;const e=+t;if(Number.isFinite(e)&&e>=0)return Math.round(1e3*e);const s=Date.parse(t);return Number.isFinite(s)?Math.max(0,s-i):void 0}const vt="X-Joryio-Auth",mt=2592e6;function bt(t,i=Date.now()){if("string"==typeof t)return t?{token:t,at:i}:null;if(!t||"object"!=typeof t)return null;const{token:e,at:s,standby:n}=t;return"string"==typeof e&&e&&"number"==typeof s&&Number.isFinite(s)?!0===n?{token:e,at:s,standby:!0}:{token:e,at:s}:null}function gt(t){var i;const e=null===(i=wt(t))||void 0===i?void 0:i.sub;return"string"==typeof e&&e?e:null}function wt(t){if(!t)return null;try{const i=t.split(".")[1];if(!i)return null;const e=i.replace(/-/g,"+").replace(/_/g,"/"),s=e+"=".repeat((4-e.length%4)%4),n="function"==typeof atob?atob:t=>globalThis.Buffer.from(t,"base64").toString("binary"),r=decodeURIComponent(Array.prototype.map.call(n(s),t=>"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)).join("")),o=JSON.parse(r);return o&&"object"==typeof o&&!Array.isArray(o)?o:null}catch(t){return null}}function kt(t,i){const e=((t||"")+"").split("?")[0],s=i&&"object"==typeof i?i:{};if(e.endsWith("/v1/push/unregister"))return!0;if(e.endsWith("/v1/subscriptions/channel"))return"unsubscribed"===s.status;if(e.endsWith("/v1/subscriptions/group"))return"unsubscribe"===s.action;if(e.endsWith("/v1/attributes")){if(["increment","append","remove","unset"].some(t=>null!=s[t]&&Object.keys(s[t]).length>0))return!1;const t=s.attributes;if(!t||"object"!=typeof t||Array.isArray(t))return!1;const i=Object.keys(t);return i.length>0&&i.every(i=>"tracking_opted_out"===i&&!0===t[i])}return!1}function St(t){if(!t||"object"!=typeof t)return null;if("string"==typeof t.userId&&t.userId)return t.userId;if("string"==typeof t.externalId&&t.externalId)return t.externalId;if(t.identify&&"string"==typeof t.identify.userId&&t.identify.userId)return t.identify.userId;for(const i of[t.events,t.impressions])if(Array.isArray(i)){const t=i.find(t=>t&&"string"==typeof t.userId&&t.userId);if(t)return t.userId}return null}function jt(t){const i=wt(t);return i&&"joryio-storefront"===i.iss&&"string"==typeof i.vid&&i.vid&&"number"==typeof i.exp?{vid:i.vid,exp:i.exp}:null}function Ot(t){if(!t||"object"!=typeof t)return null;if(St(t))return null;const i=new Set,e=t=>{"string"==typeof t&&t&&i.add(t)};e(t.anonymousId),t.identify&&e(t.identify.anonymousId);for(const i of[t.events,t.impressions])Array.isArray(i)&&i.forEach(t=>t&&e(t.anonymousId));return 1===i.size?i.values().next().value:null}const At={failureThreshold:5,cooldownMs:3e4};class It{constructor(t,i,e,s){this.circuitState="closed",this.consecutiveFailures=0,this.circuitOpenedAt=0,this.sdkAuthEnabled=!1,this.sdkAuthFailureCallback=null,this.retiredSdkAuthTokens=new Map,this.retiredTokenStore=null,this.sdkAuthTokenUser=null,this.keepaliveBytesInFlight=0,this.currentUserId=null,this.storefrontTokenProvider=null,this.storefrontRefresh=null,this.anonymousIdSource=null,this.suspended=!1,this.sdkKey=t,this.logger=i,this.retryConfig=e,this.circuitBreakerConfig=Object.assign(Object.assign({},At),s)}setAnonymousIdSource(t){this.anonymousIdSource=t}setStorefrontIdentityToken(t){const i="string"==typeof t&&t?t:void 0;!i||jt(i)?this.storefrontToken=i:this.logger.warn("setStorefrontIdentityToken: not a storefront identity token - ignored")}setStorefrontIdentityTokenProvider(t){this.storefrontTokenProvider=t}clearStorefrontIdentityToken(){this.storefrontToken=void 0,this.storefrontRefresh=null}isStorefrontIdentityError(t,i){return 401===t&&!!i&&"object"==typeof i&&"storefront_identity_error"===i.error}storefrontTokenFor(t,i){const e=this.storefrontToken;if(!e)return;if(void 0===t?this.currentUserId:t)return;const s=jt(e),n=this.anonymousIdSource?this.anonymousIdSource():null;if(s&&n&&s.vid===n&&null!==i&&(void 0===i||i===s.vid)){if(1e3*s.exp-Date.now()>=3e4)return e;this.refreshStorefrontToken()}}refreshStorefrontToken(){if(!this.storefrontTokenProvider)return Promise.resolve(void 0);if(this.storefrontRefresh)return this.storefrontRefresh;const t=this.storefrontToken,i=this.storefrontTokenProvider;return this.storefrontRefresh=(async()=>{try{const e=await Promise.resolve(i());if("string"==typeof e&&e&&jt(e))return this.storefrontToken=e,e!==t?e:void 0}catch(t){this.logger.warn("The storefront identity token provider failed:",t)}})().finally(()=>{this.storefrontRefresh=null}),this.storefrontRefresh}async handleStorefrontIdentityError(t){const i=t&&"object"==typeof t?t.reason:void 0;if(this.logger.warn(`Storefront identity token refused (${i||"invalid"})`),"expired"===i){const t=this.storefrontToken;return await this.refreshStorefrontToken()||this.storefrontToken===t&&(this.storefrontToken=void 0),!0}return this.storefrontToken=void 0,!0}setSdkAuthenticationEnabled(t){this.sdkAuthEnabled=t}setSdkAuthenticationToken(t){const i="string"==typeof t&&t?t:void 0,e=this.sdkAuthToken;if(e&&i&&e!==i){const t=gt(e),s=gt(i),n=t||this.sdkAuthTokenUser,r=t&&s?t!==s:!!n&&n!==this.currentUserId;n&&r&&this.retireToken(n,e)}this.sdkAuthToken=i,this.sdkAuthTokenUser=i?this.currentUserId:null}retireSdkAuthToken(){const t=gt(this.sdkAuthToken),i=t||this.currentUserId,e=!!t&&t!==this.currentUserId;i&&this.sdkAuthToken&&this.retireToken(i,this.sdkAuthToken,e),this.sdkAuthToken=void 0,this.sdkAuthTokenUser=null}retireToken(t,i,e=!1){const s=new Map,n=this.retiredSdkAuthTokens.get(t);for(n&&n.token!==i&&s.set(t,n.token),this.retiredSdkAuthTokens.delete(t),this.retiredSdkAuthTokens.set(t,e?{token:i,at:Date.now(),standby:!0}:{token:i,at:Date.now()});this.retiredSdkAuthTokens.size>4;){const t=this.retiredSdkAuthTokens.keys().next().value;s.set(t,this.retiredSdkAuthTokens.get(t).token),this.retiredSdkAuthTokens.delete(t)}this.saveRetiredTokens(s)}switchUser(t){const i=this.currentUserId;if(i&&i!==t&&this.sdkAuthToken){const i=gt(this.sdkAuthToken);t&&i===t||this.retireSdkAuthToken()}if(this.currentUserId=t,!this.sdkAuthToken&&t){const i=this.retiredSdkAuthTokens.get(t);i&&gt(i.token)===t&&(this.sdkAuthToken=i.token,this.sdkAuthTokenUser=t)}this.adoptStandbyToken(t)}adoptStandbyToken(t){if(!t)return;const i=this.retiredSdkAuthTokens.get(t);i&&i.standby&&gt(i.token)===t&&(this.retiredSdkAuthTokens.set(t,{token:i.token,at:i.at}),this.saveRetiredTokens())}dropStandbySdkAuthTokens(t=new Set){if(this.retiredSdkAuthTokens.forEach((i,e)=>{i.standby&&!t.has(e)&&this.retiredSdkAuthTokens.delete(e)}),this.retiredTokenStore)try{this.retiredTokenStore.update(i=>{const e={},s=Date.now();for(const n of Object.keys(i||{})){const r=bt(i[n],s);!r||r.standby&&!t.has(n)||s-r.at>mt||(e[n]=r)}return e})}catch(t){this.logger.warn("Could not store the SDK authentication tokens:",t)}}setRetiredTokenStore(t){if(this.retiredTokenStore=t,!t)return;let i=null;try{i=t.load()}catch(t){this.logger.warn("Could not read the stored SDK authentication tokens:",t)}if(!i||"object"!=typeof i)return;const e=Date.now();for(const t of Object.keys(i)){const s=bt(i[t],e);s&&e-s.at<=mt&&(this.retiredSdkAuthTokens.has(t)||this.retiredSdkAuthTokens.set(t,s))}}retiredSdkAuthUsers(){return Array.from(this.retiredSdkAuthTokens.keys())}forgetRetiredSdkAuthTokensExcept(t,i=Date.now()){const e=new Map;let s=null;return this.retiredSdkAuthTokens.forEach((n,r)=>{const o=i-n.at;o>mt?e.set(r,n.token):n.standby||t.has(r)||(6e4>o?s=Math.min(null!=s?s:1/0,6e4-o):e.set(r,n.token))}),e.forEach((t,i)=>this.retiredSdkAuthTokens.delete(i)),e.size&&this.saveRetiredTokens(e),s}saveRetiredTokens(t=new Map){if(this.retiredTokenStore)try{this.retiredTokenStore.update(i=>{const e={},s=Date.now();for(const n of Object.keys(i||{})){const r=bt(i[n],s);r&&s-r.at<=mt&&t.get(n)!==r.token&&(e[n]=r)}return this.retiredSdkAuthTokens.forEach((t,i)=>{const n=bt(e[i],s);if(!n||n.token===t.token)return void(e[i]=Object.assign({},t));const r=function(t,i){const e=wt(t),s=wt(i),n=t=>"number"==typeof t&&Number.isFinite(t)?t:null;for(const r of["exp","iat"]){const o=n(null==e?void 0:e[r]),h=n(null==s?void 0:s[r]);if(null!==o&&null!==h&&o!==h)return o>h?t:i}return null}(n.token,t.token);(r?r!==t.token:n.at>t.at)?this.retiredSdkAuthTokens.set(i,n):e[i]=Object.assign({},t)}),e})}catch(t){this.logger.warn("Could not store the SDK authentication tokens:",t)}}sdkAuthTokenFor(t){var i;const e=void 0===t?this.currentUserId:t;if(!e)return;const s=this.sdkAuthEnabled?this.sdkAuthToken:void 0,n=gt(s);return s&&n===e?s:!s||n||e!==this.currentUserId||null!==this.sdkAuthTokenUser&&this.sdkAuthTokenUser!==e?null===(i=this.retiredSdkAuthTokens.get(e))||void 0===i?void 0:i.token:s}getCurrentUserId(){return this.currentUserId}setSdkAuthenticationFailureCallback(t){this.sdkAuthFailureCallback=t}setCurrentUserId(t){this.currentUserId=t,this.adoptStandbyToken(t)}isSuspended(){return this.suspended}noteSuspended(t,i){return 402===t&&(this.suspended||(this.suspended=!0,console.warn(`[Joryio SDK] The API refused this request with 402 ${(null==i?void 0:i.code)||""} - event ingestion is paused for this workspace. Nothing more will be sent this page view; queued events are kept.`)),!0)}getSdkAuthHeaders(t,i){var e;const s=null!==(e=this.sdkAuthTokenFor(t))&&void 0!==e?e:this.storefrontTokenFor(t,i);return s?{[vt]:s}:{}}keepaliveBudget(){return Math.max(0,61440-this.keepaliveBytesInFlight)}isSdkAuthError(t,i){return 401===t&&!!i&&"object"==typeof i&&"sdk_authentication_error"===i.error}async refreshSdkAuthToken(t){if(!this.sdkAuthEnabled||!this.sdkAuthFailureCallback)return;const i=this.sdkAuthToken;let e;try{e=await Promise.resolve(this.sdkAuthFailureCallback(t))}catch(t){return void this.logger.error("SDK authentication failure callback threw:",t)}"string"==typeof e&&e&&this.setSdkAuthenticationToken(e);const s=this.sdkAuthToken;return s&&s!==i?s:void 0}async request(t){var i,e;if(this.suspended&&!kt(t.url,t.body))return{ok:!1,status:402,error:"Ingestion suspended",data:{code:"SDK_INGESTION_SUSPENDED"}};if("open"===this.circuitState){const t=Date.now()-this.circuitOpenedAt;if(t<this.circuitBreakerConfig.cooldownMs)return this.logger.warn(`Circuit breaker OPEN – failing fast (${Math.round((this.circuitBreakerConfig.cooldownMs-t)/1e3)}s remaining)`),{ok:!1,status:0,error:"Circuit breaker is open – API requests are temporarily blocked"};this.circuitState="half-open",this.logger.info("Circuit breaker transitioning to HALF-OPEN – allowing probe request")}const{url:s,method:n="POST",headers:r={}}=t;let o;try{o=t.body?JSON.stringify(t.body):void 0}catch(t){return this.logger.error(`Request to ${s} not sent: its body cannot be serialized`,t),{ok:!1,status:400,error:"The request body cannot be serialized"}}const h=void 0===t.subjectUserId||(t.subjectUserId||null)===this.currentUserId,a=t.body?Ot(t.body):void 0;let l,u,c=null,d=0,f=0,p=!1,y=!1;for(;f<=this.retryConfig.maxRetries;){try{this.logger.debug(`Request attempt ${f+1}/${this.retryConfig.maxRetries+1}: ${n} ${s}`);let{response:v,responseData:m}=await this.performFetch(s,n,r,o,t.subjectUserId,a);if(!y&&this.isStorefrontIdentityError(v.status,m)&&(y=!0,await this.handleStorefrontIdentityError(m)&&({response:v,responseData:m}=await this.performFetch(s,n,r,o,t.subjectUserId,a))),!p&&this.sdkAuthEnabled&&h&&this.isSdkAuthError(v.status,m)&&(p=!0,this.logger.warn(`SDK authentication rejected (${(null==m?void 0:m.reason)||"invalid"}) on ${s} – refreshing token`),await this.refreshSdkAuthToken({reason:(null==m?void 0:m.reason)||(this.sdkAuthToken?"invalid":"missing"),endpoint:s,userId:void 0===t.subjectUserId?this.currentUserId:t.subjectUserId||null})&&(this.logger.debug("SDK authentication token refreshed – retrying request once"),({response:v,responseData:m}=await this.performFetch(s,n,r,o,t.subjectUserId,a)))),v.ok)return this.onRequestSuccess(),dt(m)?(this.logger.warn(`Request to ${s} answered ${v.status} with success: false`),{ok:!1,status:v.status,data:m,error:(null==m?void 0:m.error)||(null==m?void 0:m.message)||"The server reported success: false",softFailure:!0}):(this.logger.debug("Request successful: "+v.status),{ok:!0,status:v.status,data:m});if(!this.shouldRetry(v.status))return this.logger.warn("Request failed with non-retryable status: "+v.status),this.noteSuspended(v.status,m),{ok:!1,status:v.status,error:(null==m?void 0:m.message)||v.statusText,data:m};d=v.status,l=m,u=yt(null===(e=null===(i=v.headers)||void 0===i?void 0:i.get)||void 0===e?void 0:e.call(i,"retry-after")),c=Error(`HTTP ${v.status}: ${v.statusText}`),this.logger.warn(`Request failed (attempt ${f+1}): ${c.message}`)}catch(t){c=t,d=0,l=void 0,u=void 0,this.logger.error(`Request error (attempt ${f+1}):`,t)}if(f<this.retryConfig.maxRetries){const t=Math.max(this.calculateBackoff(f),Math.min(null!=u?u:0,3e4));this.logger.debug(`Retrying in ${t}ms...`),await this.sleep(t)}f++}return this.onRequestFailure(),this.logger.error(`Request failed after ${this.retryConfig.maxRetries+1} attempts`),Object.assign({ok:!1,status:d,data:l,error:(null==c?void 0:c.message)||"Network request failed"},void 0!==u?{retryAfterMs:u}:{})}onRequestSuccess(){(this.consecutiveFailures>0||"closed"!==this.circuitState)&&this.logger.info(`Circuit breaker CLOSED – request succeeded after ${this.consecutiveFailures} consecutive failure(s)`),this.consecutiveFailures=0,this.circuitState="closed",this.circuitOpenedAt=0}onRequestFailure(){if(this.consecutiveFailures++,"half-open"===this.circuitState)return this.circuitState="open",this.circuitOpenedAt=Date.now(),void this.logger.warn(`Circuit breaker re-OPENED – probe request failed (${this.consecutiveFailures} consecutive failures)`);this.consecutiveFailures<this.circuitBreakerConfig.failureThreshold||(this.circuitState="open",this.circuitOpenedAt=Date.now(),this.logger.warn(`Circuit breaker OPENED – ${this.consecutiveFailures} consecutive failures reached threshold of ${this.circuitBreakerConfig.failureThreshold}`))}getCircuitBreakerState(){return{state:this.circuitState,consecutiveFailures:this.consecutiveFailures,openedAt:this.circuitOpenedAt}}async performFetch(t,i,e,s,n,r){var h;const a=new AbortController,l=setTimeout(()=>a.abort(),this.retryConfig.timeoutMs||1e4),u=Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},e),o()),c=null!==(h=this.sdkAuthTokenFor(n))&&void 0!==h?h:this.storefrontTokenFor(n,r);let d;c&&(u[vt]=c);try{d=await fetch(t,{method:i,headers:u,body:s,signal:a.signal,credentials:"omit"})}finally{clearTimeout(l)}return{response:d,responseData:await this.parseResponse(d)}}async parseResponse(t){var i,e;const s=null===(e=null===(i=t.headers)||void 0===i?void 0:i.get)||void 0===e?void 0:e.call(i,"content-type");if(s&&s.includes("application/json"))try{return await t.json()}catch(t){return this.logger.warn("Failed to parse JSON response"),null}return await t.text()}shouldRetry(t){return 408===t||429===t||t>=500}calculateBackoff(t){const{backoffMs:i,maxBackoffMs:e=3e4}=this.retryConfig,s=Math.min(i*Math.pow(2,t),e),n=.25*s*(2*Math.random()-1);return Math.max(0,Math.floor(s+n))}sleep(t){return new Promise(i=>setTimeout(i,t))}async sendEvents(t,i,e){var s;const n={events:i};return e&&(n.identify=ft(e)),this.request({url:t+"/v1/track/batch",method:"POST",body:n,subjectUserId:(null==e?void 0:e.userId)||(null===(s=i.find(t=>t&&t.userId))||void 0===s?void 0:s.userId)||null})}supportsKeepalive(){try{return"function"==typeof fetch&&"undefined"!=typeof Request&&"keepalive"in Request.prototype}catch(t){return!1}}sendEventsKeepalive(t,i,e){const s={events:i};return e&&(s.identify=ft(e)),this.postKeepalive(t+"/v1/track/batch",s)}postKeepalive(t,i){var e;if(this.suspended&&!kt(t,i)||!this.supportsKeepalive())return null;let s;try{s=JSON.stringify(i)}catch(t){return null}const n=pt(s)+256;if(this.keepaliveBytesInFlight+n>61440)return null;const r=Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),h=St(i),a=null!==(e=this.sdkAuthTokenFor(h))&&void 0!==e?e:this.storefrontTokenFor(h,Ot(i));a&&(r[vt]=a);try{this.keepaliveBytesInFlight+=n;let i=!1;const e=()=>{i||(i=!0,this.keepaliveBytesInFlight=Math.max(0,this.keepaliveBytesInFlight-n))};return fetch(t,{method:"POST",headers:r,body:s,keepalive:!0,credentials:"omit"}).then(async t=>{e();const i=await this.parseResponse(t).catch(()=>null),s=t.ok&&dt(i);return Object.assign({ok:t.ok&&!s,status:t.status,data:i},s?{softFailure:!0}:{})},t=>(e(),{ok:!1,status:0,error:((null==t?void 0:t.message)||t)+""}))}catch(t){return this.keepaliveBytesInFlight=Math.max(0,this.keepaliveBytesInFlight-n),this.logger.warn("keepalive request could not be started:",t),null}}async sendIdentify(t,i,e,s){return this.request({url:t+"/v1/identify",method:"POST",body:{userId:i,attributes:e,anonymousId:s},subjectUserId:i})}async sendIdentifyLink(t,i){return this.request({url:t+"/v1/identify-link",method:"POST",body:{token:i.token,anonymousId:i.anonymousId},subjectUserId:null})}hasStorefrontIdentity(){const t=this.storefrontToken;if(!t)return!1;const i=jt(t),e=this.anonymousIdSource?this.anonymousIdSource():null;return!!i&&!!e&&i.vid===e}async sendAddAlias(t,i){return this.request({url:t+"/v1/alias/add",method:"POST",body:i,subjectUserId:i.userId||null})}async sendDeviceSession(t,i){return this.request({url:t+"/v1/device/session",method:"POST",body:i})}async sendSetAttributes(t,i,e,s){return this.request({url:t+"/v1/attributes",method:"POST",body:Object.assign({userId:e||void 0,anonymousId:e?void 0:s},i),subjectUserId:e||null})}async sendSubscriptionUpdate(t,i){return this.request({url:t+"/v1/subscriptions/channel",method:"POST",body:i,subjectUserId:i.userId||null})}async sendSubscriptionGroupUpdate(t,i){return this.request({url:t+"/v1/subscriptions/group",method:"POST",body:i,subjectUserId:i.userId||null})}}const _t="event_queue",Tt="event_queue_inflight",$t="pending_identify",Dt=921600,Ct=3e5;function Pt(t,i){return i.every(i=>i.anonymousId===t.anonymousId&&(!i.userId||i.userId===t.userId))}class Mt{constructor(t,i,e,s,n=!0,r=1e3,o=1e3){if(this.queue=[],this.flushTimer=null,this.flushCallback=null,this.pendingPersist=!1,this.persistTimer=null,this.isFlushing=!1,this.flushWaiters=[],this.pendingIdentifies=[],this.inflightEvents=[],this.paused=!1,this.suspended=!1,this.consecutiveFailures=0,this.nextAttemptAt=0,this.retryAfterUntil=0,this.generation=0,this.clearedInflightCallback=null,this.storage=t,this.logger=i,this.batchSize=e>0?Math.floor(e):50,this.flushInterval=s,this.persistQueue=n,this.maxQueueSize=r>0?Math.floor(r):1e3,this.retryBackoffMs=o>0?o:1e3,this.persistQueue){const t=this.storage.get(Tt)||[],i=this.storage.get(_t)||[];this.queue=[...t,...i],t.length>0&&(this.storage.remove(Tt),this.logger.debug(`Recovered ${t.length} in-flight events from previous page`)),this.queue.length>this.maxQueueSize&&(this.queue=this.queue.slice(-this.maxQueueSize)),this.queue.length>0&&(this.logger.debug(`Loaded ${this.queue.length} events from storage`),this.persistQueueToStorage());const e=this.storage.get($t),s=Array.isArray(e)?e:e?[e]:[];this.pendingIdentifies=s.filter(t=>t&&"string"==typeof t.userId&&"string"==typeof t.anonymousId).slice(-20),this.pendingIdentifies.length&&this.logger.debug(`Recovered ${this.pendingIdentifies.length} pending identify(s) from a previous page`)}}setFlushCallback(t){this.flushCallback=t}setPaused(t){this.paused=t}isPaused(){return this.paused}isSuspended(){return this.suspended}isBackingOff(){return this.consecutiveFailures>0||Date.now()<this.retryAfterUntil}resetBackoff(){this.consecutiveFailures=0,this.nextAttemptAt=0}setPendingIdentify(t){const i=this.pendingIdentifies[this.pendingIdentifies.length-1],e={userId:t.userId,anonymousId:t.anonymousId,attributes:t.attributes||{}};if(!i||i.userId!==e.userId||i.anonymousId!==e.anonymousId){if(this.pendingIdentifies.push(e),this.pendingIdentifies.length>20){const t=this.pendingIdentifies.shift();this.logger.warn(`Too many identify calls waiting to be sent; dropped the oldest (${t.userId})`)}this.persistIdentifies()}}persistIdentifies(){if(this.persistQueue)try{this.pendingIdentifies.length?this.storage.set($t,this.pendingIdentifies):this.storage.remove($t)}catch(t){this.logger.error("Failed to persist pending identify:",t)}}getPendingIdentify(){return this.pendingIdentifies[0]||null}getPendingIdentifies(){return[...this.pendingIdentifies]}removeIdentify(t){const i=this.pendingIdentifies.indexOf(t);0>i||this.pendingIdentifies.splice(i,1),this.persistIdentifies()}identifyAttemptFailed(t,i){i?(t.attempts=(t.attempts||0)+1,10>t.attempts?this.persistIdentifies():(this.logger.error(`Identify for ${t.userId} failed ${t.attempts} times; dropping it`),this.removeIdentify(t))):this.persistIdentifies()}start(){this.flushTimer?this.logger.debug("Queue manager already started"):(this.flushTimer=setInterval(()=>{this.flush().catch(t=>this.logger.error("Scheduled flush failed:",t))},this.flushInterval),this.logger.debug(`Queue manager started (batch: ${this.batchSize}, interval: ${this.flushInterval}ms)`),(this.queue.length>0||this.pendingIdentifies.length)&&this.flush().catch(t=>this.logger.error("Startup flush failed:",t)))}isStarted(){return null!==this.flushTimer}stop(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null,this.logger.debug("Queue manager stopped")),this.persistNow()}enqueue(t){this.queue.push(t),this.logger.debug(`Event queued: ${t.type} (queue size: ${this.queue.length})`),this.schedulePersist(),this.trimToMax(),this.queue.length<this.batchSize||this.isFlushing||(this.logger.debug("Batch size reached, flushing queue"),this.flush())}trimToMax(){if(this.queue.length>this.maxQueueSize){const t=this.queue.length-this.maxQueueSize;this.queue=this.queue.slice(-this.maxQueueSize),this.logger.warn(`Queue exceeded max size (${this.maxQueueSize}), dropped ${t} oldest event(s)`),this.schedulePersist()}}takeBatch(){const t=Math.min(this.batchSize,500),i=[];let e=64,s=null;for(;this.queue.length>0&&i.length<t;){const t=this.queue[0];if(i.length>0){if(t.anonymousId!==i[0].anonymousId)break;if(t.userId&&s&&t.userId!==s)break}let n;try{n=pt(JSON.stringify(t))+1}catch(t){n=1/0}if(n>Dt)this.queue.shift(),this.logger.error(`Dropping event "${t.type}": it is too large to send (${n} bytes)`);else{if(i.length>0&&e+n>Dt)break;i.push(this.queue.shift()),t.userId&&(s=t.userId),e+=n}}return i}restoreToFront(t){if(!t.length)return;const i=new Set(this.queue.map(t=>t.eventId)),e=t.filter(t=>!i.has(t.eventId));this.queue.unshift(...e),this.trimToMax()}backOff(t){this.consecutiveFailures++;const i=Math.min(this.retryBackoffMs*Math.pow(2,Math.min(this.consecutiveFailures-1,20)),Ct),e=.2*i*Math.random(),s=Math.max(i+e,Math.min(null!=t?t:0,Ct));this.nextAttemptAt=Date.now()+s,t&&t>0&&(this.retryAfterUntil=Date.now()+Math.min(t,Ct)),this.logger.debug(`Event send failed; next attempt in ${Math.round(s)}ms`)}async sendBatch(t,i,e=[]){let s;this.inflightEvents=e.length?[...t,...e]:t,this.persistQueue&&(this.persistQueueToStorage(),this.persistInflightToStorage());try{s=await this.flushCallback(t,null!=i?i:void 0)||{status:"ok"}}catch(t){this.logger.error("Failed to flush events:",t),s={status:"retry"}}return this.inflightEvents=[],this.persistQueue&&this.storage.remove(Tt),s}async flush(t=!1,i=!1){var e,s;if(0===this.queue.length&&!this.pendingIdentifies.length&&!this.isFlushing)return;if(this.paused||this.suspended){if(t)throw Error(this.paused?"Sending is paused":"Sending is suspended");return}if(this.isFlushing)return await new Promise(t=>this.flushWaiters.push(t)),this.queue.length>0||this.pendingIdentifies.length?this.flush(t,i):void 0;const n=Date.now();if(n<this.retryAfterUntil||!i&&n<this.nextAttemptAt||"undefined"!=typeof navigator&&!1===navigator.onLine){if(t)throw Error("Waiting to retry");return}if(!this.flushCallback)return void this.logger.warn("No flush callback set, cannot flush queue");this.isFlushing=!0;let r=null;const o=this.generation;try{let t=null;const i=[];let n=this.queue.length;const h=new Set;for(;;){let a;i.length>0?a=i.shift():n>0?(a=this.takeBatch(),n-=a.length,0===a.length&&(n=0)):a=this.pendingIdentifies[0]&&!h.has(this.pendingIdentifies[0])&&this.pendingIdentifies[0]!==t&&this.queue.length>0&&Pt(this.pendingIdentifies[0],[this.queue[0]])?this.takeBatch():[];const l=this.pendingIdentifies[0]||null;let u=null;if(l&&!h.has(l)&&(0===a.length||l!==t&&Pt(l,a))&&(u=l),0===a.length&&!u)break;0===a.length&&u&&h.add(u),this.logger.debug(`Flushing ${a.length} events${u?" + identify":""}`);const c=await this.sendBatch(a,u,i.flat());if(this.generation!==o){if(this.logger.debug("Queue cleared during a flush; the in-flight batch is not restored"),this.clearedInflightCallback){let t=[];if("ok"===c.status){const i=new Set([...c.failedIndices||[],...c.rejectedIndices||[]]);t=a.filter((t,e)=>!i.has(e))}try{this.clearedInflightCallback(t)}catch(t){this.logger.warn("Cleared in-flight callback failed:",t)}}break}if("dropped"!==c.status){if("ok"===c.status){const t=t=>new Set((t||[]).filter(t=>Number.isInteger(t)&&t>=0&&t<a.length)),e=t(c.rejectedIndices);for(const t of e)this.logger.error(`Event "${a[t].type}" was refused by the server for good and has been dropped`);const s=[...t(c.failedIndices)].filter(t=>!e.has(t)).map(t=>a[t]);if(u&&c.identifyDropped&&(this.logger.error(`Identify for ${u.userId} was refused by the server; dropping it`),this.removeIdentify(u),u=null),u&&c.identifyFailed){this.identifyAttemptFailed(u,!1!==c.identifyAttemptCounts),this.restoreToFront([...s,...i.flat()]),this.backOff(),r="The identify was not confirmed";break}if(u&&this.removeIdentify(u),this.consecutiveFailures=0,this.nextAttemptAt=0,s.length>0){this.logger.warn(`${s.length} of ${a.length} events were not stored by the server; will retry them`),this.restoreToFront([...s,...i.flat()]),this.backOff(),r="Some events were not stored";break}continue}if("rejected"!==c.status){this.restoreToFront([...a,...i.flat()]),u&&"retry"===c.status&&this.identifyAttemptFailed(u,!0===c.counts),"suspended"===c.status?(this.suspended||(this.suspended=!0,console.warn(`[Joryio SDK] Event sending stopped for this page view (${c.reason||"refused"}). `+this.queue.length+" queued event(s) are kept.")),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),r="Sending is suspended"):(this.backOff(c.retryAfterMs),r="Events could not be delivered; will retry");break}if(u){if(0===a.length){this.logger.error(`Identify for ${u.userId} was refused by the server (HTTP ${null!==(e=c.httpStatus)&&void 0!==e?e:"4xx"}); dropping it`),this.removeIdentify(u);continue}t=u,i.unshift(a);continue}if(a.length>1){const t=Math.ceil(a.length/2);i.unshift(a.slice(0,t),a.slice(t));continue}1===a.length&&this.logger.error(`Event "${a[0].type}" was refused by the server (HTTP ${null!==(s=c.httpStatus)&&void 0!==s?s:"4xx"}) and has been dropped`)}else this.logger.error(`${a.length} event(s)${u?" and an identify":""} of a user who is no longer signed in were refused by SDK authentication (${c.reason||"401"}) and have been dropped`),u&&this.removeIdentify(u)}this.persistQueue&&this.persistQueueToStorage()}finally{this.isFlushing=!1;const t=this.flushWaiters;this.flushWaiters=[],t.forEach(t=>t())}if(r&&t)throw Error(r)}persistQueueToStorage(){this.pendingPersist=!1,null!==this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null);try{this.storage.set(_t,this.queue)}catch(t){this.logger.error("Failed to persist queue to storage:",t)}}schedulePersist(){this.persistQueue&&!this.pendingPersist&&(this.pendingPersist=!0,this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.pendingPersist&&this.persistQueueToStorage()},150))}persistNow(){this.persistQueue&&this.pendingPersist&&this.persistQueueToStorage()}persistInflightToStorage(){try{this.inflightEvents.length>0?this.storage.set(Tt,this.inflightEvents):this.storage.remove(Tt)}catch(t){this.logger.error("Failed to persist in-flight events to storage:",t)}}getQueueSize(){return this.queue.length}getQueuedEvents(){return[...this.inflightEvents,...this.queue]}getWaitingEvents(){return[...this.queue]}getInflightEvents(){return[...this.inflightEvents]}setClearedInflightCallback(t){this.clearedInflightCallback=t}markHandedOff(t,i){const e=new Set(t.map(t=>t.eventId));this.queue=this.queue.filter(t=>!e.has(t.eventId)),this.inflightEvents=this.inflightEvents.filter(t=>!e.has(t.eventId)),i&&this.removeIdentify(i),this.persistQueue&&(this.persistQueueToStorage(),this.persistInflightToStorage())}takeBack(t,i){this.restoreToFront(t),i&&!this.pendingIdentifies.includes(i)&&(this.pendingIdentifies.unshift(i),this.persistIdentifies()),this.persistQueue&&this.persistQueueToStorage()}clear(){this.generation++,this.queue=[],this.inflightEvents=[],this.persistQueue&&(this.storage.remove(_t),this.storage.remove(Tt),this.storage.remove($t)),this.pendingIdentifies=[],this.logger.debug("Queue cleared")}async destroy(){this.stop(),this.queue.length>0&&(this.logger.debug("Flushing remaining events before destroy"),await this.flush())}}const xt="first_touch_utm",Kt="last_touch_utm",Nt="session_utm",Ft="session_referrer",Et="session_landing_page";class Ut{constructor(t,i,e=!1){this.newCampaignDetected=!1,this.storage=t,this.logger=i,this.resetSessionOnNewCampaign=e,this.resetSessionOnNewCampaign&&(this.newCampaignDetected=this.detectNewCampaign()),this.captureUTMParameters()}captureUTMParameters(){if("undefined"==typeof window)return;const t=new URLSearchParams(window.location.search),i={};let e=!1;const s=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"];for(const n of s){const s=t.get(n);s&&(i[n]=s,e=!0)}document.referrer&&(i.referrer=document.referrer),i.landing_page=window.location.href,i.captured_at=Date.now(),e?(this.logger.debug("Captured UTM parameters:",i),this.storage.set(Nt,i),this.storage.set(Ft,i.referrer||null),this.storage.set(Et,i.landing_page),this.storage.get(xt)||(this.storage.set(xt,i),this.logger.debug("Set first touch UTM:",i)),this.storage.set(Kt,i),this.logger.debug("Updated last touch UTM:",i)):this.storage.get(Nt)||(this.storage.set(Nt,i),this.storage.set(Ft,i.referrer||null),this.storage.set(Et,i.landing_page),this.logger.debug("Captured session referrer and landing page"))}getUTMData(){return{current:this.storage.get(Nt)||null,firstTouch:this.storage.get(xt)||null,lastTouch:this.storage.get(Kt)||null}}getCurrentUTM(){return this.storage.get(Nt)||null}getFirstTouchUTM(){return this.storage.get(xt)||null}getLastTouchUTM(){return this.storage.get(Kt)||null}getSessionReferrer(){return this.storage.get(Ft)||null}getSessionLandingPage(){return this.storage.get(Et)||null}hasNewCampaign(){return this.newCampaignDetected}detectNewCampaign(){if("undefined"==typeof window)return!1;const t=new URLSearchParams(window.location.search),i=this.getCurrentUTM();if(!i)return t.has("utm_source")||t.has("utm_medium")||t.has("utm_campaign");const e=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"];for(const s of e){const e=t.get(s),n=i[s];if(e&&e!==n)return!0}return!1}updateUTM(){this.resetSessionOnNewCampaign&&(this.newCampaignDetected=this.detectNewCampaign()),this.captureUTMParameters()}clearSessionUTM(){this.storage.remove(Nt),this.storage.remove(Ft),this.storage.remove(Et),this.logger.debug("Cleared session UTM")}clearAllUTM(){this.storage.remove(Nt),this.storage.remove(xt),this.storage.remove(Kt),this.storage.remove(Ft),this.storage.remove(Et),this.logger.debug("Cleared all UTM data")}reset(){this.clearAllUTM()}getUTMProperties(){const t=this.getCurrentUTM(),i=this.getFirstTouchUTM(),e=this.getLastTouchUTM(),s={};return t&&(t.utm_source&&(s.utm_source=t.utm_source),t.utm_medium&&(s.utm_medium=t.utm_medium),t.utm_campaign&&(s.utm_campaign=t.utm_campaign),t.utm_content&&(s.utm_content=t.utm_content),t.utm_term&&(s.utm_term=t.utm_term),t.referrer&&(s.referrer=t.referrer),t.landing_page&&(s.landing_page=t.landing_page)),i&&(i.utm_source&&(s.first_touch_utm_source=i.utm_source),i.utm_medium&&(s.first_touch_utm_medium=i.utm_medium),i.utm_campaign&&(s.first_touch_utm_campaign=i.utm_campaign),i.utm_content&&(s.first_touch_utm_content=i.utm_content),i.utm_term&&(s.first_touch_utm_term=i.utm_term),i.referrer&&(s.first_touch_referrer=i.referrer),i.landing_page&&(s.first_touch_landing_page=i.landing_page),i.captured_at&&(s.first_touch_captured_at=new Date(i.captured_at).toISOString())),e&&e!==t&&(e.utm_source&&(s.last_touch_utm_source=e.utm_source),e.utm_medium&&(s.last_touch_utm_medium=e.utm_medium),e.utm_campaign&&(s.last_touch_utm_campaign=e.utm_campaign),e.utm_content&&(s.last_touch_utm_content=e.utm_content),e.utm_term&&(s.last_touch_utm_term=e.utm_term),e.referrer&&(s.last_touch_referrer=e.referrer),e.landing_page&&(s.last_touch_landing_page=e.landing_page),e.captured_at&&(s.last_touch_captured_at=new Date(e.captured_at).toISOString())),s}}const qt={modal:600,slideup:400};function zt(t,i,e=16){const s=Math.max(0,Math.floor(i)-2*e);return Math.max(0,Math.min(Math.floor(t),s))}const Jt="__joryioInApp",Rt="inapp_impressions",Lt=1e3,Ht=new Set(["close_button","backdrop","button","bridge_close"]);function Bt(t,i){var e,s;const n=t=>t.split(",").map(t=>{const e=t.trim();return e?/^(?:html|body|:root)$/i.test(e)?i:`${i} ${e}`:""}).filter(Boolean).join(", "),r=[];for(let o=0;o<t.length;o++){const h=t[o];if(void 0!==h.selectorText&&h.style){const t=n(h.selectorText);t&&r.push(`${t} { ${h.style.cssText} }`)}else if(h.cssRules&&void 0!==h.conditionText){const t=(null!==(e=h.cssText)&&void 0!==e?e:"").slice(0,(null!==(s=h.cssText)&&void 0!==s?s:"").indexOf("{")).trim(),n=Bt(h.cssRules,i);t&&n&&r.push(`${t} { ${n} }`)}else 7===h.type&&h.cssText&&r.push(h.cssText)}return r.join("\n")}const Vt=new Set(["click","clicked","button","link","cta_click","link_click","button_click"]);function Wt(t){if("string"!=typeof t)return;const i=t.trim();return i&&!Vt.has(i.toLowerCase())?i.slice(0,128):void 0}const Xt=new Set(["modal","banner","slideup","fullscreen"]);function Gt(t){if("string"!=typeof t)return null;const i=t.trim();return!i||i.length>100||/[;{}<>\\]/.test(i)?null:i}class Qt{capabilities(){const t=["content.native","placements","content.data"];return this.allowHtmlJsInAppMessages&&t.push("content.html"),this.page&&t.push(c),t}setPageContext(t){var i;null===(i=this.pageUnsubscribe)||void 0===i||i.call(this),this.pageUnsubscribe=null,this.page=t,t&&(this.pageUnsubscribe=t.onSignal(t=>this.onPageSignal(t)))}pageAllows(t){return!y(t.pageTargeting)||!!this.page&&function(t,i){var e,s,n,r,o;if(!y(t))return!0;const h=null!==(s=null===(e=t.urls)||void 0===e?void 0:e.include)&&void 0!==s?s:[],a=null!==(r=null===(n=t.urls)||void 0===n?void 0:n.exclude)&&void 0!==r?r:[];if(h.length||a.length){if(!i.url)return!1;if(h.length&&!h.some(t=>p(t,i.url)))return!1;if(a.some(t=>p(t,i.url)))return!1}return(null!==(o=t.variables)&&void 0!==o?o:[]).every(t=>function(t,i){var e,s,n,r,o,h,a;const l="data_layer"===t.source?i.dataLayer:"page"===t.source?i.pageVariables:"utm_session"===t.source?null!==(s=null===(e=i.utm)||void 0===e?void 0:e.session)&&void 0!==s?s:{}:"utm_first_touch"===t.source?null!==(r=null===(n=i.utm)||void 0===n?void 0:n.firstTouch)&&void 0!==r?r:{}:void 0;if(!l)return!1;const u=Object.prototype.hasOwnProperty.call(l,t.key),c=u?l[t.key]:void 0;switch(t.op){case"exists":return u;case"not_exists":return!u;case"equals":return u&&(c+"").toLowerCase()===((null!==(o=t.value)&&void 0!==o?o:"")+"").toLowerCase();case"not_equals":return!u||(c+"").toLowerCase()!==((null!==(h=t.value)&&void 0!==h?h:"")+"").toLowerCase();case"contains":return u&&(c+"").toLowerCase().includes(((null!==(a=t.value)&&void 0!==a?a:"")+"").toLowerCase());case"gt":case"lt":{const i=+c,e=+t.value;return!!(u&&Number.isFinite(i)&&Number.isFinite(e))&&("gt"===t.op?i>e:e>i)}default:return!1}}(t,i))}(t.pageTargeting,this.page.current())}onPageSignal(t){if(!this.page)return;"page_change"===t.type&&this.pageFired.clear();const i=this.page.progress();for(const e of this.campaigns.values()){const s=e.triggers||[],n=s.find(e=>v(e)&&k(e,t,i)),r="page_change"===t.type&&y(e.pageTargeting)&&s.some(t=>"immediate"===t.type);(n||r)&&(this.pageFired.has(e.id)||this.pageAllows(e)&&(this.pageFired.add(e.id),this.displayCampaign(e).catch(t=>this.logger.error("In-app display failed:",t))))}}callHost(t,i){try{i()}catch(i){this.logger.error(`The ${t} callback threw; ignored:`,i)}}invalidate(){this.generation++,this.isSyncing&&(this.syncAgain=!0)}setAllowHtmlJsInAppMessages(t){this.allowHtmlJsInAppMessages=t}constructor(t,i,e,s,n,r,o,h,a,l){this.links=null,this.pendingDelays=new Map,this.campaigns=new Map,this.displayedMessages=new Map,this.impressionTimestamps=new Map,this.watchedAttributes=new Set,this.displayOptions={},this.isSyncing=!1,this.syncRetried=!1,this.generation=0,this.syncAgain=!1,this.claimed=new Set,this.awaitingDwell=new Map,this.pageLeaving=!1,this.settleWaiters=new Set,this.pageListeners=[],this.iframes=new Map,this.frameMaxWidths=new Map,this.allowHtmlJsInAppMessages=!1,this.page=null,this.pageUnsubscribe=null,this.pageFired=new Set,this.bridge=null,this.auth=null,this.runtime={canSend:(null==l?void 0:l.canSend)||(()=>!0),requestTimeoutMs:(null==l?void 0:l.requestTimeoutMs)||1e4,syncIntervalMs:(null==l?void 0:l.syncIntervalMs)||0,evaluationMode:(null==l?void 0:l.evaluationMode)||"differential-sync",noteStatus:null==l?void 0:l.noteStatus},this.apiEndpoint=t,this.sdkKey=i,this.identity=e,this.session=s,this.logger=n,this.storage=r||null,this.displayOptions=o||{},this.bridge=h||null,this.auth=a||null,this.loadImpressionTimestamps(),this.installHostBridge(),this.installPageLifecycle()}pageHidden(){return"undefined"!=typeof document&&("hidden"===document.visibilityState||!0===document.hidden)}installPageLifecycle(){if("undefined"==typeof window||"function"!=typeof window.addEventListener)return;const t=(t,i,e)=>{t&&"function"==typeof t.addEventListener&&(t.addEventListener(i,e),this.pageListeners.push([t,i,e]))},i=()=>{this.pageLeaving=!0,this.pauseDwells(),this.settleWaiters.forEach(t=>t())},e=()=>{this.pageLeaving&&(this.pageLeaving=!1,this.resumeDwells())};t(window,"beforeunload",i),t(window,"pagehide",i),t(window,"pageshow",()=>{this.pageLeaving=!1,this.resumeDwells()}),t(window,"pointerdown",e),t(window,"keydown",e),"undefined"!=typeof document&&t(document,"visibilitychange",()=>{this.pageHidden()?this.pauseDwells():(this.pageLeaving=!1,this.resumeDwells())})}removePageLifecycle(){var t;for(const[i,e,s]of this.pageListeners)try{null===(t=i.removeEventListener)||void 0===t||t.call(i,e,s)}catch(t){}this.pageListeners=[]}whenPageSettled(){return"undefined"==typeof window||"undefined"==typeof document?Promise.resolve(!0):this.pageLeaving?Promise.resolve(!1):new Promise(t=>{let i,e,s=!1;const n=window,r=r=>{s||(s=!0,this.settleWaiters.delete(o),i&&clearTimeout(i),e&&clearTimeout(e),"function"==typeof n.removeEventListener&&n.removeEventListener("load",a),t(r&&!this.pageLeaving))},o=()=>r(!1),h=()=>{s||("function"==typeof n.requestIdleCallback?n.requestIdleCallback(()=>r(!0),{timeout:500}):e=setTimeout(()=>r(!0),50))},a=()=>{i&&clearTimeout(i),i=void 0,h()};this.settleWaiters.add(o);const l=document.readyState;l&&"complete"!==l&&"function"==typeof n.addEventListener?(n.addEventListener("load",a,{once:!0}),i=setTimeout(a,1e4)):h()})}isMounted(t){if(!this.displayedMessages.has(t)||"undefined"==typeof document)return!1;const i=document.getElementById("joryio-inapp-"+t);return!!i&&!1!==i.isConnected}scheduleDwell(t,i){const e=this.awaitingDwell.get(t);if((null==e?void 0:e.timer)&&clearTimeout(e.timer),this.pageLeaving||this.pageHidden())return void this.awaitingDwell.set(t,{timer:null,generation:i});const s=setTimeout(()=>{const i=this.awaitingDwell.get(t);i&&i.timer===s&&(i.timer=null,this.pageLeaving||this.pageHidden()||!this.isMounted(t)||i.generation===this.generation&&this.confirmDisplay(t).catch(()=>{}))},Lt);this.awaitingDwell.set(t,{timer:s,generation:i})}pauseDwells(){this.awaitingDwell.forEach(t=>{t.timer&&clearTimeout(t.timer),t.timer=null})}resumeDwells(){this.pageLeaving||this.pageHidden()||this.awaitingDwell.forEach((t,i)=>{!t.timer&&this.isMounted(i)&&this.scheduleDwell(i,t.generation)})}dropDwell(t){const i=this.awaitingDwell.get(t);(null==i?void 0:i.timer)&&clearTimeout(i.timer),this.awaitingDwell.delete(t)}confirmDisplay(t){if(!this.awaitingDwell.has(t))return Promise.resolve();this.dropDwell(t);const i=this.impressionTimestamps.get(t)||[];i.push(Date.now()),this.boundedMapSet(this.impressionTimestamps,t,i,500),this.persistImpressionTimestamps();const e=this.trackImpression(t,"displayed"),s=this.displayedMessages.get(t);return s&&this.callHost("onMessageDisplay",()=>{var t,i;return null===(i=(t=this.displayOptions).onDisplay)||void 0===i?void 0:i.call(t,s)}),e}loadImpressionTimestamps(){if(this.storage)try{const t=this.storage.get(Rt);if(t&&"object"==typeof t)for(const[i,e]of Object.entries(t))Array.isArray(e)&&this.impressionTimestamps.set(i,e.filter(t=>"number"==typeof t))}catch(t){this.logger.error("Failed to load persisted impression timestamps:",t)}}persistImpressionTimestamps(){if(this.storage)try{const t={};this.impressionTimestamps.forEach((i,e)=>{t[e]=i}),this.storage.set(Rt,t)}catch(t){this.logger.error("Failed to persist impression timestamps:",t)}}installHostBridge(){"undefined"!=typeof window&&(window[Jt]={logCustomEvent:(t,i,e)=>{var s;this.displayedMessages.has(t)&&i&&(null===(s=this.bridge)||void 0===s||s.logCustomEvent(i,e))},setCustomUserAttribute:(t,i,e)=>{var s;this.displayedMessages.has(t)&&i&&(null===(s=this.bridge)||void 0===s||s.setCustomUserAttribute(i,e))},changeUser:(t,i)=>{var e;this.displayedMessages.has(t)&&i&&(null===(e=this.bridge)||void 0===e||e.changeUser(i))},requestPushPermission:t=>{var i;this.displayedMessages.has(t)&&(null===(i=this.bridge)||void 0===i||i.requestPushPermission())},logConversion:(t,i)=>{this.displayedMessages.has(t)&&i&&this.trackConversion(t,i).catch(()=>{})},logClick:(t,i)=>{if(!this.displayedMessages.has(t))return;const e=Wt(i);this.trackImpression(t,"clicked",e?{elementId:e}:void 0).catch(()=>{});const s=this.displayedMessages.get(t);s&&this.callHost("onMessageClick",()=>{var t,e;return null===(e=(t=this.displayOptions).onClick)||void 0===e?void 0:e.call(t,s,i||"click")})},navigate:(t,i,e)=>{if(!this.displayedMessages.has(t)||"string"!=typeof i)return;if(!/^(https?:\/\/|\/(?!\/))/i.test(i))return;const s=()=>{"_top"===e||"_self"===e?window.top&&(window.top.location.href=i):window.open(i,"_blank","noopener")};if(!this.links)return s();let n=i;try{n=new URL(i,window.location.href).href}catch(t){}this.links.route(n,"in_app",{campaignId:t},s)},closeMessage:t=>{this.displayedMessages.has(t)&&this.dismiss(t,"bridge_close").catch(()=>{})},submitForm:(t,i)=>this.displayedMessages.has(t)&&i&&"object"==typeof i?(this.trackImpression(t,"clicked").catch(()=>{}),this.submitForm(t,i)):Promise.resolve({ok:!1,message:"This message is no longer open."}),setSize:(t,i,e)=>{var s;const n=this.iframes.get(t);if(!n||!Number.isFinite(e)||0>=e)return;const r=null===(s=this.displayedMessages.get(t))||void 0===s?void 0:s.campaign.type;n.style.height="fullscreen"===r?"100%":Math.ceil(e)+"px"}})}async initialize(){this.runtime.canSend()&&(this.logger.info("Initializing in-app messaging"),this.stop(),await this.sync().catch(t=>{this.logger.error("Initial in-app sync failed:",t)}),this.startAttributeWatching(),this.startPeriodicSync())}stop(){this.syncInterval&&(clearInterval(this.syncInterval),this.syncInterval=void 0),this.periodicSyncTimer&&(clearInterval(this.periodicSyncTimer),this.periodicSyncTimer=void 0),this.syncRetryTimer&&(clearTimeout(this.syncRetryTimer),this.syncRetryTimer=void 0),this.syncRetried=!1,this.pendingDelays.forEach(t=>clearTimeout(t)),this.pendingDelays.clear(),this.settleWaiters.forEach(t=>t())}startPeriodicSync(){this.periodicSyncTimer&&(clearInterval(this.periodicSyncTimer),this.periodicSyncTimer=void 0),"differential-sync"===this.runtime.evaluationMode&&this.runtime.syncIntervalMs>0&&(this.periodicSyncTimer=setInterval(()=>{"undefined"!=typeof document&&document.hidden||this.runtime.canSend()&&this.sync().catch(t=>this.logger.debug("Periodic in-app sync failed:",t))},this.runtime.syncIntervalMs))}subject(){const t=this.identity.getUserId();return Object.assign(Object.assign({},t?{userId:t}:{}),{anonymousId:this.identity.getAnonymousId()})}async maybeHandleSdkAuthError(t,i,e){var s,n,r,o;if(!this.auth||401!==t.status)return;if((e||null)!==((this.auth.getCurrentUserId?this.auth.getCurrentUserId():this.identity.getUserId())||null))return;let h=null;try{h=await t.clone().json()}catch(t){return}if(null===(n=(s=this.auth).isStorefrontIdentityError)||void 0===n?void 0:n.call(s,t.status,h))await(null===(o=(r=this.auth).handleStorefrontIdentityError)||void 0===o?void 0:o.call(r,h).catch(()=>!1));else if(this.auth.isSdkAuthError(t.status,h)){this.logger.warn(`In-app request rejected by SDK authentication (${(null==h?void 0:h.reason)||"invalid"}) on ${i} – refreshing token`);try{await this.auth.refreshSdkAuthToken({reason:(null==h?void 0:h.reason)||"invalid",endpoint:i,userId:e})}catch(t){this.logger.error("Failed to refresh SDK authentication token for in-app request:",t)}}}async sync(t){var i,e,s;if(!this.runtime.canSend())return{success:!1,campaigns:[],evaluatedAt:(new Date).toISOString()};if(this.isSyncing)return this.syncAgain=!0,t&&(this.syncAgainChanges=Object.assign(Object.assign({},this.syncAgainChanges||{}),t)),{success:!1,campaigns:[],evaluatedAt:(new Date).toISOString()};this.isSyncing=!0;const n=this.generation;this.logger.debug("Syncing in-app campaigns");const r=this.session.getSessionId(),h=this.identity.getAttributes(),a=new AbortController,l=this.runtime.requestTimeoutMs,u=setTimeout(()=>a.abort(),l),c=this.identity.getUserId();try{const l=await fetch(this.apiEndpoint+"/v1/in-app/sync",{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(i=this.auth)||void 0===i?void 0:i.getSdkAuthHeaders(c,c?null:this.identity.getAnonymousId()))||{}),body:JSON.stringify(Object.assign(Object.assign({},this.subject()),{sessionId:r,userAttributes:t||h,pendingAttributes:this.identity.pending.pending(this.identity.getAnonymousId()),deviceType:"web",locale:navigator.language,capabilities:this.capabilities()})),signal:a.signal});if(!l.ok)throw null===(s=(e=this.runtime).noteStatus)||void 0===s||s.call(e,l.status,null),await this.maybeHandleSdkAuthError(l,this.apiEndpoint+"/v1/in-app/sync",c),Error(`Sync failed: ${l.status} ${l.statusText}`);const u=await l.json();if(n!==this.generation)return this.logger.debug("Discarding an in-app sync answer that predates an identity or consent change"),this.syncAgain=!0,{success:!1,campaigns:[],evaluatedAt:(new Date).toISOString()};if(!u||!1===u.success||!Array.isArray(u.campaigns))throw Error("Sync failed: the server reported success: false");this.syncRetried=!1,this.campaigns.clear();for(const t of u.campaigns)this.campaigns.set(t.id,t),"differential-sync"===t.evaluationMode&&t.watchedAttributes&&t.watchedAttributes.forEach(t=>this.boundedSetAdd(this.watchedAttributes,t,200));return this.logger.info(`Synced ${u.campaigns.length} eligible campaigns`),this.processImmediateTriggers(),u}catch(t){const i="AbortError"===(null==t?void 0:t.name);throw this.logger.error(i?`Campaign sync timed out after ${l}ms`:"Failed to sync campaigns:",t),n===this.generation&&!this.syncRetried&&this.runtime.canSend()&&(this.syncRetried=!0,this.syncRetryTimer=setTimeout(()=>{this.syncRetryTimer=void 0,this.sync().catch(()=>{})},5e3)),i?Error("Campaign sync timed out"):t}finally{if(clearTimeout(u),this.isSyncing=!1,this.syncAgain){this.syncAgain=!1;const t=this.syncAgainChanges;this.syncAgainChanges=void 0,this.runtime.canSend()&&this.sync(n!==this.generation?void 0:t).catch(t=>this.logger.debug("Follow-up in-app sync failed:",t))}}}processImmediateTriggers(){for(const t of this.campaigns.values())(t.triggers||[]).some(t=>"immediate"===t.type||"page_view"===t.type&&!!this.page)&&this.displayCampaign(t).catch(t=>this.logger.error("In-app display failed:",t))}onEventTracked(t,i){if(t)for(const e of this.campaigns.values())if((e.triggers||[]).find(e=>"event"===e.type&&e.event===t&&this.triggerFilterMatches(e,i)))return void this.displayCampaign(e).catch(t=>this.logger.error("In-app display failed:",t))}triggerFilterMatches(t,i){return Yt(t,i)}async resolveForDisplay(t){var i,e,s;if(!this.runtime.canSend())return null;const n=this.generation,r=new AbortController,h=setTimeout(()=>r.abort(),this.runtime.requestTimeoutMs);try{const h=await fetch(this.apiEndpoint+"/v1/in-app/resolve",{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(i=this.auth)||void 0===i?void 0:i.getSdkAuthHeaders(this.identity.getUserId(),this.identity.getUserId()?null:this.identity.getAnonymousId()))||{}),body:JSON.stringify(Object.assign(Object.assign(Object.assign({},this.subject()),{campaignId:t.id,sessionId:this.session.getSessionId(),userAttributes:this.identity.getAttributes(),pendingAttributes:this.identity.pending.pending(this.identity.getAnonymousId()),deviceType:"web",capabilities:this.capabilities()}),this.page?{context:this.page.current()}:{})),signal:r.signal});if(!h.ok)return null===(s=(e=this.runtime).noteStatus)||void 0===s||s.call(e,h.status,null),null;const a=await h.json();return n!==this.generation?null:(null==a?void 0:a.eligible)&&a.campaign?a.campaign:null}catch(t){return null}finally{clearTimeout(h)}}canPromptForPush(){try{return"undefined"!=typeof Notification&&"default"===Notification.permission}catch(t){return!1}}async displayCampaign(t){const i=t.id;if(!this.pageAllows(t))return void this.logger.debug(`Campaign ${i} not for this page`);if(this.claimed.has(i)||this.displayedMessages.has(i)||this.pendingDelays.has(i))return void this.logger.debug(`Campaign ${i} already displayed, scheduled or being prepared`);this.claimed.add(i);const e=this.generation;try{if(t.reevaluateBeforeDisplay){const i=await this.resolveForDisplay(t);if(!i)return void this.logger.info(`Campaign ${t.id} not displayed: re-check said no`);t=i}if(this.displayedMessages.has(t.id)||this.pendingDelays.has(t.id))return void this.logger.debug(`Campaign ${t.id} already displayed or scheduled`);if(!this.checkFrequencyCap(t))return void this.logger.debug(`Campaign ${t.id} blocked by frequency cap`);const s=await this.renderTemplate(t);if(e!==this.generation||!this.runtime.canSend())return void this.logger.debug(`Campaign ${t.id} not displayed: the visitor or consent changed meanwhile`);const n=this.undisplayableReason(t,s);if(n)return void this.logger.warn(`Campaign ${t.id} not displayed (${n}). No impression recorded and no frequency cap consumed, so it stays eligible.`);if(s.includes("requestPushPermission")&&!this.canPromptForPush())return void this.logger.debug(`Campaign ${t.id} is a push primer but the browser can't be prompted (permission not 'default'); suppressing.`);const r=()=>{const i={campaign:t,renderedHtml:s,displayedAt:new Date};this.boundedMapSet(this.displayedMessages,t.id,i,500),this.display(i),this.scheduleDwell(t.id,e)},o=async()=>{await this.whenPageSettled()?e===this.generation&&this.runtime.canSend()?!this.displayedMessages.has(t.id)&&this.checkFrequencyCap(t)&&r():this.logger.debug(`Campaign ${t.id} not displayed: the visitor or consent changed`):this.logger.debug(`Campaign ${t.id} not displayed: the page is unloading. It stays eligible.`)},h=1e3*Math.max(0,+t.delay||0);if(h>0){const e=setTimeout(()=>{this.pendingDelays.delete(t.id),this.claimed.has(i)||this.displayedMessages.has(i)||(this.claimed.add(i),o().catch(t=>this.logger.error("In-app display failed:",t)).finally(()=>this.claimed.delete(i)))},h);return void this.pendingDelays.set(t.id,e)}await o()}finally{this.claimed.delete(i)}}async renderTemplate(t){const i=t.content;return i&&"html"===i.kind?i.html:""}undisplayableReason(t,i){var e;const s=null===(e=t.content)||void 0===e?void 0:e.kind;return t.content?"native"===s?null:"html"===s?i.trim()?this.allowHtmlJsInAppMessages?null:"it is an HTML message and allowHtmlJsInAppMessages is false":"its `content.html` is empty":`this SDK cannot render content kind '${s+""}'`:"the payload carries no `content`"}display(t){var i,e,s,n,r,o,h;const{campaign:a,renderedHtml:l}=t,u=document.createElement("div");u.id="joryio-inapp-"+a.id;const c=Xt.has(a.type)?null:["top","center","bottom"].find(t=>t===this.displayOptions.defaultPosition)||"center",d=["fade","slide","none"].find(t=>t===this.displayOptions.defaultAnimation)||"fade";u.className="joryio-inapp joryio-inapp-"+a.type+(c?" joryio-inapp-pos-"+c:"")+("none"!==d?" joryio-inapp-anim-"+d:"");const f=document.createElement("style");f.id="joryio-style-"+a.id;const p=Number.isFinite(this.displayOptions.zIndex)?+this.displayOptions.zIndex:999999,y=Gt(this.displayOptions.backdropColor)||"rgba(0, 0, 0, 0.5)",v=Gt(this.displayOptions.closeButtonColor)||"inherit";f.textContent=`\n .joryio-inapp {\n position: fixed;\n z-index: ${p};\n }\n\n /* displayOptions.defaultPosition - only for types with no placement of their own. */\n .joryio-inapp-pos-top {\n top: 20px;\n left: 50%;\n transform: translateX(-50%);\n max-width: 90%;\n }\n .joryio-inapp-pos-center {\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n max-width: 90%;\n max-height: 90%;\n }\n .joryio-inapp-pos-bottom {\n bottom: 20px;\n left: 50%;\n transform: translateX(-50%);\n max-width: 90%;\n }\n\n /* displayOptions.defaultAnimation. The individual \`translate\` property\n composes with the positioning \`transform\` above instead of\n replacing it. Motion is skipped for visitors who asked for less. */\n @keyframes joryio-inapp-fade-in { from { opacity: 0; } to { opacity: 1; } }\n @keyframes joryio-inapp-slide-in { from { opacity: 0; translate: 0 16px; } to { opacity: 1; translate: 0 0; } }\n .joryio-inapp-anim-fade { animation: joryio-inapp-fade-in 200ms ease-out both; }\n .joryio-inapp-anim-slide { animation: joryio-inapp-slide-in 240ms ease-out both; }\n @media (prefers-reduced-motion: reduce) {\n .joryio-inapp-anim-fade, .joryio-inapp-anim-slide { animation: none; }\n }\n\n /* The message content lives in a sandboxed iframe; its own CSS stays\n inside it (no leak to/from the host page). Only SDK chrome is here. */\n .joryio-inapp > iframe {\n border: 0;\n width: 100%;\n display: block;\n background: transparent;\n color-scheme: normal;\n }\n\n .joryio-inapp-modal {\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n max-width: 90%;\n max-height: 90%;\n }\n\n .joryio-inapp-banner {\n top: 0;\n left: 0;\n right: 0;\n }\n\n .joryio-inapp-slideup {\n bottom: 20px;\n right: 20px;\n max-width: 400px;\n }\n\n .joryio-inapp-fullscreen {\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n }\n\n /* Native card. Deliberately minimal and system-font: the host page's\n typography is the closest thing the web has to "the app's look", and\n a shipped palette would clash with every site.\n\n Every author-settable value comes through a CUSTOM PROPERTY with the\n system default as its fallback. That is what lets the campaign's own\n CSS override the colour pickers: inline styles beat a stylesheet, so\n setting the pickers inline would have made "advanced" strictly weaker\n than "basic" - the opposite of what an escape hatch is for. */\n .joryio-inapp-native {\n /* Positioning context for the close button, which sits in the card's\n top trailing corner rather than in the content flow. */\n position: relative;\n background: var(--joryio-inapp-bg, Canvas);\n color: var(--joryio-inapp-fg, CanvasText);\n color-scheme: light dark;\n border-radius: var(--joryio-inapp-radius, 14px);\n padding: 20px;\n box-shadow: 0 10px 40px rgba(0,0,0,0.18);\n font: menu;\n font-family: var(--joryio-inapp-font, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif);\n /* Direction-relative, so a Hebrew or Arabic message reads from the\n right without the campaign having to know which way it runs. The\n card carries dir=auto, so 'start' resolves per message. */\n text-align: var(--joryio-inapp-align, start);\n max-width: 420px;\n }\n .joryio-inapp-fullscreen .joryio-inapp-native {\n border-radius: 0;\n max-width: none;\n height: 100%;\n }\n .joryio-inapp-native img {\n width: 100%;\n height: 140px;\n object-fit: cover;\n border-radius: 8px;\n display: block;\n margin-bottom: 14px;\n }\n .joryio-inapp-native h2 {\n margin: 0 0 8px;\n /* Room for the close button in the trailing corner. Logical, so in a\n Hebrew message the gap is on the left, where the button is. */\n padding-inline-end: 28px;\n /* Derived from the body size so one control keeps the hierarchy. */\n font-size: calc(var(--joryio-inapp-size, 14.5px) * 1.3);\n font-weight: var(--joryio-inapp-title-weight, 700);\n line-height: 1.3;\n }\n .joryio-inapp-native p {\n margin: 0 0 16px;\n font-size: var(--joryio-inapp-size, 14.5px);\n line-height: 1.5;\n opacity: 0.85;\n }\n .joryio-inapp-buttons {\n display: flex;\n gap: 8px;\n }\n .joryio-inapp-buttons.stacked {\n flex-direction: column;\n }\n .joryio-inapp-native button {\n flex: 1;\n min-height: 44px;\n border-radius: 8px;\n font: inherit;\n font-size: 14px;\n cursor: pointer;\n border: 1px solid transparent;\n }\n .joryio-inapp-native button.primary {\n background: var(--joryio-inapp-primary, AccentColor);\n color: var(--joryio-inapp-primary-fg, AccentColorText);\n }\n .joryio-inapp-native button.secondary {\n background: transparent;\n color: inherit;\n border-color: rgba(128,128,128,0.4);\n }\n /*\n * Native messages used to override the shared close button into a\n * full-width "Close" text row under the buttons, while HTML messages in\n * this same SDK drew an ✕ in the corner. One SDK, two dismiss designs -\n * and the text row also hardcoded the English word "Close", which is\n * wrong in a Hebrew or Arabic app. The ✕ needs no translation, so native\n * now uses the shared button and this override is gone.\n */\n\n .joryio-inapp-backdrop {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: ${y};\n z-index: ${p-1};\n }\n\n .joryio-inapp-close {\n position: absolute;\n top: 6px;\n /* inset-inline-end, not right: the card carries dir=auto, so a Hebrew\n or Arabic message puts the ✕ in ITS trailing corner - the left one -\n without the campaign having to know which way the text runs. */\n inset-inline-end: 6px;\n display: flex;\n align-items: center;\n justify-content: center;\n /* 32px is the tap target; the glyph inside is smaller. Anything less\n is hard to hit on a phone, and it is the only way out of a\n full-screen message. */\n width: 32px;\n height: 32px;\n padding: 0;\n cursor: pointer;\n background: transparent;\n border: none;\n border-radius: 50%;\n font: inherit;\n font-size: 22px;\n line-height: 1;\n opacity: 0.55;\n color: ${v};\n }\n .joryio-inapp-close:hover,\n .joryio-inapp-close:focus-visible {\n opacity: 1;\n }\n `;const m=document.createElement("iframe");let b;if(m.id="joryio-iframe-"+a.id,"native"===(null===(i=a.content)||void 0===i?void 0:i.kind)){const i=a.content,s=document.createElement("div");s.className="joryio-inapp-native",s.dir="auto";const n=i.style;if("string"==typeof(null==n?void 0:n.customCss)&&(b=n.customCss),n){const t=(t,i,e="")=>{"string"==typeof i&&i.trim()?s.style.setProperty(t,i.trim()+e):"number"==typeof i&&Number.isFinite(i)&&s.style.setProperty(t,i+""+e)};t("--joryio-inapp-bg",n.backgroundColor),t("--joryio-inapp-fg",n.textColor),t("--joryio-inapp-font",n.fontFamily),t("--joryio-inapp-radius",n.cornerRadius,"px"),t("--joryio-inapp-size",n.fontSize,"px"),"string"==typeof n.titleWeight&&t("--joryio-inapp-title-weight",{regular:"400",medium:"500",semibold:"600",bold:"700"}[n.titleWeight]),"string"==typeof n.textAlign&&"auto"!==n.textAlign&&t("--joryio-inapp-align",n.textAlign),t("--joryio-inapp-primary",n.primaryButtonColor),t("--joryio-inapp-primary-fg","string"==typeof n.primaryButtonTextColor&&n.primaryButtonTextColor.trim()?n.primaryButtonTextColor:function(t){if("string"!=typeof t)return;const i=t.trim().replace(/^#/,""),e=3===i.length?i.replace(/(.)/g,"$1$1"):i;if(!/^[0-9a-f]{6}$/i.test(e))return;const[s,n,r]=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16));return.2126*s+.7152*n+.0722*r>150?"#0A1240":"#FFFFFF"}(n.primaryButtonColor))}if(i.imageUrl&&/^https:\/\//i.test(i.imageUrl)){const t=document.createElement("img");t.src=i.imageUrl,t.alt="",t.onerror=()=>t.remove(),s.appendChild(t)}if(i.title){const t=document.createElement("h2");t.textContent=i.title,s.appendChild(t)}const r=document.createElement("p");if(r.textContent=i.body,s.appendChild(r),null===(e=i.buttons)||void 0===e?void 0:e.length){const e=document.createElement("div");e.className=i.buttons.length>2?"joryio-inapp-buttons stacked":"joryio-inapp-buttons",i.buttons.forEach((i,s)=>{const n=document.createElement("button");n.type="button",n.textContent=i.text,n.className=0===s?"primary":"secondary",n.addEventListener("click",()=>{var e;const s=Wt(i.id);if(this.trackImpression(a.id,"clicked",Object.assign(Object.assign({},i.url&&/^https?:\/\//i.test(i.url)?{clickedUrl:i.url}:{}),s?{elementId:s}:{})).catch(()=>{}),this.callHost("onMessageClick",()=>{var e,s;return null===(s=(e=this.displayOptions).onClick)||void 0===s?void 0:s.call(e,t,i.id||i.action||"button")}),"request_push_permission"===i.action)this.canPromptForPush()&&(null===(e=this.bridge)||void 0===e||e.requestPushPermission());else if(("url"===i.action||"deep_link"===i.action)&&i.url){const t=i.url,e=()=>{/^https?:\/\//i.test(t)&&window.open(t,"_blank","noopener")};this.links?this.links.route(t,"in_app",{campaignId:a.id},e):e()}this.dismiss(a.id,"button").catch(()=>{})}),e.appendChild(n)}),s.appendChild(e)}if(!1!==i.closeButton){const t=document.createElement("button");t.type="button",t.className="joryio-inapp-close",t.innerHTML="&times;",t.setAttribute("aria-label","Close"),t.addEventListener("click",()=>{this.dismiss(a.id,"close_button").catch(()=>{})}),s.appendChild(t)}u.appendChild(s)}let g=!1;if("native"!==(null===(s=a.content)||void 0===s?void 0:s.kind)){if(!this.allowHtmlJsInAppMessages)return void this.logger.warn(`Campaign ${a.id} is an HTML in-app message, but allowHtmlJsInAppMessages is false - not displaying it.`);m.setAttribute("sandbox","allow-scripts allow-same-origin allow-popups");let t=0;m.addEventListener("load",()=>{var i,e;t++;let s=!0;try{const t=null===(e=null===(i=m.contentWindow)||void 0===i?void 0:i.location)||void 0===e?void 0:e.href;s=void 0===t||"about:srcdoc"===t}catch(t){s=!1}1>=t&&s||(this.logger.warn(`In-app message ${a.id} tried to navigate its frame; it has been closed`),this.dismiss(a.id,"navigation_blocked").catch(()=>{}))}),m.setAttribute("title",a.name||"Message"),m.style.height="0","banner"!==a.type&&"fullscreen"!==a.type||(m.style.width="100%");const i=function(t){var i;if("modal"!==t.type&&"slideup"!==t.type)return null;if("html"!==(null===(i=t.content)||void 0===i?void 0:i.kind))return null;const e=t.content.maxWidth;return"number"==typeof e&&Number.isFinite(e)&&e>0?Math.floor(e):qt[t.type]}(a);if(null!==i&&(u.style.maxWidth="none",this.frameMaxWidths.set(a.id,i),m.style.width=zt(i,this.hostViewportWidth())+"px",this.watchViewport()),m.srcdoc=this.buildSrcdoc(a.id,l,"html"===(null===(n=a.content)||void 0===n?void 0:n.kind)?a.content.css:"",a.type),u.appendChild(m),this.iframes.set(a.id,m),l.includes("requestPushPermission")&&(null===(o=null===(r=this.bridge)||void 0===r?void 0:r.preparePushPermission)||void 0===o||o.call(r)),!1!==this.displayOptions.closeButton){const t=document.createElement("button");t.className="joryio-inapp-close",t.innerHTML="&times;",t.setAttribute("aria-label","Close"),t.onclick=async()=>{g||(g=!0,await this.dismiss(a.id,"close_button").catch(()=>{}))},u.appendChild(t)}}let w=null;if("modal"===a.type||"fullscreen"===a.type){w=document.createElement("div"),w.className="joryio-inapp-backdrop",w.id="joryio-backdrop-"+a.id;const t="native"!==(null===(h=a.content)||void 0===h?void 0:h.kind)||!1!==a.content.backdropDismissible;!1!==this.displayOptions.backdropClose&&t&&(w.onclick=async()=>{g||(g=!0,await this.dismiss(a.id,"backdrop").catch(()=>{}))})}const k=this.displayOptions.container||document.documentElement;if(w&&k.appendChild(w),k.appendChild(f),"string"==typeof b&&b.trim()){const t=this.scopeCss(b,"#joryio-inapp-"+a.id);if(t){const i=document.createElement("style");i.id="joryio-css-"+a.id,i.textContent=t,k.appendChild(i)}}k.appendChild(u),this.logger.info(`Displayed campaign: ${a.name} (${a.id})`)}hostViewportWidth(){const t="undefined"!=typeof document?document.documentElement:null,i=t&&"number"==typeof t.clientWidth?t.clientWidth:0;return i>0?i:"undefined"!=typeof window&&"number"==typeof window.innerWidth?window.innerWidth:0}sizeContentFrame(t){const i=this.iframes.get(t),e=this.frameMaxWidths.get(t);i&&void 0!==e&&(i.style.width=zt(e,this.hostViewportWidth())+"px")}watchViewport(){this.viewportListener||"undefined"==typeof window||"function"!=typeof window.addEventListener||(this.viewportListener=()=>{this.viewportTimer&&clearTimeout(this.viewportTimer),this.viewportTimer=setTimeout(()=>{this.viewportTimer=void 0;for(const t of this.frameMaxWidths.keys())this.sizeContentFrame(t)},100)},window.addEventListener("resize",this.viewportListener))}unwatchViewportIfIdle(){0>=this.frameMaxWidths.size&&this.viewportListener&&("undefined"!=typeof window&&"function"==typeof window.removeEventListener&&window.removeEventListener("resize",this.viewportListener),this.viewportListener=void 0,this.viewportTimer&&(clearTimeout(this.viewportTimer),this.viewportTimer=void 0))}buildSrcdoc(t,i,e,s){return Zt(t,i,e,s)}scopeCss(t,i){let e=null;try{e=document.createElement("style"),e.media="not all",e.textContent=t,document.head.appendChild(e);const s=e.sheet;if(!s)return this.logger.warn("Custom CSS could not be parsed; ignoring it"),"";const n=Bt(s.cssRules,i);return n||this.logger.warn("Custom CSS contained no rules that can be scoped; ignoring it"),n}catch(t){return this.logger.warn("Custom CSS could not be parsed; ignoring it",t),""}finally{null==e||e.remove()}}async dismiss(t,i="dismiss"){const e=this.pendingDelays.get(t);e&&(clearTimeout(e),this.pendingDelays.delete(t));let s=!0;const n=this.awaitingDwell.get(t);n&&(Ht.has(i)&&n.generation===this.generation?this.confirmDisplay(t).catch(()=>{}):(this.dropDwell(t),s=!1));const r=document.getElementById("joryio-inapp-"+t),o=document.getElementById("joryio-backdrop-"+t),h=document.getElementById("joryio-style-"+t),a=document.getElementById("joryio-css-"+t);r&&r.remove(),this.iframes.delete(t),this.frameMaxWidths.delete(t),this.unwatchViewportIfIdle(),o&&o.remove(),h&&h.remove(),a&&a.remove();const l=this.displayedMessages.get(t);l&&(s&&await this.trackImpression(t,"dismissed").catch(()=>{}),this.callHost("onMessageDismiss",()=>{var t,e;return null===(e=(t=this.displayOptions).onDismiss)||void 0===e?void 0:e.call(t,l,i)}),this.displayedMessages.delete(t)),this.logger.info("Dismissed campaign: "+t)}async trackConversion(t,i){await this.trackImpression(t,"converted",{conversionEvent:i});const e=this.displayedMessages.get(t);e&&this.callHost("onConversion",()=>{var t,s;return null===(s=(t=this.displayOptions).onConversion)||void 0===s?void 0:s.call(t,e,i)})}async submitForm(t,i){var e,s,n;const r=this.displayedMessages.get(t);if(!this.runtime.canSend())return{ok:!1,message:"This form cannot be sent right now."};const h=new AbortController,a=setTimeout(()=>h.abort(),this.runtime.requestTimeoutMs),l=this.identity.getUserId();try{const a=()=>{var e,s,n;return fetch(this.apiEndpoint+"/v1/in-app/form-submit",{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(e=this.auth)||void 0===e?void 0:e.getSdkAuthHeaders(l,l?null:this.identity.getAnonymousId()))||{}),body:JSON.stringify(Object.assign(Object.assign({campaignId:t,variantId:null===(s=null==r?void 0:r.campaign)||void 0===s?void 0:s.variantId,userId:this.identity.getUserId()||void 0,anonymousId:this.identity.getAnonymousId()},(null===(n=null==r?void 0:r.campaign)||void 0===n?void 0:n.formToken)?{formToken:r.campaign.formToken}:{}),{values:i})),signal:h.signal})};let u=await a();if(401===u.status&&(null===(e=this.auth)||void 0===e?void 0:e.isStorefrontIdentityError)){const t=await u.clone().json().catch(()=>null);this.auth.isStorefrontIdentityError(401,t)&&await(null===(n=(s=this.auth).handleStorefrontIdentityError)||void 0===n?void 0:n.call(s,t).catch(()=>!1))&&(u=await a())}await this.maybeHandleSdkAuthError(u,this.apiEndpoint+"/v1/in-app/form-submit",l);const c=await u.json().catch(()=>null);return c&&"object"==typeof c?c:{ok:!1,message:"Something went wrong. Please try again."}}catch(t){return{ok:!1,message:"Something went wrong. Please try again."}}finally{clearTimeout(a)}}async trackImpression(t,i,e){var s,n,r,h,a;const l=this.campaigns.get(t)||(null===(s=this.displayedMessages.get(t))||void 0===s?void 0:s.campaign);if(!l)return;if(!this.runtime.canSend())return;const u="displayed"!==i?this.awaitingDwell.get(t):void 0;if(u){if(u.generation!==this.generation)return;this.confirmDisplay(t).catch(()=>{})}const c=this.session.getSessionId(),d=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({campaignId:t,variantId:l.variantId},this.subject()),{sessionId:c,deviceType:"web",locale:navigator.language,userAgent:navigator.userAgent}),l.pendingId?{pendingId:l.pendingId}:{}),l.deliveryToken?{deliveryToken:l.deliveryToken}:{}),e);"displayed"===i?d.displayedAt=(new Date).toISOString():"clicked"===i?(d.clicked=!0,d.clickedAt=(new Date).toISOString(),d.action="clicked"):"dismissed"===i?(d.dismissedAt=(new Date).toISOString(),d.action="dismissed"):"converted"===i&&(d.converted=!0,d.convertedAt=(new Date).toISOString());const f=new AbortController,p=setTimeout(()=>f.abort(),this.runtime.requestTimeoutMs),y="string"==typeof d.userId&&d.userId?d.userId:null;try{const e=await fetch(this.apiEndpoint+"/v1/in-app/track",{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(n=this.auth)||void 0===n?void 0:n.getSdkAuthHeaders(y,y?null:null!==(r=d.anonymousId)&&void 0!==r?r:null))||{}),body:JSON.stringify(d),signal:f.signal});e.ok||null===(a=(h=this.runtime).noteStatus)||void 0===a||a.call(h,e.status,null),await this.maybeHandleSdkAuthError(e,this.apiEndpoint+"/v1/in-app/track",y),this.logger.debug(`Tracked ${i} for campaign ${t}`)}catch(e){"AbortError"===(null==e?void 0:e.name)?this.logger.error(`Impression tracking timed out after ${this.runtime.requestTimeoutMs}ms for campaign ${t}`):this.logger.error(`Failed to track ${i}:`,e)}finally{clearTimeout(p)}}checkFrequencyCap(t){if(!t.frequencyCap)return!0;const{maxImpressions:i,timeWindow:e,minDelayBetweenImpressions:s}=t.frequencyCap;if(!i||!e)return!0;const n=this.impressionTimestamps.get(t.id)||[],r=Date.now();let o=0;if("once"===e||"lifetime"===e)return 0===n.length;if("session"===e)o=this.session.getSessionInfo().sessionStart;else{const t=[["min",6e4],["mo",2592e6],["h",36e5],["d",864e5],["w",6048e5],["m",2592e6]];let i=864e5;for(const[s,n]of t){if(!e.endsWith(s))continue;const t=parseInt(e.slice(0,-s.length),10);!Number.isNaN(t)&&t>0&&(i=t*n);break}o=r-i}return n.filter(t=>t>=o).length<i&&!(s&&n.length>0&&1e3*s>r-n[n.length-1])}startAttributeWatching(){if(this.syncInterval&&(clearInterval(this.syncInterval),this.syncInterval=void 0),0===this.watchedAttributes.size)return;this.logger.debug(`Watching ${this.watchedAttributes.size} attributes for changes`);const t={};this.watchedAttributes.forEach(i=>{t[i]=this.identity.getAttribute(i)}),this.syncInterval=window.setInterval(()=>{if("undefined"!=typeof document&&document.hidden)return;const i={};let e=!1;if(this.watchedAttributes.forEach(s=>{const n=this.identity.getAttribute(s);n!==t[s]&&(i[s]=n,t[s]=n,e=!0)}),e){if(this.checkAttributeThresholds(Object.keys(i)),"session-start-only"===this.runtime.evaluationMode||!this.runtime.canSend())return;this.logger.info("Attribute changes detected, re-syncing campaigns"),this.sync(i).catch(t=>{this.logger.error("Failed to re-sync on attribute change:",t)})}},5e3)}checkAttributeThresholds(t){if(!t.length)return;const i=this.identity.getAttributes()||{};for(const e of this.campaigns.values())if((e.triggers||[]).some(e=>"attribute_threshold"===e.type&&!!e.attribute&&t.includes(e.attribute)&&this.triggerFilterMatches(e,i)))return void this.displayCampaign(e).catch(t=>this.logger.error("In-app display failed:",t))}getCampaigns(){return Array.from(this.campaigns.values())}getCampaign(t){return this.campaigns.get(t)}clearAll(){this.logger.info("Clearing in-app messaging state"),this.invalidate(),this.stop();for(const t of this.displayedMessages.keys())this.dismiss(t,"clear").catch(t=>this.logger.error("In-app dismiss failed:",t));this.campaigns.clear(),this.displayedMessages.clear(),this.awaitingDwell.forEach((t,i)=>this.dropDwell(i)),this.watchedAttributes.clear(),this.iframes.clear(),this.frameMaxWidths.clear(),this.unwatchViewportIfIdle(),this.logger.info("In-app messaging state cleared")}forgetImpressions(){var t;this.impressionTimestamps.clear();try{null===(t=this.storage)||void 0===t||t.remove(Rt)}catch(t){}}boundedMapSet(t,i,e,s){if(t.set(i,e),t.size>s){const i=t.keys().next().value;void 0!==i&&t.delete(i)}}boundedSetAdd(t,i,e){if(t.add(i),t.size>e){const i=t.values().next().value;void 0!==i&&t.delete(i)}}destroy(){var t;null===(t=this.pageUnsubscribe)||void 0===t||t.call(this),this.pageUnsubscribe=null,this.logger.info("Destroying in-app messaging"),this.stop();for(const t of this.displayedMessages.keys())this.dismiss(t,"destroy").catch(t=>this.logger.error("In-app dismiss failed:",t));this.campaigns.clear(),this.displayedMessages.clear(),this.awaitingDwell.forEach((t,i)=>this.dropDwell(i)),this.removePageLifecycle(),this.impressionTimestamps.clear(),this.watchedAttributes.clear(),this.iframes.clear(),this.frameMaxWidths.clear(),this.unwatchViewportIfIdle(),"undefined"!=typeof window&&delete window[Jt]}}function Zt(t,i,e,s,n=Jt){const r="modal"===s||"slideup"===s||"placement"===s,o=r?"body{display:flow-root;}":"",h=`(function(){\n var CID=${JSON.stringify(t)},KEY=${JSON.stringify(n)},SIZED=${r?"true":"false"};\n // Per-device visibility: tag the root with the REAL device class from the\n // HOST page viewport (the iframe is message-sized, so its own innerWidth is\n // useless here). The jr-vp-* → jr-hide-* rules in <style> then hide elements\n // the dashboard marked "Mobile only" / "Desktop only". <=480 = mobile.\n try{var __vp=0;try{__vp=window.parent.innerWidth||0;}catch(e){}if(!__vp)__vp=window.innerWidth||0;document.documentElement.className+=(__vp<=480?' jr-vp-mobile':' jr-vp-desktop');}catch(e){}\n function host(){try{return window.parent[KEY]||null;}catch(e){return null;}}\n function call(m,args){var b=host();if(b&&typeof b[m]==='function'){try{return b[m].apply(b,[CID].concat(args||[]));}catch(e){}}}\n window.joryioBridge={\n logCustomEvent:function(name,props){call('logCustomEvent',[name,props]);},\n setCustomUserAttribute:function(k,v){call('setCustomUserAttribute',[k,v]);},\n changeUser:function(uid){call('changeUser',[uid]);},\n requestPushPermission:function(){call('requestPushPermission',[]);},\n logConversion:function(ev){call('logConversion',[ev||'in_app_conversion']);},\n submitForm:function(values){return call('submitForm',[values]);},\n logClick:function(action){call('logClick',[action]);},\n navigate:function(url,target){call('navigate',[url,target]);},\n closeMessage:function(){call('closeMessage',[]);}\n };\n document.addEventListener('click',function(e){\n var el=e.target;\n while(el&&el!==document.body&&el!==document.documentElement){\n var action=el.getAttribute&&el.getAttribute('data-joryio-action');\n if(action&&typeof window.joryioBridge[action]==='function'){e.preventDefault();window.joryioBridge[action](el.getAttribute('data-joryio-event')||undefined);return;}\n var tag=el.tagName;\n if(tag==='A'||tag==='BUTTON'){\n var da=el.getAttribute('data-action');\n var href=tag==='A'?el.getAttribute('href'):null;\n window.joryioBridge.logClick(da||(href?'link_click':'cta_click'));\n // Route only http(s)/root-relative links through the host (top-nav,\n // since the sandbox can't navigate the top page itself). Leave\n // #anchors, mailto:, tel:, sms: to the browser. Any other link\n // would navigate THIS frame away from the message: cancelled (rule 57).\n if(href&&/^(https?:\\/\\/|\\/(?!\\/))/i.test(href)){e.preventDefault();window.joryioBridge.navigate(href,el.getAttribute('target'));}\n else if(href&&!/^(#|mailto:|tel:|sms:)/i.test(href)){e.preventDefault();}\n return;\n }\n el=el.parentNode;\n }\n },true);\n // Forms (data-jry-form): serialize, hand the values to the host, show the\n // answer in place. A redirect goes through navigate (the sandbox cannot).\n document.addEventListener('submit',function(ev){var f=ev.target;if(!(f&&f.tagName==='FORM'&&f.hasAttribute('data-jry-form')))return;ev.preventDefault();if(f.getAttribute('data-jry-busy'))return;\n var d={},els=f.querySelectorAll('input,select,textarea');for(var i=0;i<els.length;i++){var el=els[i],n=el.name;if(!n||el.disabled)continue;if(el.type==='checkbox'){if(!el.checked)continue;if(d[n]===undefined)d[n]=[];d[n].push(el.value||'on')}else if(el.type==='radio'){if(el.checked)d[n]=el.value}else d[n]=el.value}\n function msg(text,ok){var b=f.querySelector('[data-jry-message]');if(!b){b=document.createElement('div');b.setAttribute('data-jry-message','');b.setAttribute('role','status');f.appendChild(b)}b.textContent=text;b.className=ok?'jry-form-success':'jry-form-error';reportSize()}\n f.setAttribute('data-jry-busy','1');var btn=f.querySelector('button[type="submit"],input[type="submit"]');if(btn)btn.disabled=true;\n var p=window.joryioBridge.submitForm(d);if(!p||typeof p.then!=='function'){msg('This form cannot be sent here.',false);f.removeAttribute('data-jry-busy');if(btn)btn.disabled=false;return}\n p.then(function(r){if(r&&r.ok){if(r.redirect){window.joryioBridge.navigate(r.redirect,'_top');return}var els2=f.querySelectorAll('input,select,textarea,button');for(var j=0;j<els2.length;j++){els2[j].disabled=true}msg(r.message||'Thank you.',true)}else{msg((r&&(r.message||(r.errors&&r.errors[0])))||'Something went wrong. Please try again.',false);f.removeAttribute('data-jry-busy');if(btn)btn.disabled=false}}).catch(function(){msg('Something went wrong. Please try again.',false);f.removeAttribute('data-jry-busy');if(btn)btn.disabled=false});\n },true);\n function reportSize(){try{var b=document.body,de=document.documentElement;var w=Math.max(b?b.scrollWidth:0,de.scrollWidth);var h=SIZED&&b?Math.ceil(Math.max(b.scrollHeight,b.getBoundingClientRect?b.getBoundingClientRect().height:0)):Math.max(b?b.scrollHeight:0,de.scrollHeight);call('setSize',[w,h]);}catch(e){}}\n if(document.readyState!=='loading')reportSize();else document.addEventListener('DOMContentLoaded',reportSize);\n window.addEventListener('load',reportSize);\n try{if(window.ResizeObserver&&document.body){new ResizeObserver(reportSize).observe(document.body);}}catch(e){}\n })();`,a=function(){const t=new Uint8Array(16),i=globalThis.crypto;if(i&&"function"==typeof i.getRandomValues)i.getRandomValues(t);else for(let i=0;i<t.length;i++)t[i]=Math.floor(256*Math.random());return Array.from(t,t=>t.toString(16).padStart(2,"0")).join("")}();return`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${["default-src 'none'",`script-src 'nonce-${a}'`,"style-src 'unsafe-inline'; img-src https: data:; media-src https: data:; font-src https: data:; connect-src 'none'; form-action 'none'; base-uri 'none'; upgrade-insecure-requests"].join("; ")}"><meta name="viewport" content="width=device-width, initial-scale=1"><style>html,body{margin:0;padding:0;}img,video{max-width:100%;height:auto;}${o}.jr-vp-mobile .jr-hide-mobile{display:none!important}.jr-vp-desktop .jr-hide-desktop{display:none!important}${e=function(t){return"string"==typeof t?t.replace(/<\//g,"<\\/"):""}(e)}</style></head><body>${i}<script nonce="${a}">${h}<\/script></body></html>`}function Yt(t,i){if(!t.attribute)return!0;const e=null==i?void 0:i[t.attribute],s=t.value;switch(t.operator){case void 0:case"equals":case"eq":return e===s;case"not_equals":case"neq":return e!==s;case"greater_than":case"gt":return+e>+s;case"less_than":case"lt":return+s>+e;case"contains":return((null!=e?e:"")+"").includes(s+"");case"exists":return null!=e;default:return!1}}function ti(t){let i=!1;const e=()=>{i||(i=!0,t())},s=()=>e();return s.cancel=e,s}const ii="product:";function ei(t){return`${ii}${t}`.slice(0,128)}const si=t=>"joryio_placements_v1_"+e(t).toString(36),ni="__joryioPlacement",ri=/^[a-z0-9][a-z0-9_]{0,63}$/,oi=()=>Date.now();function hi(t){return"string"==typeof t&&ri.test(t)}function ai(){try{const t=null===navigator||void 0===navigator?void 0:navigator.userActivation;return!t||!0===t.isActive}catch(t){return!0}}function li(t){return"string"==typeof t&&/^https?:\/\//i.test(t)?t:null}const ui=["javascript","data","file","vbscript","blob","about","content","intent"];function ci(t){if("string"!=typeof t)return!1;const i=/^([a-z][a-z0-9+.-]*):\/\/./i.exec(t.trim());if(!i)return!1;const e=i[1].toLowerCase();return"http"!==e&&"https"!==e&&!ui.includes(e)}function di(){return"undefined"==typeof document||"hidden"!==document.visibilityState}function fi(t,i){let e=!1;const s={observer:null,timer:null,inView:!1,resume:()=>{!e&&!s.timer&&s.inView&&di()&&(s.timer=setTimeout(()=>{var t;s.timer=null,!e&&s.inView&&di()&&(e=!0,null===(t=s.observer)||void 0===t||t.disconnect(),i())},Lt))},pause:()=>{s.timer&&clearTimeout(s.timer),s.timer=null},cancel:()=>{var t;e=!0,null===(t=s.observer)||void 0===t||t.disconnect(),s.pause()}};return"undefined"==typeof IntersectionObserver?(s.inView=!0,s.resume(),s):(s.observer=new IntersectionObserver(t=>{for(const i of t)s.inView=i.isIntersecting&&i.intersectionRatio>=.5,s.inView?s.resume():s.pause()},{threshold:[0,.5,1]}),s.observer.observe(t),s)}class pi{constructor(t,i,e,s,n,r,o){this.apiEndpoint=t,this.sdkKey=i,this.identity=e,this.session=s,this.logger=n,this.runtime=r,this.auth=o,this.links=null,this.cache=new Map,this.lastNetworkAt=new Map,this.inflight=new Map,this.batchKeys=new Set,this.batchTimer=null,this.batchWaiters=[],this.deferredKeys=new Set,this.deferredTimer=null,this.listeners=new Set,this.mounts=new Set,this.reported=new Set,this.triggeredAt=new Map,this.dismissedLocally=new Set,this.generation=0,this.mutationObserver=null,this.frames=new Map,this.frameSeq=0,this.pageListener=null,this.destroyed=!1,this.page=null,this.pageUnsubscribe=null,this.pageScopedKeys=new Set,this.loadCache(),this.installBridge(),this.installPageVisibility()}insertPlacement(t,i,e={}){if(!hi(t))return this.logger.warn(`insertPlacement: "${t}" is not a placement key (a-z, 0-9 and _, up to 64)`),null;if(!i||"function"!=typeof i.appendChild)return this.logger.warn("insertPlacement: an element is required"),null;for(const t of this.mounts)t.element===i&&this.unmount(t);const s={key:t,element:i,options:e,wrapper:null,shown:[],pendingUpdate:!1,hostInView:!1,hostObserver:null,trackers:[],frameIds:[]};return this.mounts.add(s),this.observeHost(s),this.freshEntry(t)&&this.render(s),this.ensure([t]).then(()=>{this.mounts.has(s)&&!s.wrapper&&this.render(s)}).catch(t=>this.logger.debug("Placement fetch failed:",t)),{placementKey:t,element:i,remove:()=>this.unmount(s)}}async getPlacements(t){const i=this.cleanKeys(t);await this.ensure(i);const e={};for(const t of i)e[t]=this.toPlacement(t);return e}async refreshPlacements(t){const i=t?this.cleanKeys(t):this.knownKeys();i.length&&await this.fetchKeys(i,!0)}onPlacementsUpdated(t){if("function"!=typeof t)return ti(()=>{});const i=i=>t(i);return this.listeners.add(i),ti(()=>{this.listeners.delete(i)})}autoMount(){"undefined"!=typeof document&&"function"==typeof document.querySelectorAll&&("loading"!==document.readyState||"function"!=typeof document.addEventListener?(this.scanDocument(),!this.mutationObserver&&"undefined"!=typeof MutationObserver&&document.body&&(this.mutationObserver=new MutationObserver(()=>this.scanDocument()),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}))):document.addEventListener("DOMContentLoaded",()=>!this.destroyed&&this.autoMount(),{once:!0}))}onEventTracked(t,i){if(!t)return;const e=new Set;for(const[s,n]of this.cache)for(const r of n.placement.items||[])(r.triggers||[]).some(e=>"event"===e.type&&e.event===t&&Yt(e,i))&&(this.triggeredAt.set(this.handle(s,r),oi()),e.add(s));e.size&&this.applyChanged(Array.from(e))}invalidate(){this.generation++,this.cache.clear(),this.lastNetworkAt.clear(),this.triggeredAt.clear(),this.dismissedLocally.clear(),this.reported.clear(),this.persistCache();const t=this.mountedKeys();for(const t of this.mounts)this.render(t);t.length&&this.fetchKeys(t,!0).catch(()=>{})}destroy(){var t,i,e;this.destroyed=!0,null===(t=this.pageUnsubscribe)||void 0===t||t.call(this),this.pageUnsubscribe=null;for(const t of Array.from(this.mounts))this.unmount(t);null===(i=this.mutationObserver)||void 0===i||i.disconnect(),this.mutationObserver=null,this.batchTimer&&clearTimeout(this.batchTimer),this.deferredTimer&&clearTimeout(this.deferredTimer),this.batchTimer=null,this.deferredTimer=null,this.batchWaiters.forEach(t=>t.resolve()),this.batchWaiters=[],this.listeners.clear(),this.pageListener&&"undefined"!=typeof document&&"function"==typeof document.removeEventListener&&document.removeEventListener("visibilitychange",this.pageListener);try{"undefined"!=typeof window&&(null===(e=window[ni])||void 0===e?void 0:e.__owner)===this&&delete window[ni]}catch(t){}}cleanKeys(t){const i=[];for(const e of Array.isArray(t)?t:[])hi(e)&&!i.includes(e)?i.push(e):hi(e)||this.logger.warn(`Ignoring "${e}": not a placement key`);return i}knownKeys(){return Array.from(new Set([...this.mountedKeys(),...this.cache.keys()]))}mountedKeys(){return Array.from(new Set(Array.from(this.mounts).map(t=>t.key)))}setPageContext(t){var i;null===(i=this.pageUnsubscribe)||void 0===i||i.call(this),this.pageUnsubscribe=null,this.page=t,t&&(this.pageUnsubscribe=t.onSignal(t=>{if("page_change"!==t.type||this.destroyed)return;const i=[];if(this.cache.forEach((e,s)=>{e.placement.pageScoped&&e.url!==t.url&&i.push(s)}),!i.length)return;i.forEach(t=>this.cache.delete(t)),this.persistCache();for(const t of this.mounts)i.includes(t.key)&&this.render(t);const e=i.filter(t=>this.mountedKeys().includes(t));e.length&&this.fetchKeys(e,!1).then(()=>{for(const t of this.mounts)e.includes(t.key)&&!t.wrapper&&this.render(t)}).catch(()=>{})}))}currentUrl(){return this.page?this.page.current().url:m()}rateKey(t){var i,e;return(null===(i=this.cache.get(t))||void 0===i?void 0:i.placement.pageScoped)||this.pageScopedKeys.has(t)?`${t}\0${null!==(e=this.currentUrl())&&void 0!==e?e:""}`:t}freshEntry(t){const i=this.cache.get(t);if(!i)return null;if(i.placement.pageScoped&&i.url!==this.currentUrl())return null;const e=1e3*(i.placement.ttlSeconds||300);return oi()-i.fetchedAt<e?i:null}async ensure(t){const i=t.filter(t=>!this.freshEntry(t));i.length&&await this.fetchKeys(i,!1)}fetchKeys(t,i){const e=oi(),s=[],n=[];for(const r of t){const t=this.inflight.get(r);if(t){s.push(t),i&&this.defer(r);continue}const o=this.lastNetworkAt.get(this.rateKey(r));void 0!==o&&3e4>e-o?i&&this.defer(r):n.push(r)}if(n.length){n.forEach(t=>this.batchKeys.add(t));const t=new Promise(t=>this.batchWaiters.push({keys:n,resolve:t}));n.forEach(i=>this.inflight.set(i,t)),this.batchTimer||(this.batchTimer=setTimeout(()=>{this.flushBatch()},50)),s.push(t)}return Promise.all(s).then(()=>{})}defer(t){if(this.deferredKeys.add(t),this.deferredTimer)return;const i=Math.min(...Array.from(this.deferredKeys).map(t=>{var i;return null!==(i=this.lastNetworkAt.get(this.rateKey(t)))&&void 0!==i?i:0})),e=Math.max(0,i+3e4-oi());this.deferredTimer=setTimeout(()=>{this.deferredTimer=null;const t=Array.from(this.deferredKeys);this.deferredKeys.clear(),t.length&&!this.destroyed&&this.fetchKeys(t,!1).catch(()=>{})},e+10)}async flushBatch(){this.batchTimer=null;const t=Array.from(this.batchKeys);this.batchKeys.clear();const i=this.batchWaiters;this.batchWaiters=[];const e=[];for(let i=0;i<t.length;i+=10)e.push(t.slice(i,i+10));try{await Promise.all(e.map(t=>this.request(t)))}finally{t.forEach(t=>this.inflight.delete(t)),i.forEach(t=>t.resolve())}}async request(t){var i,e,s,n;const r=this.runtime.consent();if(null===r||this.destroyed)return;const h=this.generation,a="granted"===r,l=oi();t.forEach(t=>this.lastNetworkAt.set(this.rateKey(t),l));const u=this.currentUrl(),c={};for(const i of this.mounts)t.includes(i.key)&&i.shown.length&&(c[i.key]=i.shown.slice());const d=a?this.identity.getUserId():null,f=a?this.identity.getAnonymousId():null,p=Object.assign(Object.assign(Object.assign(Object.assign({},d?{userId:d}:{}),f?{anonymousId:f}:{}),a?{sessionId:this.session.getSessionId()}:{}),{deviceType:"web",locale:"undefined"!=typeof navigator?navigator.language:void 0,capabilities:this.capabilities(),trackingConsent:r,placements:t,shown:c,context:this.page?Object.assign(Object.assign({},this.page.current()),{screen:null}):{url:m(),screen:null}}),y="undefined"!=typeof AbortController?new AbortController:null,v=setTimeout(()=>null==y?void 0:y.abort(),null!==(i=this.runtime.requestTimeoutMs)&&void 0!==i?i:1e4),b=this.apiEndpoint+"/v1/in-app/placements";try{const i=await fetch(b,Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),a&&(null===(e=this.auth)||void 0===e?void 0:e.getSdkAuthHeaders(d,d?null:f))||{}),body:JSON.stringify(p)},y?{signal:y.signal}:{}));if(!i.ok)return null===(n=(s=this.runtime).noteStatus)||void 0===n||n.call(s,i.status,null),void this.logger.debug(`Placements request answered ${i.status}; keeping the cached placements`);const r=await i.json();if(h!==this.generation)return void this.logger.debug("Discarding a placements answer that predates an identity or consent change");if(!r||!1===r.success||!r.placements||"object"!=typeof r.placements)return;const l=oi(),c=[];for(const i of t){const t=r.placements[i]||{placementKey:i,items:[]},e=this.normalize(i,t),s=this.cache.get(i);this.cache.set(i,{placement:e,fetchedAt:l,url:u}),e.pageScoped?this.pageScopedKeys.add(i):this.pageScopedKeys.delete(i);for(const t of Array.from(this.dismissedLocally))t.startsWith(i+"\0")&&this.dismissedLocally.delete(t);s&&JSON.stringify(s.placement)===JSON.stringify(e)||c.push(i)}this.persistCache(),c.length&&this.applyChanged(c)}catch(t){const i="AbortError"===(null==t?void 0:t.name);this.logger.debug(i?"Placements request timed out":"Placements request failed",t)}finally{clearTimeout(v)}}capabilities(){const t=["placements","content.native","content.data"];return this.page&&t.push(c),this.runtime.allowHtml()&&t.push("content.html"),t}normalize(t,i){const e=Array.isArray(i.items)?i.items.filter(t=>t&&"string"==typeof t.id):[];return Object.assign({placementKey:t,emptyBehavior:"keep_space"===i.emptyBehavior?"keep_space":"collapse",maxItems:"number"==typeof i.maxItems&&i.maxItems>0?i.maxItems:1,ttlSeconds:"number"==typeof i.ttlSeconds&&i.ttlSeconds>0?i.ttlSeconds:300,isControl:!0===i.isControl,controlToken:i.controlToken||null,items:e},!0===i.pageScoped?{pageScoped:!0}:{})}applyChanged(t){for(const i of this.mounts)t.includes(i.key)&&(i.hostInView&&i.shown.length?i.pendingUpdate=!0:this.render(i));if(!this.listeners.size)return;const i={};t.forEach(t=>i[t]=this.toPlacement(t));for(const t of Array.from(this.listeners))try{t(i)}catch(t){this.logger.error("The onPlacementsUpdated callback threw; ignored:",t)}}handle(t,i){return`${t}\0${i.deliveryToken||i.id}`}visibleItems(t){const i=this.cache.get(t);if(!i)return[];const e=oi(),s=i.placement.maxItems||1;return(i.placement.items||[]).filter(i=>{if(i.expiresAt&&Date.parse(i.expiresAt)<=e)return!1;if(this.dismissedLocally.has(this.handle(t,i)))return!1;if((i.triggers||[]).filter(t=>"event"===t.type).length){const s=this.triggeredAt.get(this.handle(t,i)),n=i.placementTriggerWindowSeconds||1800;if(void 0===s||e-s>1e3*n)return!1}return!0}).slice(0,s)}toPlacement(t){const i=this.cache.get(t),e=(null==i?void 0:i.placement)||this.normalize(t,{placementKey:t,items:[]}),s=this.generation;return{placementKey:t,items:this.visibleItems(t).map(i=>this.toItem(t,i,s)),isControl:!0===e.isControl,emptyBehavior:e.emptyBehavior||"collapse",maxItems:e.maxItems||1,ttlSeconds:e.ttlSeconds||300,markDisplayed:()=>this.current(s)&&this.reportControl(t)}}current(t){return t===this.generation}toItem(t,i,e){var s,n,r;return{id:i.id,variantId:null!==(s=i.variantId)&&void 0!==s?s:null,kind:i.kind,data:Object.assign({},i.data||{}),content:null!==(n=i.content)&&void 0!==n?n:null,products:yi(i.products),priority:i.priority,expiresAt:null!==(r=i.expiresAt)&&void 0!==r?r:null,markDisplayed:()=>this.current(e)&&this.report(t,i,"displayed"),markClicked:s=>this.current(e)&&this.report(t,i,"clicked",s),markDismissed:()=>this.current(e)&&this.dismissItem(t,i)}}dismissItem(t,i){this.report(t,i,"dismissed"),this.dismissedLocally.add(this.handle(t,i));for(const i of this.mounts)i.key===t&&this.render(i)}report(t,i,e,s){if("granted"!==this.runtime.consent())return;const n=`${e}:${this.handle(t,i)}`;if("clicked"!==e){if(this.reported.has(n))return;this.reported.add(n)}"displayed"!==e&&this.report(t,i,"displayed");const r=(new Date).toISOString(),o=Wt(s),h=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({campaignId:i.id},i.variantId?{variantId:i.variantId}:{}),i.deliveryToken?{deliveryToken:i.deliveryToken}:{}),{placementKey:t}),this.subject()),{sessionId:this.session.getSessionId(),deviceType:"web"}),"displayed"===e?{action:"displayed",displayedAt:r}:{}),"clicked"===e?Object.assign({action:"clicked",clicked:!0,clickedAt:r},o?{elementId:o}:{}):{}),"dismissed"===e?{action:"dismissed",dismissedAt:r}:{});this.post("/v1/in-app/track",h)}reportControl(t){const i=this.cache.get(t);if(!(null==i?void 0:i.placement.isControl)||!i.placement.controlToken)return;if("granted"!==this.runtime.consent())return;const e="control:"+i.placement.controlToken;this.reported.has(e)||(this.reported.add(e),this.post("/v1/in-app/track",Object.assign(Object.assign({action:"control_viewed",controlToken:i.placement.controlToken,placementKey:t},this.subject()),{sessionId:this.session.getSessionId(),deviceType:"web",viewedAt:(new Date).toISOString()})))}subject(){const t=this.identity.getUserId();return Object.assign(Object.assign({},t?{userId:t}:{}),{anonymousId:this.identity.getAnonymousId()})}post(t,i){var e,s;const n="string"==typeof i.userId?i.userId:null;fetch(`${this.apiEndpoint}${t}`,{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(e=this.auth)||void 0===e?void 0:e.getSdkAuthHeaders(n,n?null:null!==(s=i.anonymousId)&&void 0!==s?s:null))||{}),body:JSON.stringify(i),keepalive:!0}).then(t=>{var i,e;t.ok||null===(e=(i=this.runtime).noteStatus)||void 0===e||e.call(i,t.status,null)}).catch(i=>this.logger.debug(`Placement report to ${t} failed`,i))}scanDocument(){if("undefined"==typeof document||"function"!=typeof document.querySelectorAll)return;for(const t of Array.from(this.mounts))!1===t.element.isConnected&&this.unmount(t);const t=new Set(Array.from(this.mounts).map(t=>t.element));document.querySelectorAll("[data-joryio-placement]").forEach(i=>{if(t.has(i))return;const e=i.getAttribute("data-joryio-placement");e&&this.insertPlacement(e,i)})}unmount(t){var i,e,s;this.mounts.delete(t),null===(i=t.hostObserver)||void 0===i||i.disconnect(),this.clearTrackers(t),this.clearDrawn(t),null===(s=(e=t.element).removeAttribute)||void 0===s||s.call(e,"data-joryio-placement-state")}clearTrackers(t){for(const i of t.trackers)i.cancel();t.trackers=[]}clearDrawn(t){var i;t.frameIds.forEach(t=>this.frames.delete(t)),t.frameIds=[],null===(i=t.wrapper)||void 0===i||i.remove(),t.wrapper=null,t.shown=[]}render(t){if(!this.mounts.has(t))return;t.pendingUpdate=!1,this.clearTrackers(t),this.clearDrawn(t);const i=this.toPlacement(t.key),e=this.cache.get(t.key),s=document.createElement("div");s.className="joryio-placement",s.setAttribute("data-joryio-placement-key",t.key);const n=[];for(const i of this.visibleItems(t.key)){const e=this.drawItem(t,i);e&&(s.appendChild(e),n.push(i),this.trackViewability(t,e,()=>this.report(t.key,i,"displayed")))}t.shown=n.map(t=>t.deliveryId||t.id),t.element.appendChild(s),t.wrapper=s;const r=n.length?"filled":i.isControl?"control":"empty";if(t.element.setAttribute("data-joryio-placement-state",r),n.length||(s.style.display="keep_space"===i.emptyBehavior?"":"none",i.isControl&&(null==e?void 0:e.placement.controlToken)&&this.trackViewability(t,t.element,()=>this.reportControl(t.key))),t.options.onRender)try{t.options.onRender(i,t.element)}catch(t){this.logger.error("The insertPlacement onRender callback threw; ignored:",t)}}drawItem(t,i){const e=i.content;let s=null;if("html"===(null==e?void 0:e.kind)){if(!this.runtime.allowHtml())return this.logger.warn(`Placement ${t.key}: HTML item skipped (allowHtmlJsInAppMessages is off)`),null;s=this.drawHtml(t,i,e)}else if("native"===(null==e?void 0:e.kind))s=this.drawNative(t,i,e);else if(e)return null;const n=!1===t.options.showProducts?[]:yi(i.products);if(!n.length)return s;const r=this.drawProducts(t,i,n);if(!s)return r;const o=document.createElement("div");return o.className="joryio-placement-item",o.setAttribute("data-joryio-item",i.id),o.appendChild(s),o.appendChild(r),o}drawProducts(t,i,e){const s=document.createElement("div");s.className="joryio-placement-products",s.setAttribute("data-joryio-item",i.id),s.style.cssText="display:flex;gap:8px;overflow-x:auto;box-sizing:border-box;";const n=+t.options.productCardWidth,r=Number.isFinite(n)&&n>0?n:160;for(const n of e){const e=document.createElement("div");e.className="joryio-placement-product",e.setAttribute("data-joryio-product",n.id),e.style.cssText=`flex:0 0 ${r}px;width:${r}px;box-sizing:border-box;`;const o=n.url?()=>this.buttonAction(t,i,{id:ei(n.id),action:"deep_link",url:n.url}):null,h=li(n.imageUrl);if(h){const t=document.createElement("img");t.className="joryio-placement-product-image",t.src=h,t.alt=n.title||"",t.style.cssText="display:block;width:100%;aspect-ratio:1/1;object-fit:cover;",e.appendChild(t)}if(n.title){const t=document.createElement("div");t.className="joryio-placement-product-title",t.textContent=n.title,e.appendChild(t)}if(n.price){const t=document.createElement("div");if(t.className="joryio-placement-product-price",t.textContent=n.price,n.compareAtPrice){const i=document.createElement("s");i.className="joryio-placement-product-compare",i.textContent=n.compareAtPrice,i.style.cssText="margin-inline-start:6px;opacity:0.6;",t.appendChild(i)}e.appendChild(t)}if(o&&t.options.productButtonText){const i=document.createElement("button");i.type="button",i.className="joryio-placement-product-button",i.textContent=t.options.productButtonText,i.addEventListener("click",t=>{var i;null===(i=null==t?void 0:t.stopPropagation)||void 0===i||i.call(t),o()}),e.appendChild(i)}o&&(e.setAttribute("role","link"),e.tabIndex=0,e.style.cursor="pointer",e.addEventListener("click",o),e.addEventListener("keydown",t=>{"Enter"===(null==t?void 0:t.key)&&o()})),s.appendChild(e)}return s}drawNative(t,i,e){var s;const n=document.createElement("div");n.className="joryio-placement-card",n.setAttribute("data-joryio-item",i.id),n.style.cssText="position:relative;box-sizing:border-box;";const r=li(e.imageUrl);if(r){const t=document.createElement("img");t.src=r,t.alt="",t.style.cssText="display:block;max-width:100%;height:auto;",n.appendChild(t)}if(e.title){const t=document.createElement("div");t.className="joryio-placement-title",t.textContent=e.title,n.appendChild(t)}if(e.body){const t=document.createElement("div");t.className="joryio-placement-body",t.textContent=e.body,n.appendChild(t)}if(null===(s=e.buttons)||void 0===s?void 0:s.length){const s=document.createElement("div");s.className="joryio-placement-buttons",e.buttons.forEach((e,n)=>{const r=document.createElement("button");r.type="button",r.className=0===n?"primary":"secondary",r.textContent=e.text,r.addEventListener("click",()=>this.buttonAction(t,i,e)),s.appendChild(r)}),n.appendChild(s)}if(!0===e.closeButton){const e=document.createElement("button");e.type="button",e.className="joryio-placement-close",e.setAttribute("aria-label","Close"),e.textContent="×",e.addEventListener("click",()=>this.dismissItem(t.key,i)),n.appendChild(e)}return n}buttonAction(t,i,e){var s,n;const r=t.key;if("request_push_permission"===e.action&&(null===(s=this.runtime.bridge)||void 0===s||s.requestPushPermission()),this.report(r,i,"clicked",e.id),"url"===e.action||"deep_link"===e.action){const s=li(e.url),o={placementKey:r,itemId:i.id};if(s)this.openLink(s,o,()=>window.open(s,"_blank","noopener"));else if("deep_link"===e.action&&ci(e.url)&&(t.options.onDeepLink||(null===(n=this.links)||void 0===n?void 0:n.hasHandler))){const s=e.url.trim();this.openLink(s,o,()=>{if(t.options.onDeepLink)try{t.options.onDeepLink(s,this.toItem(r,i,this.generation))}catch(t){this.logger.error("The insertPlacement onDeepLink callback threw; ignored:",t)}})}return}"dismiss"!==e.action&&"close"!==e.action||this.dismissItem(r,i)}openLink(t,i,e){this.links?this.links.route(t,"placement",i,e):e()}drawHtml(t,i,e){const s="p"+ ++this.frameSeq,n=document.createElement("iframe");return n.className="joryio-placement-frame",n.setAttribute("data-joryio-item",i.id),n.setAttribute("sandbox","allow-scripts allow-same-origin allow-popups"),n.setAttribute("title","Placement"),n.style.cssText="display:block;width:100%;height:0;border:0;",n.srcdoc=Zt(s,e.html||"",e.css||"","placement",ni),this.frames.set(s,{iframe:n,key:t.key,item:i}),t.frameIds.push(s),n}installBridge(){if("undefined"==typeof window)return;const t=t=>this.frames.get(t);window[ni]={__owner:this,setSize:(i,e,s)=>{const n=t(i);n&&Number.isFinite(s)&&s>0&&(n.iframe.style.height=Math.ceil(s)+"px")},logClick:(i,e)=>{const s=t(i);s&&ai()&&this.report(s.key,s.item,"clicked",e)},navigate:(i,e)=>{if(!t(i)||!ai())return;const s=li(e),n=t(i);s&&n&&this.openLink(s,{placementKey:n.key,itemId:n.item.id},()=>window.open(s,"_blank","noopener"))},closeMessage:i=>{const e=t(i);e&&this.dismissItem(e.key,e.item)},logConversion:()=>{},logCustomEvent:(i,e,s)=>{var n;t(i)&&e&&(null===(n=this.runtime.bridge)||void 0===n||n.logCustomEvent(e,s))},setCustomUserAttribute:(i,e,s)=>{var n;t(i)&&e&&(null===(n=this.runtime.bridge)||void 0===n||n.setCustomUserAttribute(e,s))},changeUser:(i,e)=>{var s;t(i)&&e&&(null===(s=this.runtime.bridge)||void 0===s||s.changeUser(e))},requestPushPermission:i=>{var e;t(i)&&(null===(e=this.runtime.bridge)||void 0===e||e.requestPushPermission())},submitForm:()=>Promise.resolve({ok:!1,message:"Forms are not available in this spot."})}}pageVisible(){return"undefined"==typeof document||"hidden"!==document.visibilityState}observeHost(t){if("undefined"==typeof IntersectionObserver)return;const i=new IntersectionObserver(i=>{for(const e of i)t.hostInView=e.isIntersecting,!e.isIntersecting&&t.pendingUpdate&&this.render(t)});i.observe(t.element),t.hostObserver=i}trackViewability(t,i,e){let s=null;s=fi(i,()=>{s&&t.trackers.includes(s)&&e()}),t.trackers.push(s)}installPageVisibility(){"undefined"!=typeof document&&"function"==typeof document.addEventListener&&(this.pageListener=()=>{for(const t of this.mounts)for(const i of t.trackers)this.pageVisible()?i.resume():i.pause()},document.addEventListener("visibilitychange",this.pageListener))}subjectKey(){return`${this.identity.getUserId()||""}|${this.identity.getAnonymousId()}`}loadCache(){var t;try{if("undefined"==typeof sessionStorage)return;null===(t=sessionStorage.removeItem)||void 0===t||t.call(sessionStorage,"joryio_placements_v1");const i=sessionStorage.getItem(si(this.sdkKey));if(!i)return;const e=JSON.parse(i);if(!e||e.subject!==this.subjectKey()||"object"!=typeof e.entries)return;for(const[t,i]of Object.entries(e.entries))hi(t)&&i&&i.placement&&"number"==typeof i.fetchedAt&&this.cache.set(t,{placement:this.normalize(t,i.placement),fetchedAt:i.fetchedAt,url:"string"==typeof i.url?i.url:null})}catch(t){}}persistCache(){try{if("undefined"==typeof sessionStorage)return;const t={};this.cache.forEach((i,e)=>{t[e]=i}),sessionStorage.setItem(si(this.sdkKey),JSON.stringify({subject:this.subjectKey(),entries:t}))}catch(t){}}}function yi(t){if(!Array.isArray(t))return[];const i=t=>"string"==typeof t?t:null;return t.filter(t=>!!t&&"object"==typeof t&&("string"==typeof t.id||"number"==typeof t.id)).map(t=>({id:t.id+"",title:i(t.title),price:i(t.price),compareAtPrice:i(t.compareAtPrice),discountPercent:"number"==typeof t.discountPercent?t.discountPercent:null,imageUrl:i(t.imageUrl),url:i(t.url)}))}const vi="joryio-cards-ui.min.js",mi=300,bi="viewed",gi="read",wi="clicked",ki="dismissed",Si=t=>"joryio_cards_v1_"+e(t).toString(36),ji=t=>"joryio_cards_device_v1_"+e(t).toString(36);function Oi(){const t="undefined"!=typeof window?window.__joryioCardsUi:null;return t&&1===t.version&&"function"==typeof t.mount?t:null}const Ai=()=>Date.now(),Ii=t=>"string"==typeof t?t:null;function _i(t){if(!t||"object"!=typeof t)return null;const i=Ii(t.id),e=Ii(t.deliveryToken);return i&&e?{id:i,campaignId:Ii(t.campaignId)||"",variantId:Ii(t.variantId),title:Ii(t.title),body:Ii(t.body),imageUrl:Ii(t.imageUrl),buttonText:Ii(t.buttonText),url:Ii(t.url),pinned:!0===t.pinned,createdAt:Ii(t.createdAt)||"",expiresAt:Ii(t.expiresAt),read:!0===t.read,clicked:!0===t.clicked,deliveryToken:e}:null}function Ti(t){return Array.isArray(t)?t.map(_i).filter(Boolean):[]}function $i(t,i,e){return{id:t.id,campaignId:t.campaignId,variantId:t.variantId,title:t.title,body:t.body,imageUrl:t.imageUrl,buttonText:t.buttonText,url:t.url,pinned:t.pinned,createdAt:t.createdAt,expiresAt:t.expiresAt,read:i,clicked:e}}class Di{constructor(t,i,e,s,n,r,o){this.apiEndpoint=t,this.sdkKey=i,this.identity=e,this.session=s,this.logger=n,this.runtime=r,this.auth=o,this.links=null,this.wireCards=[],this.serverUnread=0,this.nextCursor=null,this.stateScope="server",this.etag=null,this.ttlSeconds=mi,this.fetchedAt=null,this.lastNetworkAt=null,this.inflight=null,this.deferredTimer=null,this.listeners=new Set,this.mounts=new Set,this.reported=new Set,this.overlayRead=new Set,this.overlayClicked=new Set,this.overlayDismissed=new Set,this.deviceRead=new Set,this.deviceDismissed=new Set,this.generation=0,this.destroyed=!1,this.cardsUi=null,this.cardsUiLoading=null,this.removeLegacyStorage(),this.loadFeedCache(),this.loadDeviceState()}async getCards(t={}){const i=t&&"string"==typeof t.cursor&&t.cursor?t.cursor:null;return i?this.loadPage(i):(this.fresh()||await this.fetch(!1),this.view())}getUnreadCardCount(){return this.view().unreadCount}async refreshCards(){await this.fetch(!0)}onCardsUpdated(t){if("function"!=typeof t)return ti(()=>{});const i=i=>t(i);return this.listeners.add(i),ti(()=>{this.listeners.delete(i)})}markCardViewed(t){this.report(t,bi)}markCardRead(t){this.report(t,gi)}markCardClicked(t){this.report(t,wi)}dismissCard(t){this.report(t,ki)}mountCardFeed(t,i={}){if(!t||"function"!=typeof t.appendChild)return this.logger.warn("mountCardFeed: an element is required"),null;if("undefined"==typeof document)return null;for(const i of this.mounts)i.element===t&&this.unmount(i);const e={element:t,options:i||{},view:null};return this.mounts.add(e),this.fresh()||this.fetch(!1).catch(()=>{}),this.cardsUi=this.cardsUi||Oi(),this.cardsUi?this.attach(e,this.cardsUi):this.loadCardsUi().then(i=>{this.mounts.has(e)&&(i?this.attach(e,i):t.setAttribute("data-joryio-card-feed-state","unavailable"))}),{element:t,remove:()=>this.unmount(e)}}invalidate(t){if(this.generation++,this.wireCards=[],this.serverUnread=0,this.nextCursor=null,this.stateScope="server",this.etag=null,this.ttlSeconds=mi,this.fetchedAt=null,this.lastNetworkAt=null,this.inflight=null,this.deferredTimer&&clearTimeout(this.deferredTimer),this.deferredTimer=null,this.reported.clear(),this.overlayRead.clear(),this.overlayClicked.clear(),this.overlayDismissed.clear(),t){this.deviceRead.clear(),this.deviceDismissed.clear();try{"undefined"!=typeof localStorage&&localStorage.removeItem(ji(this.sdkKey))}catch(t){}}try{"undefined"!=typeof sessionStorage&&sessionStorage.removeItem(Si(this.sdkKey))}catch(t){}const i=this.listeners.size>0||this.mounts.size>0;this.notify(),i&&!this.destroyed&&this.fetch(!0).catch(()=>{})}destroy(){this.destroyed=!0;for(const t of Array.from(this.mounts))this.unmount(t);this.deferredTimer&&clearTimeout(this.deferredTimer),this.deferredTimer=null,this.listeners.clear()}fresh(){return null!==this.fetchedAt&&Ai()-this.fetchedAt<1e3*this.ttlSeconds}fetch(t){if(this.destroyed)return Promise.resolve();if(this.inflight)return t&&this.defer(),this.inflight;if(null!==this.lastNetworkAt&&3e4>Ai()-this.lastNetworkAt)return t&&this.defer(),Promise.resolve();const i=this.requestFirstPage().finally(()=>{this.inflight===i&&(this.inflight=null)});return this.inflight=i,i}defer(){var t;if(this.deferredTimer)return;const i=Math.max(0,(null!==(t=this.lastNetworkAt)&&void 0!==t?t:0)+3e4-Ai());this.deferredTimer=setTimeout(()=>{this.deferredTimer=null,this.destroyed||this.fetch(!1).catch(()=>{})},i+10)}async post(t){var i,e,s,n;const r=this.runtime.consent();if("granted"!==r||this.destroyed)return null;const h=this.generation;t||(this.lastNetworkAt=Ai());const a=this.identity.getUserId(),l=this.identity.getAnonymousId(),u=Object.assign(Object.assign(Object.assign(Object.assign({},a?{userId:a}:{}),{anonymousId:l,sessionId:this.session.getSessionId(),deviceType:"web",locale:"undefined"!=typeof navigator?navigator.language:void 0,capabilities:["cards","content.native"],trackingConsent:r,limit:20}),t?{cursor:t}:{}),!t&&this.etag?{etag:this.etag}:{}),c="undefined"!=typeof AbortController?new AbortController:null,d=setTimeout(()=>null==c?void 0:c.abort(),null!==(i=this.runtime.requestTimeoutMs)&&void 0!==i?i:1e4);try{const t=await fetch(this.apiEndpoint+"/v1/in-app/cards",Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(e=this.auth)||void 0===e?void 0:e.getSdkAuthHeaders(a,a?null:l))||{}),body:JSON.stringify(u)},c?{signal:c.signal}:{}));if(!t.ok)return null===(n=(s=this.runtime).noteStatus)||void 0===n||n.call(s,t.status,null),this.logger.debug(`Card feed request answered ${t.status}; keeping the cached feed`),null;const i=await t.json();return h!==this.generation?(this.logger.debug("Discarding a card feed answer that predates an identity or consent change"),null):i&&"object"==typeof i&&!1!==i.success?{data:i,generation:h}:(this.logger.debug("Card feed answered success: false; keeping the cached feed"),null)}catch(t){const i="AbortError"===(null==t?void 0:t.name);return this.logger.debug(i?"Card feed request timed out":"Card feed request failed",t),null}finally{clearTimeout(d)}}async requestFirstPage(){const t=await this.post(null);if(!t||t.generation!==this.generation)return;const{data:i}=t,e=Ai();this.ttlSeconds="number"==typeof i.ttlSeconds&&i.ttlSeconds>0?i.ttlSeconds:mi;let s=!1;if(!0===i.notModified&&null!==this.fetchedAt)this.fetchedAt=e;else{if(!0===i.notModified)return this.etag=null,this.lastNetworkAt=null,this.requestFirstPage();{const t=JSON.stringify(this.view());this.wireCards=Ti(i.cards),this.serverUnread="number"==typeof i.unreadCount?Math.max(0,i.unreadCount):0,this.nextCursor=Ii(i.nextCursor),this.stateScope="device"===i.stateScope?"device":"server",this.etag=Ii(i.etag),this.fetchedAt=e,s=t!==JSON.stringify(this.view())}}this.persistFeed(),s&&this.notify()}async loadPage(t){const i=await this.post(t);if(!i||i.generation!==this.generation)return Object.assign(Object.assign({},this.view()),{cards:[]});const{data:e}=i,s=Ti(e.cards),n=new Set(this.wireCards.map(t=>t.id));this.wireCards=this.wireCards.concat(s.filter(t=>!n.has(t.id))),this.nextCursor=Ii(e.nextCursor),"number"==typeof e.unreadCount&&(this.serverUnread=Math.max(0,e.unreadCount)),this.persistFeed();const r=this.view(),o=new Set(s.map(t=>t.id));return this.notify(),Object.assign(Object.assign({},r),{cards:r.cards.filter(t=>o.has(t.id))})}notify(){for(const t of this.mounts)this.render(t);if(!this.listeners.size)return;const t=this.view();for(const i of Array.from(this.listeners))try{i(t)}catch(t){this.logger.error("The onCardsUpdated callback threw; ignored:",t)}}key(t){return`${t.id}\0${t.createdAt}`}view(){const t=Ai();let i=this.serverUnread;const e=[];for(const s of this.wireCards){const n=this.key(s),r=this.overlayDismissed.has(n)||this.deviceDismissed.has(s.id),o=s.expiresAt?Date.parse(s.expiresAt):NaN,h=Number.isFinite(o)&&t>=o,a=s.clicked||this.overlayClicked.has(n),l=s.read||a||this.overlayRead.has(n)||this.deviceRead.has(s.id);!s.read&&(l||r||h)&&i--,r||h||e.push($i(s,l,a))}return{cards:e,unreadCount:Math.max(0,i),nextCursor:this.nextCursor,stateScope:this.stateScope}}report(t,i){const e="string"==typeof t?t:null==t?void 0:t.id,s="string"==typeof t?null:null==t?void 0:t.createdAt,n=this.wireCards.find(t=>t.id===e&&(null==s||t.createdAt===s));if(!n)return void this.logger.debug(`Card report ignored: ${e+""} is not in the current feed`);const r=this.key(n),o=n.read||n.clicked||this.overlayRead.has(r)||this.overlayClicked.has(r)||this.deviceRead.has(n.id);if(i===gi&&o)return void this.reported.add(`${gi}:${n.id}`);const h=`${i}:${n.id}`;if(this.reported.has(h))return;this.reported.add(h);const a=[];i===bi||this.reported.has(`${bi}:${n.id}`)||(this.reported.add(`${bi}:${n.id}`),a.push(bi)),a.push(i);const l="device"===this.stateScope;if(i!==gi&&i!==wi||(this.overlayRead.add(r),l&&this.deviceRead.add(n.id)),i===wi&&(this.overlayClicked.add(r),this.reported.add(`${gi}:${n.id}`)),i===ki&&(this.overlayDismissed.add(r),l&&this.deviceDismissed.add(n.id)),l&&i!==bi&&this.persistDeviceState(),i!==bi&&this.notify(),"granted"!==this.runtime.consent())return;const u=this.session.getSessionId();for(const t of a)this.send({deliveryToken:n.deliveryToken,action:t,sessionId:u})}send(t){var i;const e=this.identity.getUserId();fetch(this.apiEndpoint+"/v1/in-app/track",{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(i=this.auth)||void 0===i?void 0:i.getSdkAuthHeaders(e,e?null:this.identity.getAnonymousId()))||{}),body:JSON.stringify(t),keepalive:!0}).then(t=>{var i,e;t.ok||null===(e=(i=this.runtime).noteStatus)||void 0===e||e.call(i,t.status,null)}).catch(t=>this.logger.debug("Card report failed",t))}loadCardsUi(){if(this.cardsUiLoading)return this.cardsUiLoading;const t=(async()=>{var t;let i=Oi();const e=null!==(t=this.runtime.loadScript)&&void 0!==t?t:t=>R(t,"data-joryio-cards-ui");for(const t of i?[]:J(vi,this.runtime.cardsUiScriptUrl))try{if(await e(t),i=Oi(),i)break}catch(t){this.logger.debug("Joryio card feed file failed to load",t)}return i||this.logger.warn(`mountCardFeed: ${vi} could not be loaded (Content-Security-Policy script-src?)`),this.cardsUi=i,i})().catch(()=>null);return this.cardsUiLoading=t,t.then(t=>{t||(this.cardsUiLoading=null)}),t}attach(t,i){try{t.view=i.mount(t.element,t.options,this.feedHost(t)),t.view.render()}catch(t){this.logger.error("The card feed could not be drawn:",t)}}feedHost(t){return{view:()=>this.view(),generation:()=>this.generation,markCardViewed:t=>this.markCardViewed(t),markCardRead:t=>this.markCardRead(t),markCardClicked:t=>this.markCardClicked(t),dismissCard:t=>this.dismissCard(t),routeLink:(i,e,s)=>{this.mounts.has(t)&&(this.links?this.links.route(i,"card",e,s):s())},loadMore:async()=>{const i=this.nextCursor;i&&this.mounts.has(t)&&this.wireCards.length&&await this.loadPage(i)},trackViewable:fi,logger:this.logger}}unmount(t){this.mounts.delete(t);const i=t.view;t.view=null;try{null==i||i.remove()}catch(t){this.logger.debug("Card feed remove failed",t)}}render(t){var i;try{null===(i=t.view)||void 0===i||i.render()}catch(t){this.logger.error("The card feed could not be drawn:",t)}}subjectKey(){return`${this.identity.getUserId()||""}|${this.identity.getAnonymousId()}`}removeLegacyStorage(){var t,i;try{"undefined"!=typeof sessionStorage&&(null===(t=sessionStorage.removeItem)||void 0===t||t.call(sessionStorage,"joryio_cards_v1"))}catch(t){}try{"undefined"!=typeof localStorage&&(null===(i=localStorage.removeItem)||void 0===i||i.call(localStorage,"joryio_cards_device_v1"))}catch(t){}}persistFeed(){try{if("undefined"==typeof sessionStorage)return;sessionStorage.setItem(Si(this.sdkKey),JSON.stringify({subject:this.subjectKey(),fetchedAt:this.fetchedAt,etag:this.etag,ttlSeconds:this.ttlSeconds,unreadCount:this.serverUnread,nextCursor:this.nextCursor,stateScope:this.stateScope,cards:this.wireCards}))}catch(t){}}loadFeedCache(){try{if("undefined"==typeof sessionStorage)return;const t=sessionStorage.getItem(Si(this.sdkKey));if(!t)return;const i=JSON.parse(t);if(!i||i.subject!==this.subjectKey())return;this.wireCards=Ti(i.cards),this.serverUnread="number"==typeof i.unreadCount?Math.max(0,i.unreadCount):0,this.nextCursor=Ii(i.nextCursor),this.stateScope="device"===i.stateScope?"device":"server",this.etag=Ii(i.etag),this.ttlSeconds="number"==typeof i.ttlSeconds&&i.ttlSeconds>0?i.ttlSeconds:mi,this.fetchedAt="number"==typeof i.fetchedAt?i.fetchedAt:null}catch(t){this.wireCards=[]}}persistDeviceState(){const t=t=>{for(;t.size>500;)t.delete(t.values().next().value)};t(this.deviceRead),t(this.deviceDismissed);try{if("undefined"==typeof localStorage)return;localStorage.setItem(ji(this.sdkKey),JSON.stringify({anonymousId:this.identity.getAnonymousId(),read:Array.from(this.deviceRead),dismissed:Array.from(this.deviceDismissed)}))}catch(t){}}loadDeviceState(){try{if("undefined"==typeof localStorage)return;const t=localStorage.getItem(ji(this.sdkKey));if(!t)return;const i=JSON.parse(t);if(!i||i.anonymousId!==this.identity.getAnonymousId())return;for(const t of Array.isArray(i.read)?i.read:[])"string"==typeof t&&this.deviceRead.add(t);for(const t of Array.isArray(i.dismissed)?i.dismissed:[])"string"==typeof t&&this.deviceDismissed.add(t)}catch(t){this.deviceRead.clear(),this.deviceDismissed.clear()}}}class Ci{constructor(t=()=>{}){this.onHandlerError=t,this.handler=null}setHandler(t){this.handler="function"==typeof t?t:null}get hasHandler(){return null!==this.handler}route(t,i,e,s){if("string"!=typeof t)return!1;const n=t.trim(),r=ci(n);if(!li(n)&&!r)return!1;let o=!1;const h=()=>{o||(o=!0,s())},a=Object.assign(Object.assign({url:n,source:i},function(t){const i={};for(const e of["campaignId","placementKey","itemId","cardId"]){const s=t[e];"string"==typeof s&&s&&(i[e]=s)}return i}(e)),{isAppDeepLink:r,openDefault:h}),l=this.handler;if(l){let t=!1;try{t=!0===l(a)}catch(t){this.onHandlerError(t)}if(t)return!0}return h(),!0}}const Pi=t=>"jry_flags_"+e(t).toString(36),Mi=()=>Date.now();class xi{constructor(t,i,e,s,n,r,o){this.apiEndpoint=t,this.sdkKey=i,this.identity=e,this.session=s,this.logger=n,this.runtime=r,this.auth=o,this.flags={},this.etag="",this.fetchedAt=0,this.generation=0,this.inflight=null,this.inflightGeneration=0,this.listeners=new Set,this.exposed=new Set,this.pending=null,this.flushTimer=null,this.used=!1,this.onVisible=()=>{"undefined"!=typeof document&&"visible"===document.visibilityState&&this.refresh(!1)},this.load()}start(){"undefined"!=typeof document&&document.addEventListener("visibilitychange",this.onVisible),this.used&&this.refresh(!0)}use(){this.used||(this.used=!0,this.refresh(!0))}destroy(){"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.onVisible),this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null,this.listeners.clear()}onIdentityChanged(){this.generation++,this.flush();const t=Object.keys(this.flags);this.flags={},this.etag="",this.fetchedAt=0,this.save(),t.length&&this.emit(t),this.used&&this.refresh(!0)}getFlag(t,i){const e=this.read(t);return e?e.value:i}getBoolFlag(t,i){const e=this.read(t,"boolean");return e&&"boolean"==typeof e.value?e.value:i}getStringFlag(t,i){const e=this.read(t,"string");return e&&"string"==typeof e.value?e.value:i}getNumberFlag(t,i){const e=this.read(t,"number");return e&&"number"==typeof e.value?e.value:i}getJsonFlag(t,i){const e=this.read(t,"json");return e?e.value:i}getAllFlags(){if(!this.runtime.canSend())return{};this.use();const t={};for(const[i,e]of Object.entries(this.flags))t[i]=e.value;return t}async refreshFlags(){this.used=!0,await this.refresh(!0)}onFlagsUpdated(t){if("function"!=typeof t)return ti(()=>{});const i=i=>t(i);return this.listeners.add(i),this.use(),ti(()=>{this.listeners.delete(i)})}read(t,i){if(!this.runtime.canSend())return null;this.use();const e=this.flags[t];return!e||i&&e.valueType!==i?null:(this.noteExposure(t,e),e)}noteExposure(t,i){if(!i.logExposure)return;const e=`${this.session.getSessionId()}|${this.subjectKey()}|${t}|${i.variant}`;this.exposed.has(e)||(this.exposed.add(e),this.pending&&this.pending.generation===this.generation||(this.pending&&this.flush(),this.pending={body:this.requestBody(),generation:this.generation,exposures:[]}),this.pending.exposures.push({key:t,variant:i.variant}),this.flushTimer||(this.flushTimer=setTimeout(()=>this.flush(),1e3)))}flush(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null;const t=this.pending;if(this.pending=null,!t||!t.exposures.length||!this.runtime.canSend())return;const i=Object.assign(Object.assign({},t.body),{exposures:t.exposures.slice(0,100)});this.post("/v1/flags/exposures",i,!0).catch(t=>this.logger.debug("Flag exposures failed",t))}subjectKey(){return`${this.identity.getUserId()||""}|${this.identity.getAnonymousId()}`}requestBody(){var t,i,e;const s=this.identity.getUserId();return Object.assign(Object.assign({},s?{userId:s}:{}),{anonymousId:this.identity.getAnonymousId(),sessionId:this.session.getSessionId(),attributes:null!==(e=null===(i=(t=this.runtime).attributes)||void 0===i?void 0:i.call(t))&&void 0!==e?e:{},context:{platform:"web",locale:"undefined"!=typeof navigator?navigator.language:void 0,url:"undefined"!=typeof location?location.href.split("?")[0]:void 0}})}async refresh(t){if(!this.runtime.canSend()||!this.used)return;if(this.inflight){const t=this.inflightGeneration!==this.generation;return await this.inflight,void(t&&await this.refresh(!0))}if(!t&&6e4>Mi()-this.fetchedAt)return;const i=this.generation;return this.inflightGeneration=i,this.inflight=(async()=>{try{const t=await this.post("/v1/flags/evaluate",Object.assign(Object.assign({},this.requestBody()),this.etag?{etag:this.etag}:{}),!1);if(!t)return;if(i!==this.generation)return;if(this.fetchedAt=Mi(),t.notModified)return void this.save();if(!t.flags||"object"!=typeof t.flags)return;const e=t.flags,s=Object.keys(Object.assign(Object.assign({},this.flags),e)).filter(t=>{var i,s,n,r;return JSON.stringify(null===(i=this.flags[t])||void 0===i?void 0:i.value)!==JSON.stringify(null===(s=e[t])||void 0===s?void 0:s.value)||(null===(n=this.flags[t])||void 0===n?void 0:n.variant)!==(null===(r=e[t])||void 0===r?void 0:r.variant)});this.flags=e,this.etag="string"==typeof t.etag?t.etag:"",this.save(),s.length&&this.emit(s)}catch(t){this.logger.debug("Flags refresh failed; keeping the held flags",t)}finally{this.inflight=null}})(),this.inflight}async post(t,i,e){var s,n,r,h,a;const l="undefined"!=typeof AbortController?new AbortController:null,u=setTimeout(()=>null==l?void 0:l.abort(),null!==(s=this.runtime.requestTimeoutMs)&&void 0!==s?s:1e4),c="string"==typeof i.userId?i.userId:null;try{const s=await fetch(`${this.apiEndpoint}${t}`,Object.assign(Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(n=this.auth)||void 0===n?void 0:n.getSdkAuthHeaders(c,c?null:null!==(r=i.anonymousId)&&void 0!==r?r:null))||{}),body:JSON.stringify(i)},e?{keepalive:!0}:{}),l?{signal:l.signal}:{}));return s.ok?await s.json():(null===(a=(h=this.runtime).noteStatus)||void 0===a||a.call(h,s.status,null),null)}finally{clearTimeout(u)}}emit(t){for(const i of Array.from(this.listeners))try{i(t)}catch(t){this.logger.error("onFlagsUpdated callback failed",t)}}load(){try{if("undefined"==typeof localStorage)return;localStorage.removeItem("jry_flags");const t=localStorage.getItem(Pi(this.sdkKey));if(!t)return;const i=JSON.parse(t);if(!i||i.subject!==this.subjectKey()||"object"!=typeof i.flags)return;this.flags=i.flags,this.etag=i.etag||"",this.used=!0,this.fetchedAt=0}catch(t){}}save(){try{if("undefined"==typeof localStorage)return;const t={subject:this.subjectKey(),etag:this.etag,fetchedAt:this.fetchedAt,flags:this.flags};localStorage.setItem(Pi(this.sdkKey),JSON.stringify(t))}catch(t){}}}var Ki;t.SubscriptionStatus=void 0,(Ki=t.SubscriptionStatus||(t.SubscriptionStatus={})).OPTED_IN="optedIn",Ki.SUBSCRIBED="subscribed",Ki.UNSUBSCRIBED="unsubscribed";const Ni=["email","sms","whatsapp","push","viber"];class Fi{constructor(t,i,e,s,n){this.logger=t,this.network=i,this.identity=e,this.apiEndpoint=s,this.runWrite=n||((t,i)=>{this.sendOnce(i).then(i=>{i.ok||this.logger.error(`${t} failed (HTTP ${i.status||"no response"})`)},i=>this.logger.error(t+" failed:",i))})}sendOnce(t){return"subscription"===t.kind?this.network.sendSubscriptionUpdate(this.apiEndpoint,t.payload):"group"===t.kind?this.network.sendSubscriptionGroupUpdate(this.apiEndpoint,t.payload):Promise.resolve({ok:!1,status:0})}ids(){const t=this.identity.getUserId();return Object.assign(Object.assign({},t?{userId:t}:{}),{anonymousId:this.identity.getAnonymousId()})}setSubscription(i,e){if(!Ni.includes(i))return void this.logger.error(`Invalid channel: ${i}. Must be one of: ${Ni.join(", ")}`);const s=Object.values(t.SubscriptionStatus);if(!s.includes(e))return void this.logger.error(`Invalid status: ${e}. Must be one of: ${s.join(", ")}`);this.logger.debug(`Setting ${i} subscription status to ${e}`);const n=Object.assign({channel:i,status:e},this.ids());this.runWrite(`Update ${i} subscription`,{kind:"subscription",payload:n})}setSubscriptions(t){if(t&&"object"==typeof t)for(const[i,e]of Object.entries(t))void 0!==e&&this.setSubscription(i,e);else this.logger.error("setSubscriptions requires an object, e.g. { email: SubscriptionStatus.OPTED_IN }")}addToSubscriptionGroup(t,i="email"){this.updateGroup(t,i,"subscribe")}removeFromSubscriptionGroup(t,i="email"){this.updateGroup(t,i,"unsubscribe")}updateGroup(t,i,e){if("string"!=typeof t||!t)return void this.logger.error(`Cannot ${e} subscription group: groupId is required`);if(!Ni.includes(i))return void this.logger.error(`Invalid channel: ${i}. Must be one of: ${Ni.join(", ")}`);this.logger.debug(`${e} subscription group ${t} for channel ${i}`);const s=Object.assign({groupId:t,channel:i,action:e},this.ids());this.runWrite(`Subscription group ${t} ${e}`,{kind:"group",payload:s})}}const Ei={error:0,warn:1,info:2,debug:3};class Ui{constructor(t,i="error"){this.enabled=t,this.level=i}shouldLog(t){return this.enabled&&Ei[t]<=Ei[this.level]}error(...t){this.shouldLog("error")&&console.error("[Joryio SDK]",...t)}warn(...t){this.shouldLog("warn")&&console.warn("[Joryio SDK]",...t)}info(...t){this.shouldLog("info")&&console.info("[Joryio SDK]",...t)}debug(...t){this.shouldLog("debug")&&console.debug("[Joryio SDK]",...t)}setEnabled(t){this.enabled=t}setLevel(t){this.level=t}}const qi=t=>t.includes("Edg/")?"Edge":t.includes("OPR/")?"Opera":t.includes("Chrome/")?"Chrome":t.includes("Safari/")&&!t.includes("Chrome/")?"Safari":t.includes("Firefox/")?"Firefox":t.includes("MSIE")||t.includes("Trident/")?"IE":"Unknown",zi=t=>"string"==typeof t&&t.trim().length>0,Ji=t=>"number"==typeof t&&Number.isFinite(t),Ri=t=>Ji(t)?t:void 0;class Li{constructor(t,i,e){this.sdk=t,this.config={currency:i&&"string"==typeof i.currency&&i.currency||"USD"},this.logger=e||new Ui(!1)}guard(t,i,e){if(i)this.logger.warn(`ecommerce.${t}() not tracked: ${i}`);else try{e()}catch(i){this.logger.error(`ecommerce.${t}() failed:`,i)}}productProblem(t,i="product"){return t&&"object"==typeof t?zi(t.productId)?Ji(t.price)?null:i+".price must be a finite number":i+".productId is required":`a ${i} object is required`}itemsProblem(t){if(!Array.isArray(t))return"an items array is required";for(const i of t){if(null==i)continue;const t=this.productProblem(i,"item");if(t)return t}return null}cartProblem(t,i){var e;return null!==(e=this.itemsProblem(t))&&void 0!==e?e:Ji(i)?null:"cartValue must be a finite number"}textProblem(t){for(const[i,e]of Object.entries(t))if(!zi(e))return`a ${i} is required`;return null}amountsProblem(t){for(const[i,e]of Object.entries(t))if(null!=e&&!Ji(e))return i+" must be a finite number";return null}validItems(t){return t.filter(t=>t&&"object"==typeof t)}itemCount(t){return t.reduce((t,i)=>t+(Ji(i.quantity)?i.quantity:0),0)}viewProduct(t){this.guard("viewProduct",this.productProblem(t),()=>this.sdk.track("Product Viewed",{product_id:t.productId,name:t.name,price:t.price,category:t.category,brand:t.brand,variant:t.variant,variant_id:t.variantId,sku:t.sku,image_url:t.imageUrl,url:t.url,currency:this.config.currency}))}viewCategory(t,i,e){this.guard("viewCategory",this.textProblem({categoryId:t,categoryName:i}),()=>this.sdk.track("Product List Viewed",Object.assign({category_id:t,category_name:i},e&&"object"==typeof e?e:{})))}search(t,i,e){this.guard("search",this.textProblem({query:t}),()=>this.sdk.track("Products Searched",Object.assign({query:t,result_count:Ri(i)},e&&"object"==typeof e?e:{})))}addToCart(t,i){var e;const s=null!==(e=this.productProblem(t,"item"))&&void 0!==e?e:this.amountsProblem({cartValue:i});this.guard("addToCart",s,()=>this.sdk.track("Product Added",{product_id:t.productId,name:t.name,price:t.price,quantity:t.quantity,category:t.category,brand:t.brand,variant:t.variant,variant_id:t.variantId,sku:t.sku,image_url:t.imageUrl,url:t.url,item_total:Ri(t.price*t.quantity),cart_value:Ri(i),currency:this.config.currency}))}removeFromCart(t,i=1){this.guard("removeFromCart",this.productProblem(t,"item"),()=>this.sdk.track("Product Removed",{product_id:t.productId,name:t.name,price:t.price,quantity:Ji(i)?i:1,variant_id:t.variantId,sku:t.sku,currency:this.config.currency}))}cartViewed(t,i){this.guard("cartViewed",this.cartProblem(t,i),()=>{const e=this.validItems(t);this.sdk.track("Cart Viewed",{items:e.map(t=>({product_id:t.productId,name:t.name,price:t.price,quantity:t.quantity,variant_id:t.variantId,sku:t.sku})),item_count:this.itemCount(e),cart_value:Ri(i),currency:this.config.currency})})}updateCart(t,i){this.guard("updateCart",this.cartProblem(t,i),()=>{const e=this.validItems(t);this.sdk.track("Cart Updated",{items:e.map(t=>({product_id:t.productId,name:t.name,price:t.price,quantity:t.quantity,variant_id:t.variantId,sku:t.sku})),item_count:this.itemCount(e),cart_value:Ri(i),currency:this.config.currency})})}startCheckout(t,i,e){this.guard("startCheckout",this.cartProblem(t,i),()=>{const s=this.validItems(t);this.sdk.track("Checkout Started",Object.assign({items:s.map(t=>({product_id:t.productId,name:t.name,price:t.price,quantity:t.quantity,variant_id:t.variantId,sku:t.sku})),item_count:this.itemCount(s),value:Ri(i),currency:this.config.currency},e&&"object"==typeof e?e:{}))})}addPaymentInfo(t,i){this.guard("addPaymentInfo",this.textProblem({paymentMethod:t}),()=>this.sdk.track("Payment Info Entered",Object.assign({payment_method:t},i&&"object"==typeof i?i:{})))}purchase(t){var i;const e=t&&"object"==typeof t?zi(t.orderId)?Ji(t.value)?null!==(i=this.itemsProblem(t.items))&&void 0!==i?i:this.amountsProblem({shipping:t.shipping,tax:t.tax,discount:t.discount}):"order.value must be a finite number":"order.orderId is required":"an order object is required";this.guard("purchase",e,()=>{const i=this.validItems(t.items);this.sdk.track("Order Completed",{orderId:t.orderId,items:i.map(t=>({product_id:t.productId,name:t.name,price:t.price,quantity:t.quantity,category:t.category,brand:t.brand,variant_id:t.variantId,sku:t.sku})),item_count:this.itemCount(i),total:t.value,currency:t.currency||this.config.currency,shipping:Ri(t.shipping),tax:Ri(t.tax),discount:Ri(t.discount),coupon:t.coupon})})}orderFulfilled(t,i,e){this.guard("orderFulfilled",zi(t)?null:"an orderId is required",()=>this.sdk.track("Order Fulfilled",{order_id:t,tracking_number:i,carrier:e}))}orderDelivered(t){this.guard("orderDelivered",zi(t)?null:"an orderId is required",()=>this.sdk.track("Order Delivered",{order_id:t}))}orderCancelled(t,i){this.guard("orderCancelled",zi(t)?null:"an orderId is required",()=>this.sdk.track("Order Cancelled",{order_id:t,reason:i}))}orderRefunded(t,i,e){var s;const n=null!==(s=this.textProblem({orderId:t}))&&void 0!==s?s:this.amountsProblem({refundAmount:i});this.guard("orderRefunded",n,()=>this.sdk.track("Order Refunded",{order_id:t,refund_amount:Ri(i),reason:e}))}addToWishlist(t){this.guard("addToWishlist",this.productProblem(t),()=>this.sdk.track("Product Added to Wishlist",{product_id:t.productId,name:t.name,price:t.price,category:t.category,brand:t.brand,currency:this.config.currency}))}removeFromWishlist(t){this.guard("removeFromWishlist",this.productProblem(t),()=>this.sdk.track("Product Removed from Wishlist",{product_id:t.productId,name:t.name}))}shareProduct(t,i){var e;this.guard("shareProduct",null!==(e=this.productProblem(t))&&void 0!==e?e:this.textProblem({shareMethod:i}),()=>this.sdk.track("Product Shared",{product_id:t.productId,name:t.name,share_method:i}))}applyCoupon(t,i,e){var s;const n=null!==(s=this.textProblem({couponCode:t}))&&void 0!==s?s:this.amountsProblem({discountAmount:i});this.guard("applyCoupon",n,()=>this.sdk.track("Coupon Applied",{coupon_code:t,discount_amount:Ri(i),discount_type:e}))}removeCoupon(t){this.guard("removeCoupon",zi(t)?null:"a couponCode is required",()=>this.sdk.track("Coupon Removed",{coupon_code:t}))}submitReview(t,i,e){const s=zi(t)?Ji(i)?null:"rating must be a finite number":"a productId is required";this.guard("submitReview",s,()=>this.sdk.track("Product Reviewed",{product_id:t,rating:i,review_text:e}))}}function Hi(t,i,e){return new Li(t,i,e)}function Bi(t,i){var e={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&0>i.indexOf(s)&&(e[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(t);n<s.length;n++)0>i.indexOf(s[n])&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(e[s[n]]=t[s[n]])}return e}function Vi(t){switch(t.kind){case"subscription":return"unsubscribed"===t.payload.status;case"group":return"unsubscribe"===t.payload.action;case"marker":return!0===t.payload.value;default:return!1}}"function"==typeof SuppressedError&&SuppressedError;const Wi=[2e3,5e3,15e3,3e4,6e4,6e4,6e4,6e4,6e4],Xi=3e5;function Gi(t,i){const e=Wi[Math.min(Math.max(t,1),Wi.length)-1];return Math.min(Math.max(t>Wi.length?Math.min(e*Math.pow(2,t-Wi.length),Xi):e,null!=i?i:0),Xi)}function Qi(t,i){if(t.ok)return{action:"done"};if(t.softFailure)return{action:"retry",counts:!0};const e=t.status;return 0!==e&&408!==e&&429!==e&&500>e?404===e?{action:"retry",counts:!0,notFound:!0}:401===e?i.isSdkAuthError?i.ownerIsCurrentUser?{action:"retry",counts:!0}:{action:"drop",reason:"SDK authentication refused a write of a user who is no longer signed in (401)"}:{action:"hold",reason:"the SDK key was refused (401)"}:402===e?{action:"retry",counts:!1,retryAfterMs:t.retryAfterMs}:{action:"drop",reason:`refused by the server (HTTP ${e})`}:{action:"retry",counts:!1,retryAfterMs:t.retryAfterMs}}function Zi(t,i){return t>=10||i>=5}const Yi="push_registration",te="push_unregistered",ie="push_in_use",ee="push_pending_unregister",se="joryio-sdk-state";class ne{constructor(t,i,e,s,n={}){this.logger=t,this.network=i,this.identity=e,this.apiEndpoint=s,this.vapidKeyCache=null,this.prepared=null,this.lastPrepareError=null,this.unregisterInFlight=!1,this.unregisterTimer=null,this.usedThisPage=!1,this.canSend=n.canSend||(()=>!0),this.canWithdraw=n.canWithdraw||(()=>!0),this.withdrawalUserId=n.withdrawalUserId||(()=>this.identity.getUserId()),this.storage=n.storage||null,this.getDeviceId=n.getDeviceId||(()=>{}),this.onSubscribeSettled=n.onSubscribeSettled||null,this.onPrepared=n.onPrepared||null}usedOnThisPage(){return this.usedThisPage}usedEarlier(){if(!this.storage)return!1;try{return!0===this.storage.get(ie)||null!=this.storage.get(Yi)||!0===this.storage.get(te)}catch(t){return!1}}markUsed(){var t;this.usedThisPage=!0;try{null===(t=this.storage)||void 0===t||t.set(ie,!0)}catch(t){}}isSupported(){return"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}getPermissionState(){if(!this.isSupported())return"unavailable";const t=Notification.permission;return"granted"===t||"denied"===t?t:"notDetermined"}async getExistingSubscription(t){if(!this.isSupported())return null;try{const i=await navigator.serviceWorker.getRegistration((null==t?void 0:t.scope)||"/");return i?await i.pushManager.getSubscription():null}catch(t){return this.logger.warn("Could not read the push subscription:",t),null}}async syncExistingSubscription(t=!1,i){var e,s;try{if(await this.sendPendingUnregister(),!this.canSend())return;if(!0===(null===(e=this.storage)||void 0===e?void 0:e.get(te)))return;if(!this.isSupported()||"granted"!==Notification.permission)return;const n=await navigator.serviceWorker.getRegistration((null==i?void 0:i.scope)||"/");if(!n)return;let r=await n.pushManager.getSubscription();const o=null===(s=this.storage)||void 0===s?void 0:s.get(Yi),h=this.identity.getUserId(),a=this.identity.getAnonymousId(),l=!o||Date.now()-(o.at||0)>864e5,u=!r||!o||o.endpoint!==r.endpoint||o.userId!==h||o.anonymousId!==a;if(!t&&!l&&!u)return;const c=await this.fetchVapidPublicKey();if(!c)return;r&&!this.subscriptionKeyMatches(r,c)&&(this.logger.info("VAPID key changed - re-subscribing this browser"),await r.unsubscribe().catch(()=>!1),r=null),r||(r=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:re(c)})),await this.registerWithBackend(r)}catch(t){this.logger.warn("Could not refresh the push subscription:",t)}}async setTrackingOptedOut(t){try{if("undefined"==typeof caches)return;if(t){const t=await caches.open(se);await t.put("/__joryio/tracking-opted-out",new Response("1"))}else await caches.delete(se)}catch(t){this.logger.debug("Could not record the opt-out for the service worker:",t)}}async prepare(t){var i;if(t=t||{},!this.isSupported())return this.lastPrepareError="unsupported",!1;if(this.prepared)return this.lastPrepareError=null,!0;const e=await this.fetchVapidPublicKey();if(!e)return this.lastPrepareError="no-key",this.logger.error("Web push is not enabled for this workspace"),!1;try{const s=await navigator.serviceWorker.register(t.swPath||"/joryio-sw.js",{scope:t.scope||"/"});await navigator.serviceWorker.ready,this.prepared={registration:s,publicKey:e},this.lastPrepareError=null,this.markUsed();try{null===(i=this.onPrepared)||void 0===i||i.call(this)}catch(t){this.logger.warn("Push permission report failed:",t)}return!0}catch(t){return this.lastPrepareError="sw-failed",this.logger.error("Service worker registration failed:",t),!1}}async subscribe(t){var i;try{return await this.subscribeOnce(t)}finally{this.markUsed();try{null===(i=this.onSubscribeSettled)||void 0===i||i.call(this)}catch(t){this.logger.warn("Push permission report failed:",t)}}}async subscribeOnce(t){var i;if(t=t||{},!this.isSupported())return console.warn("[Joryio SDK] Push not enabled: this browser/context does not support web push (needs HTTPS, a service worker, and PushManager - Safari < 16.4 and insecure origins are excluded)."),null;this.prepared||await this.prepare(t);const e=this.prepared;if(!e){this.logger.error("Web push is not enabled for this workspace");const i=t.swPath||"/joryio-sw.js";return"no-key"===this.lastPrepareError?console.warn("[Joryio SDK] Push not enabled: the server returned no VAPID key - web push is not configured for this app. Enable web push for THIS app (the one your SDK key belongs to) in the dashboard."):"sw-failed"===this.lastPrepareError?console.warn(`[Joryio SDK] Push not enabled: the service worker failed to register. The VAPID key was fetched OK, so the problem is ${i}: make sure it is hosted on your origin AND its importScripts() points at https://sdk.joryio.com/web/1/joryio-sw.js (a dead URL makes the worker's install throw and registration fail).`):console.warn("[Joryio SDK] Push not enabled: could not prepare web push."),null}null===(i=this.storage)||void 0===i||i.remove(te);try{const t=await e.registration.pushManager.getSubscription();if(t&&this.subscriptionKeyMatches(t,e.publicKey))return await this.registerWithBackend(t).catch(t=>this.logRegisterFailure(t)),t;t&&(this.logger.info("VAPID key changed - re-subscribing this browser"),await t.unsubscribe().catch(()=>{}));const i=await e.registration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:re(e.publicKey)});return await this.sendPendingUnregister(),await this.registerWithBackend(i).catch(t=>this.logRegisterFailure(t)),this.logger.info("Web push subscribed"),i}catch(t){return"NotAllowedError"===(null==t?void 0:t.name)?(this.logger.info("User denied push permission"),console.warn("[Joryio SDK] Push not enabled: notification permission is denied. The browser will not re-prompt - the user must re-allow notifications for this site in browser settings.")):(this.logger.error("pushManager.subscribe failed:",t),console.warn("[Joryio SDK] Push not enabled: pushManager.subscribe failed:",t)),null}}async unsubscribe(t){var i,e;const s={userId:this.withdrawalUserId()||void 0,anonymousId:this.identity.getAnonymousId()};try{if(null===(i=this.storage)||void 0===i||i.set(te,!0),null===(e=this.storage)||void 0===e||e.remove(Yi),!this.isSupported())return!1;const n=await navigator.serviceWorker.getRegistration((null==t?void 0:t.scope)||"/");if(!n)return!1;const r=await n.pushManager.getSubscription();if(!r)return!0;const o=r.endpoint,h=await r.unsubscribe().catch(()=>!1),a=this.pendingUnregisters().filter(t=>t.endpoint!==o);return a.push(Object.assign({endpoint:o},s)),this.storePendingUnregisters(a),await this.sendPendingUnregister(),h}catch(t){return this.logger.warn("Push unsubscribe failed:",t),!1}}async forget(){await this.unsubscribe(),this.prepared=null}pendingUnregisterUsers(){return this.pendingUnregisters().map(t=>t.userId).filter(t=>"string"==typeof t&&!!t)}pendingUnregisters(){var t;const i=null===(t=this.storage)||void 0===t?void 0:t.get(ee);return(Array.isArray(i)?i:i?[i]:[]).filter(t=>t&&"string"==typeof t.endpoint&&t.endpoint&&"string"==typeof t.anonymousId)}storePendingUnregisters(t){var i,e;t.length?null===(i=this.storage)||void 0===i||i.set(ee,t.slice(-20)):null===(e=this.storage)||void 0===e||e.remove(ee)}retryPendingUnregister(){this.sendPendingUnregister().catch(()=>{})}async sendPendingUnregister(){if(!this.unregisterInFlight&&this.canWithdraw()&&("undefined"==typeof navigator||!1!==navigator.onLine)){null!==this.unregisterTimer&&(clearTimeout(this.unregisterTimer),this.unregisterTimer=null),this.unregisterInFlight=!0;try{for(;;){const[t]=this.pendingUnregisters();if(!t)return;const{attempts:i=0,notFoundAttempts:e=0,failures:s=0}=t,n=Bi(t,["attempts","notFoundAttempts","failures"]),r=await this.network.request({url:this.apiEndpoint+"/v1/push/unregister",method:"POST",body:Object.assign({platform:"web"},n),subjectUserId:n.userId||null}),o=Qi(r,{isSdkAuthError:this.network.isSdkAuthError(r.status,r.data),ownerIsCurrentUser:(n.userId||null)===this.withdrawalUserId()}),h=this.pendingUnregisters().filter(i=>i.endpoint!==t.endpoint);if("done"===o.action||"drop"===o.action){"drop"===o.action&&this.logger.error("Push unregister dropped: "+o.reason),this.storePendingUnregisters(h);continue}if("hold"===o.action)return;const a=Object.assign(Object.assign({},t),{failures:s+1,attempts:i+(o.counts&&!o.notFound?1:0),notFoundAttempts:e+(o.counts&&o.notFound?1:0)});if(!Zi(a.attempts,a.notFoundAttempts))return this.storePendingUnregisters([a,...h]),void(this.unregisterTimer=setTimeout(()=>{this.unregisterTimer=null,this.sendPendingUnregister().catch(()=>{})},Gi(a.failures,o.retryAfterMs)));this.logger.error("Push unregister failed too many times; dropping it"),this.storePendingUnregisters(h)}}catch(t){this.logger.warn("Failed to notify backend about unsubscribe:",t)}finally{this.unregisterInFlight=!1}}}destroy(){null!==this.unregisterTimer&&clearTimeout(this.unregisterTimer),this.unregisterTimer=null}logRegisterFailure(t){this.logger.warn("This browser is subscribed, but registering it with Joryio failed; it is retried on the next page load:",t)}subscriptionKeyMatches(t,i){var e;try{const s=null===(e=t.options)||void 0===e?void 0:e.applicationServerKey;if(!s)return!0;const n=new Uint8Array(s),r=re(i);if(n.byteLength!==r.byteLength)return!1;for(let t=0;t<n.byteLength;t++)if(n[t]!==r[t])return!1;return!0}catch(t){return!0}}async fetchVapidPublicKey(){var t,i;if(this.vapidKeyCache)return this.vapidKeyCache;try{const e=await this.network.request({url:this.apiEndpoint+"/v1/push/vapid-public-key",method:"GET"});return e.ok&&(null===(t=e.data)||void 0===t?void 0:t.enabled)&&(null===(i=e.data)||void 0===i?void 0:i.publicKey)?(this.vapidKeyCache=e.data.publicKey,this.vapidKeyCache):null}catch(t){return this.logger.error("Failed to fetch VAPID public key:",t),null}}async registerWithBackend(t){var i,e,s,n;if(!this.canSend())return void this.logger.debug("Push subscription not registered: tracking is off or consent is pending");const r=t.toJSON(),o=this.getDeviceId(),h=Object.assign({platform:"web",subscription:{endpoint:t.endpoint,keys:{p256dh:(null===(i=r.keys)||void 0===i?void 0:i.p256dh)||"",auth:(null===(e=r.keys)||void 0===e?void 0:e.auth)||""}},userId:this.identity.getUserId()||void 0,anonymousId:this.identity.getAnonymousId()},o?{deviceId:o}:{}),a=this.pendingUnregisters();a.some(i=>i.endpoint===t.endpoint)&&this.storePendingUnregisters(a.filter(i=>i.endpoint!==t.endpoint));const l=await this.network.request({url:this.apiEndpoint+"/v1/push/register",method:"POST",body:h,subjectUserId:h.userId||null});if(!l.ok)throw Error("Failed to register subscription: "+(l.error||l.status));null===(s=this.storage)||void 0===s||s.set(Yi,{endpoint:t.endpoint,userId:null!==(n=h.userId)&&void 0!==n?n:null,anonymousId:h.anonymousId,at:Date.now()})}}function re(t){const i=(t+"=".repeat((4-t.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),e=atob(i),s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s}const oe="write_outbox",he="deferred_writes",ae="write_outbox_removed";function le(t){const i=t.payload;return Object.assign({anonymousId:i.anonymousId},i.userId?{userId:i.userId}:{})}function ue(t){switch(t.kind){case"subscription":return"subscription:"+t.payload.channel;case"group":return`group:${t.payload.groupId}:${t.payload.channel}`;case"marker":return"marker";default:return null}}function ce(t){switch(t.kind){case"alias":return"addAlias";case"subscription":return`Update ${t.payload.channel} subscription`;case"group":return`Subscription group ${t.payload.groupId} ${t.payload.action}`;case"marker":return"The tracking_opted_out marker"}}function de(){return"undefined"!=typeof navigator&&!1===navigator.onLine}function fe(t){return!(!t||"object"!=typeof t||"alias"!==t.kind&&"subscription"!==t.kind&&"group"!==t.kind&&"marker"!==t.kind||!t.payload||"object"!=typeof t.payload||"string"!=typeof t.payload.anonymousId)}function pe(t){if(!t||!fe(t.record))return null;const i=t=>Number.isInteger(t)&&t>=0?t:0;return{id:"string"==typeof t.id?t.id:X(),record:t.record,withdrawal:Vi(t.record),attempts:i(t.attempts),notFoundAttempts:i(t.notFoundAttempts),failures:i(t.failures),notBefore:0,createdAt:"number"==typeof t.createdAt&&Number.isFinite(t.createdAt)?t.createdAt:0}}class ye{constructor(t){this.deps=t,this.entries=[],this.inFlight=null,this.timer=null,this.stopped=!1,this.handedOffAt=new Map,this.destroyed=!1,this.knownIds=new Set,this.load()}enqueue(t){if(this.destroyed)return;const i={id:X(),record:t,withdrawal:Vi(t),attempts:0,notFoundAttempts:0,failures:0,notBefore:0,createdAt:Date.now()};this.knownIds.add(i.id);const e=ue(t);e&&(this.entries=this.entries.filter(i=>i===this.inFlight||ue(i.record)!==e||!this.sameOwner(i.record,t))),this.entries.push(i),this.trim(),this.persist(),this.kick()}discardNonWithdrawals(){this.entries=this.entries.filter(t=>t.withdrawal),this.persist({discardNonWithdrawals:!0})}persistNow(){this.persist()}find(t){return this.entries.find(t)}findLast(t){for(let i=this.entries.length-1;i>=0;i--)if(t(this.entries[i]))return this.entries[i]}cancel(t){const i=this.entries.length;this.entries=this.entries.filter(i=>i===this.inFlight||!t(i)),this.entries.length!==i&&this.persist()}pinOwner(t,i){let e=!1;for(const s of this.entries){const n=s.record.payload;n.anonymousId!==t||n.userId||(s.record=Object.assign(Object.assign({},s.record),{payload:Object.assign(Object.assign({},n),{userId:i})}),e=!0)}e&&this.persist()}isInFlight(t){return this.inFlight===t}size(){return this.entries.length}records(){return this.entries.map(t=>t.record)}kick(){if(this.destroyed||this.stopped||this.inFlight)return;if(null!==this.timer&&(clearTimeout(this.timer),this.timer=null),de())return;const t=Date.now(),i=new Set;let e=1/0,s=null;for(const n of[...this.entries]){const r=this.blockKey(n);if(i.has(r))continue;const o=this.safeGate(n);if("drop"!==o)if("hold"!==o){if(n.notBefore<=t){s=n;break}i.add(r),e=Math.min(e,n.notBefore)}else i.add(r);else this.remove(n)}s?this.run(s):1/0>e&&(this.timer=setTimeout(()=>{this.timer=null,this.kick()},Math.max(0,e-t)))}handOffAtUnload(t){let i=0;if(!this.deps.keepalive||this.destroyed||this.stopped||de())return i;this.persist();const e=Date.now(),s=new Set;this.inFlight&&s.add(this.blockKey(this.inFlight));for(const n of[...this.entries]){const r=this.blockKey(n);if(s.has(r))continue;if(n!==this.inFlight&&this.removedElsewhere(n)){this.deps.logger.debug(ce(n.record)+" not handed off: another tab settled or replaced it");const t=this.entries.indexOf(n);0>t||this.entries.splice(t,1);continue}if(s.add(r),n===this.inFlight||"send"!==this.safeGate(n))continue;const o=this.handedOffAt.get(n.id);if(void 0===o||e-o>=1e4)try{const s=this.deps.keepalive(n,this.deps.resolveOwner(le(n.record)));if(null===s)break;if(this.handedOffAt.set(n.id,e),i+=s,i>=t)break}catch(t){break}}return this.persist(),i}destroy(){this.destroyed=!0,null!==this.timer&&clearTimeout(this.timer),this.timer=null}async run(t){this.inFlight=t;const i=ce(t.record);try{if(await this.deps.beforeSend(t).catch(()=>{}),!this.entries.includes(t))return;const e=this.safeGate(t);if("drop"===e)return void this.remove(t);if("hold"===e)return;if(this.removedElsewhere(t))return this.deps.logger.debug(i+" not sent: another tab settled or replaced it"),void this.remove(t);const s=this.deps.resolveOwner(le(t.record)),n=await this.deps.send(t,s);if(!this.entries.includes(t))return;const r=Qi(n,{isSdkAuthError:this.deps.isSdkAuthError(n.status,n.data),ownerIsCurrentUser:this.deps.ownerIsCurrentUser(s)});switch(r.action){case"done":return void this.settle(t,"done");case"drop":return this.deps.logger.error(`${i} dropped: ${r.reason}`),void this.settle(t,"drop");case"hold":return this.deps.logger.error(`${i} not sent: ${r.reason}; kept for the next page view`),void(this.stopped=!0);case"retry":return this.hasNewerOfSameSubject(t)?void this.remove(t):(t.failures++,r.counts&&(r.notFound?t.notFoundAttempts++:t.attempts++),Zi(t.attempts,t.notFoundAttempts)?(this.deps.logger.error(`${i} failed (HTTP ${n.status||"no response"}) too many times; dropping it`),void this.settle(t,"drop")):(t.notBefore=Date.now()+Gi(t.failures,r.retryAfterMs),void this.deps.logger.debug(`${i} failed with HTTP ${n.status||"no response"}; retrying`)))}}catch(e){this.deps.logger.error(i+" failed:",e),t.failures++,t.notBefore=Date.now()+Gi(t.failures)}finally{this.inFlight===t&&(this.inFlight=null),this.persist(),this.kick()}}safeGate(t){try{return this.deps.gate(t)}catch(t){return"hold"}}settle(t,i){var e,s;this.remove(t);try{null===(s=(e=this.deps).onSettled)||void 0===s||s.call(e,t,i)}catch(t){this.deps.logger.error("Outbox bookkeeping failed:",t)}}remove(t){const i=this.entries.indexOf(t);0>i||(this.entries.splice(i,1),this.persist())}hasNewerOfSameSubject(t){const i=ue(t.record);if(!i)return!1;const e=this.entries.indexOf(t);return this.entries.slice(e+1).some(e=>ue(e.record)===i&&this.sameOwner(e.record,t.record))}effectiveUser(t){if(t.userId)return t.userId;const i=this.deps.currentIdentity();return t.anonymousId===i.anonymousId?i.userId:null}sameOwner(t,i){const e=le(t),s=le(i);return e.anonymousId===s.anonymousId&&this.effectiveUser(e)===this.effectiveUser(s)}blockKey(t){var i;const e=le(t.record);return`${null!==(i=ue(t.record))&&void 0!==i?i:`${t.record.kind}:${t.id}`}|${e.anonymousId}`}trim(){for(;this.entries.length>200;){let t=this.entries.findIndex(t=>!t.withdrawal&&t!==this.inFlight);if(0>t&&(t=this.entries.findIndex(t=>t!==this.inFlight)),0>t)break;const[i]=this.entries.splice(t,1);this.deps.logger.warn(`Too many profile writes waiting; dropped the oldest (${ce(i.record)})`)}}persist(t={}){try{const i=this.deps.storage.get(oe),e=Array.isArray(i)?i.filter(t=>t&&"string"==typeof t.id).map(t=>t.id):[],s=this.readRemoved();this.entries=this.entries.filter(t=>t===this.inFlight||!s.has(t.id));let n=this.foreignStoredEntries(i).filter(t=>!s.has(t.id));t.discardNonWithdrawals&&(n=n.filter(t=>t.withdrawal));let r=this.entries;if(n.length){const t=[...this.entries,...n].sort((t,i)=>t.createdAt-i.createdAt),i=(i,e)=>{const s=ue(i.record);return!!s&&i!==this.inFlight&&t.slice(e+1).some(t=>ue(t.record)===s&&this.sameOwner(t.record,i.record))};for(r=t.filter((t,e)=>!i(t,e));r.length>200;){let t=r.findIndex(t=>!t.withdrawal&&t!==this.inFlight);if(0>t&&(t=r.findIndex(t=>t!==this.inFlight)),0>t)break;this.deps.logger.warn(`Too many profile writes waiting; dropped the oldest (${ce(r[t].record)})`),r=r.filter((i,e)=>e!==t)}this.entries=this.entries.filter(t=>t===this.inFlight||r.includes(t))}const o=r.filter(t=>!s.has(t.id));this.write(o);const h=new Set(o.map(t=>t.id)),a=e.filter(t=>!h.has(t)&&!s.has(t));a.length&&this.writeRemoved(s,a)}catch(t){this.deps.logger.error("Failed to store pending profile writes:",t)}}removedElsewhere(t){try{if(this.readRemoved().has(t.id))return!0;const i=ue(t.record);if(!i)return!1;const e=this.deps.storage.get(oe);return!!Array.isArray(e)&&e.some(e=>e&&e.id!==t.id&&fe(e.record)&&"number"==typeof e.createdAt&&e.createdAt>t.createdAt&&ue(e.record)===i&&this.sameOwner(e.record,t.record))}catch(t){return!1}}readRemoved(){const t=new Map,i=this.deps.storage.get(ae);if(!Array.isArray(i))return t;const e=Date.now();for(const s of i)Array.isArray(s)&&"string"==typeof s[0]&&"number"==typeof s[1]&&(e-s[1]>2592e6||t.set(s[0],s[1]));return t}writeRemoved(t,i){const e=Date.now(),s=[...t.entries(),...i.map(t=>[t,e])];this.deps.storage.set(ae,s.slice(-500))}write(t){t.length?this.deps.storage.set(oe,t.map(t=>({id:t.id,record:t.record,attempts:t.attempts,notFoundAttempts:t.notFoundAttempts,failures:t.failures,createdAt:t.createdAt}))):this.deps.storage.remove(oe)}foreignStoredEntries(t){if(!Array.isArray(t))return[];const i=[];for(const e of t){if(!e||"string"!=typeof e.id||this.knownIds.has(e.id)||!fe(e.record))continue;const t=pe(e);t&&i.push(t)}return i}load(){const t=this.deps.storage.get(oe);if(Array.isArray(t))for(const i of t){const t=pe(i);t&&(this.entries.push(t),this.knownIds.add(t.id))}const i=this.deps.storage.get(he);if(Array.isArray(i)){for(const t of i){if(!fe(t))continue;const i={id:X(),record:t,withdrawal:Vi(t),attempts:0,notFoundAttempts:0,failures:0,notBefore:0,createdAt:0};this.entries.push(i),this.knownIds.add(i.id)}this.deps.storage.remove(he),this.trim(),this.persist()}else this.entries.length>200&&(this.trim(),this.persist())}}function ve(t){const i=[],e=(t,s)=>{switch(typeof t){case"number":return Number.isFinite(t)?null:"a non-finite number (NaN or Infinity)";case"bigint":return"a BigInt";case"function":return"a function";case"symbol":return"a symbol";case"object":if(null===t)return null;if(s>100)return"a value nested deeper than 100 levels";if("function"==typeof t.toJSON)try{return JSON.stringify(t),null}catch(t){return"a value that cannot be serialized"}if(i.includes(t))return"a circular reference";i.push(t);try{const i=Array.isArray(t)?t:Object.values(t);for(const t of i){const i=e(t,s+1);if(i)return i}}finally{i.pop()}return null;default:return null}};try{return e(t,1)}catch(t){return"a value that cannot be serialized"}}function me(t,i){const e={};for(const s of Object.keys(t)){const n=ve(t[s]);n?i(s,n):e[s]=t[s]}return e}const be=/^[A-Za-z0-9._:-]{8,255}$/,ge=/^[0-9a-f]{24}$/,we="signed_in_anonymous_ids",ke="jr_t",Se=/^[A-Za-z0-9_-]{16,512}$/;function je(t){if("string"!=typeof t||!t.includes(ke+"="))return null;try{const i="undefined"!=typeof window&&window.location?window.location.href:"https://x.invalid/",e=new URL(t,i).searchParams.get(ke);return e&&Se.test(e)?e:null}catch(t){return null}}function Oe(t){try{const i=new URL(t);return i.searchParams.has(ke)?(i.searchParams.delete(ke),i.toString()):null}catch(t){return null}}const Ae="tracking_opted_out",Ie="tracking_consent",_e="tracking_consent_granted_at",Te="tracking_consent_denied_at",$e="tracking_opted_out_at",De="tracking_opt_in_at",Ce="reported_tracking_opted_out",Pe="tracking_opted_out_marker_given_up",Me="session_start_sent",xe="withdrawal_user_id",Ke="retired_sdk_auth_tokens",Ne=[_t,Tt,$t,oe,ee,"held_attribute_writes"];function Fe(t,i,e=0){if(t&&"object"==typeof t&&6>=e)if(Array.isArray(t))for(const s of t)Fe(s,i,e+1);else for(const[s,n]of Object.entries(t))"userId"===s&&"string"==typeof n&&n?i.add(n):Fe(n,i,e+1)}const Ee=new WeakMap;function Ue(t,i,e){const s=t,n=s.dataGate;s.dataGate=new Set([...n,...i]);try{e()}finally{s.dataGate=n}}const qe="anonymous_id",ze="user_id",Je=["jry_sdk_ios_","jry_sdk_android_"],Re="tracking_opted_out",Le="held_attribute_writes",He="joryio_reported_push_permission",Be="push_permission";class Ve{constructor(t,i){if(this.attributeFlushTimer=null,this.attributeFlushInFlight=!1,this.attributeFlushAgain=!1,this.attributeGeneration=0,this.attributeFailures=0,this.links=new Ci(t=>{var i;return null===(i=this.logger)||void 0===i?void 0:i.error("Your link handler threw; the link opens as without one:",t)}),this.editor=null,this.t=null,this.isInitialized=!1,this.isOptedOut=!1,this.disabled=!1,this.consentPending=!1,this.userOptedOut=!1,this.dntEnabled=!1,this.trackingConsent="granted",this.lastTrackedUrl=null,this.boundHandlePageUnload=null,this.boundHandleOnline=null,this.boundHandleStorage=null,this.withdrawalUserId=null,this.optedOutAt=0,this.consentDeniedAt=0,this.lastDecisionStamp=0,this.awaitingSessionOf=null,this.pruneTimer=null,this.pendingLinkToken=null,this.sentLinkTokens=new Set,this.dataGate=new Set,this.inflightSessionStartAtClear=null,Ve.instance)return console.warn("[Joryio] SDK already initialized. Returning existing instance."),Ve.instance;const e=t&&"object"==typeof t&&"string"==typeof t.sdkKey&&t.sdkKey?t.sdkKey.startsWith("jry_sdk_")?Je.some(i=>t.sdkKey.startsWith(i))?"this is a mobile app key - use the web SDK key (jry_sdk_web_...) from Settings -> Apps":null:"invalid SDK key format, expected jry_sdk_*":"sdkKey is required";e&&(console.error(`[Joryio] SDK not started: ${e}. Calls on this instance are ignored.`),this.disabled=!0),this.config=function(t){var i,e,s,n,r,o,l,u,c,d,f,p,y,v,m,b,g,w,k,S,j;!function(t){const i=t;for(const[t,e]of Object.entries(a))void 0!==i[t]&&console.warn(`[Joryio] \`${t}\` must be nested under \`${e}\`, not passed at the top level - as written it is IGNORED. Use: { ${e}: { ${t}: ${JSON.stringify(i[t])} } }`);void 0!==i.disablePlugins&&console.warn("[Joryio] `disablePlugins` was removed in 1.3.0 and is ignored - leave a plugin out of `plugins` instead.")}(t);const O={enabled:!1!==(null===(i=t.inApp)||void 0===i?void 0:i.enabled),evaluationMode:"session-start-only"===(null===(e=t.inApp)||void 0===e?void 0:e.evaluationMode)?"session-start-only":"differential-sync",syncInterval:(null===(s=t.inApp)||void 0===s?void 0:s.syncInterval)&&t.inApp.syncInterval>0?Math.max(3e4,t.inApp.syncInterval):0,displayOptions:{defaultPosition:(null===(r=null===(n=t.inApp)||void 0===n?void 0:n.displayOptions)||void 0===r?void 0:r.defaultPosition)||"center",defaultAnimation:(null===(l=null===(o=t.inApp)||void 0===o?void 0:o.displayOptions)||void 0===l?void 0:l.defaultAnimation)||"fade",backdropColor:(null===(c=null===(u=t.inApp)||void 0===u?void 0:u.displayOptions)||void 0===c?void 0:c.backdropColor)||"rgba(0, 0, 0, 0.5)",closeButtonColor:(null===(f=null===(d=t.inApp)||void 0===d?void 0:d.displayOptions)||void 0===f?void 0:f.closeButtonColor)||void 0,zIndex:(null===(y=null===(p=t.inApp)||void 0===p?void 0:p.displayOptions)||void 0===y?void 0:y.zIndex)||999999},allowHtmlJsInAppMessages:!0===(null===(v=t.inApp)||void 0===v?void 0:v.allowHtmlJsInAppMessages),autoMountPlacements:!1!==(null===(m=t.inApp)||void 0===m?void 0:m.autoMountPlacements),onMessageDisplay:(null===(b=t.inApp)||void 0===b?void 0:b.onMessageDisplay)||(()=>{}),onMessageClick:(null===(g=t.inApp)||void 0===g?void 0:g.onMessageClick)||(()=>{}),onMessageDismiss:(null===(w=t.inApp)||void 0===w?void 0:w.onMessageDismiss)||(()=>{})};return{sdkKey:t.sdkKey,apiEndpoint:h(t.apiEndpoint),userId:t.userId,anonymousId:t.anonymousId||"",batchSize:t.batchSize||50,batchFlushInterval:"number"==typeof t.batchFlushInterval&&t.batchFlushInterval>0?Math.max(1e3,t.batchFlushInterval):5e3,sendImmediately:t.sendImmediately||!1,maxQueueSize:t.maxQueueSize||1e3,sessionTimeout:t.sessionTimeout||18e5,trackSessionStart:!1!==t.trackSessionStart,trackPageViews:!0===t.trackPageViews,captureUTM:!1!==t.captureUTM,resetSessionOnNewCampaign:t.resetSessionOnNewCampaign||!1,trackPageProperties:!1!==t.trackPageProperties,trackDeviceProperties:!1!==t.trackDeviceProperties,inApp:O,pageContext:{pageVariables:Array.isArray(null===(k=t.pageContext)||void 0===k?void 0:k.pageVariables)?t.pageContext.pageVariables.filter(t=>"string"==typeof t):[],dataLayerVariables:Array.isArray(null===(S=t.pageContext)||void 0===S?void 0:S.dataLayerVariables)?t.pageContext.dataLayerVariables.filter(t=>"string"==typeof t):[],dataLayerName:"string"==typeof(null===(j=t.pageContext)||void 0===j?void 0:j.dataLayerName)&&/^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/.test(t.pageContext.dataLayerName)?t.pageContext.dataLayerName:"dataLayer"},pageEdits:!1!==t.pageEdits,editorScriptUrl:"string"==typeof t.editorScriptUrl&&/^https:\/\//i.test(t.editorScriptUrl)?t.editorScriptUrl:void 0,cardsUiScriptUrl:"string"==typeof t.cardsUiScriptUrl&&/^https:\/\//i.test(t.cardsUiScriptUrl)?t.cardsUiScriptUrl:void 0,webPush:!0===t.webPush||!1!==t.webPush&&void 0,persistQueue:!1!==t.persistQueue,maxRetries:"number"!=typeof t.maxRetries||0>t.maxRetries?3:Math.floor(t.maxRetries),retryBackoffMs:t.retryBackoffMs||1e3,requestTimeout:t.requestTimeout&&t.requestTimeout>0?t.requestTimeout:1e4,respectDoNotTrack:!1!==t.respectDoNotTrack,optOut:!0===t.optOut,trackingConsent:"granted"===t.trackingConsent||"denied"===t.trackingConsent||"pending"===t.trackingConsent?t.trackingConsent:void 0,enableSdkAuthentication:!0===t.enableSdkAuthentication,sdkAuthenticationToken:t.sdkAuthenticationToken,storefrontIdentityToken:"string"==typeof t.storefrontIdentityToken&&t.storefrontIdentityToken?t.storefrontIdentityToken:void 0,storefrontIdentityTokenProvider:"function"==typeof t.storefrontIdentityTokenProvider?t.storefrontIdentityTokenProvider:void 0,enableDebug:t.enableDebug||!1,logLevel:t.logLevel||(t.enableDebug?"debug":"error"),loggingEnabled:!0===t.enableDebug||!!t.logLevel,plugins:t.plugins||[]}}(e?Object.assign(Object.assign({},t&&"object"==typeof t?t:{}),{sdkKey:"jry_sdk_invalid",optOut:!1}):t),this.logger=new Ui(this.config.loggingEnabled,this.config.logLevel),this.logger.info("Initializing Joryio SDK v"+s),this.storage=new W(this.config.sdkKey,this.logger),this.dntEnabled=this.config.respectDoNotTrack&&this.isDoNotTrackEnabled(),this.dntEnabled&&this.logger.warn("Do Not Track is enabled, SDK will not track events"),this.config.optOut&&this.writeOptOut(),this.userOptedOut=this.config.optOut||this.storedOptOut(),this.userOptedOut&&(this.optedOutAt=this.storedStamp($e)),this.trackingConsent=this.initialConsent(this.config.trackingConsent);const n=function(){if("undefined"==typeof window||!window.location)return null;const t=window.location.href,i=je(t),e=Oe(t);if(e)try{window.history&&"function"==typeof window.history.replaceState&&window.history.replaceState(window.history.state,"",e)}catch(t){}return i}();n&&!this.disabled&&(this.pendingLinkToken=n),this.utm=new Ut(this.storage,this.logger,this.config.resetSessionOnNewCampaign);const r=this.config.resetSessionOnNewCampaign&&this.config.captureUTM&&this.utm.hasNewCampaign();this.session=new it(this.storage,this.logger,this.config.sessionTimeout),r&&(this.logger.info("New campaign detected, resetting session"),this.session.resetSession()),this.identity=new ct(this.storage,this.logger,this.config.userId,this.config.anonymousId),this.deviceId=this.getOrCreateDeviceId(),this.queue=new Mt(this.storage,this.logger,this.config.batchSize,this.config.batchFlushInterval,this.config.persistQueue,this.config.maxQueueSize,this.config.retryBackoffMs),this.network=new It(this.config.sdkKey,this.logger,{maxRetries:this.config.maxRetries,backoffMs:this.config.retryBackoffMs,timeoutMs:this.config.requestTimeout}),this.network.setRetiredTokenStore({load:()=>this.storage.get(Ke),update:t=>{const i=this.storage.get(Ke),e=t(i&&"object"==typeof i&&!Array.isArray(i)?i:{});Object.keys(e).length?this.storage.set(Ke,e):this.storage.remove(Ke)}});const o=this.storage.get(xe),l="string"==typeof this.config.userId&&this.config.userId?this.config.userId:null;this.withdrawalUserId="string"==typeof o&&o&&o!==this.identity.getUserId()&&!l?o:null,!this.withdrawalUserId&&o&&this.storage.remove(xe),this.network.setCurrentUserId(this.withdrawalUserId||this.identity.getUserId()),this.config.enableSdkAuthentication&&(this.network.setSdkAuthenticationEnabled(!0),this.config.sdkAuthenticationToken&&this.network.setSdkAuthenticationToken(this.config.sdkAuthenticationToken)),this.network.setAnonymousIdSource(()=>this.identity.getAnonymousId()),this.config.storefrontIdentityTokenProvider&&this.network.setStorefrontIdentityTokenProvider(this.config.storefrontIdentityTokenProvider),this.config.storefrontIdentityToken&&this.network.setStorefrontIdentityToken(this.config.storefrontIdentityToken),this.outbox=this.createOutbox(),this.inapp=new Qt(this.config.apiEndpoint,this.config.sdkKey,this.identity,this.session,this.logger,this.storage,Object.assign(Object.assign({closeButton:!0,backdropClose:!0},this.config.inApp.displayOptions),{onDisplay:this.config.inApp.onMessageDisplay,onClick:this.config.inApp.onMessageClick,onDismiss:this.config.inApp.onMessageDismiss}),{logCustomEvent:(t,i)=>this.track(t,i),setCustomUserAttribute:(t,i)=>this.setAttribute(t,i),changeUser:t=>this.identify(t),requestPushPermission:()=>{this.i.subscribe().catch(t=>{this.logger.warn("Push subscribe failed:",t)})},preparePushPermission:()=>{this.i.prepare().catch(t=>{this.logger.warn("Push prepare failed:",t)})}},this.network,{canSend:()=>this.canSend(),requestTimeoutMs:this.config.requestTimeout,syncIntervalMs:this.config.inApp.syncInterval,evaluationMode:this.config.inApp.evaluationMode,noteStatus:(t,i)=>{this.network.noteSuspended(t,i)}}),this.inapp.setAllowHtmlJsInAppMessages(this.config.inApp.allowHtmlJsInAppMessages),this.pageContext=new w(this.config.pageContext),this.pageContext.setUtmSource(()=>this.config.captureUTM&&this.utm?this.utm.getUTMData():null),this.inapp.setPageContext(this.pageContext),this.placements=new pi(this.config.apiEndpoint,this.config.sdkKey,this.identity,this.session,this.logger,{consent:()=>this.placementConsent(),allowHtml:()=>this.config.inApp.allowHtmlJsInAppMessages,requestTimeoutMs:this.config.requestTimeout,noteStatus:(t,i)=>this.network.noteSuspended(t,i),bridge:{logCustomEvent:(t,i)=>this.track(t,i),setCustomUserAttribute:(t,i)=>this.setAttribute(t,i),changeUser:t=>this.identify(t),requestPushPermission:()=>{this.i.subscribe().catch(t=>this.logger.warn("Push subscribe failed:",t))}}},this.network),this.placements.setPageContext(this.pageContext),this.pageEdits=new F(this.config.apiEndpoint,this.config.sdkKey,this.identity,this.session,this.logger,{consent:()=>this.placementConsent(),requestTimeoutMs:this.config.requestTimeout,noteStatus:(t,i)=>this.network.noteSuspended(t,i)},this.network),this.pageEdits.setPageContext(this.pageContext),this.cards=new Di(this.config.apiEndpoint,this.config.sdkKey,this.identity,this.session,this.logger,{consent:()=>this.placementConsent(),requestTimeoutMs:this.config.requestTimeout,noteStatus:(t,i)=>this.network.noteSuspended(t,i),cardsUiScriptUrl:this.config.cardsUiScriptUrl},this.network),this.inapp.links=this.links,this.placements.links=this.links,this.cards.links=this.links,this.flags=new xi(this.config.apiEndpoint,this.config.sdkKey,this.identity,this.session,this.logger,{canSend:()=>this.isInitialized&&!this.disabled&&!this.network.isSuspended()&&this.canSend(),requestTimeoutMs:this.config.requestTimeout,noteStatus:(t,i)=>this.network.noteSuspended(t,i)},this.network),this.o=new Fi(this.logger,this.network,this.identity,this.config.apiEndpoint,(t,i)=>this.runWrite(t,i)),this.i=new ne(this.logger,this.network,this.identity,this.config.apiEndpoint,{canSend:()=>this.canSend(),canWithdraw:()=>this.isInitialized&&!this.disabled,withdrawalUserId:()=>this.effectiveUserId(),storage:this.storage,getDeviceId:()=>this.deviceId,onSubscribeSettled:()=>this.reportPushPermissionIfChanged(),onPrepared:()=>this.reportPushPermissionIfChanged()}),this.queue.setClearedInflightCallback(t=>{const i=this.inflightSessionStartAtClear;i&&(this.inflightSessionStartAtClear=null,t.some(t=>"Session Start"===t.type&&t.sessionId===i)||this.storage.get(Me)!==i||this.storage.set(Me,""))}),this.queue.setFlushCallback(async(t,i)=>{try{return await this.flushEvents(t,i)}finally{this.scheduleRetiredTokenPrune()}}),Ee.set(this,{optedOut:this.userOptedOut,consent:this.trackingConsent});for(const t of i||[])this.applyPreInitDecision(t);this.recomputePrivacy(),this.isOptedOut&&this.logger.warn("Tracking is off (opt-out, Do Not Track or consent denied)"),this.queue.setPaused(this.consentPending),this.isOptedOut&&this.queue.clear(),this.restoreAttributeWrites(),this.disabled||"undefined"==typeof window||"function"!=typeof window.addEventListener||(this.boundHandlePageUnload=this.handlePageUnload.bind(this),window.addEventListener("pagehide",this.boundHandlePageUnload),window.addEventListener("beforeunload",this.boundHandlePageUnload),this.boundHandleOnline=()=>{this.queue.resetBackoff(),this.canSend()&&this.queue.flush().catch(t=>this.logger.error("Flush failed:",t)),this.outbox.kick(),this.i.retryPendingUnregister(),!this.identity.pending.isEmpty()&&this.canSend()&&(this.attributeFailures=0,null!==this.attributeFlushTimer&&(clearTimeout(this.attributeFlushTimer),this.attributeFlushTimer=null),this.scheduleAttributeFlush(0))},window.addEventListener("online",this.boundHandleOnline),this.boundHandleStorage=t=>this.handleStorageEvent(t),window.addEventListener("storage",this.boundHandleStorage)),this.disabled||this.loadPlugins().catch(t=>this.logger.error("Plugin load failed:",t)),this.isInitialized=!0,this.disabled||(Ve.instance=this),this.logger.info("SDK initialized successfully"),!this.disabled&&this.config.inApp.autoMountPlacements&&this.placements.autoMount(),this.disabled||this.pageContext.start(),!this.disabled&&this.config.pageEdits&&(H()?(this.editor=new V(this.config.apiEndpoint,this.config.sdkKey,this.logger,{scriptUrl:this.config.editorScriptUrl}),this.editor.start()):this.pageEdits.start()),this.disabled||this.flags.start(),this.reportPushPermissionIfChanged();let u=!1;if(this.session.ensureSession(),this.config.trackSessionStart&&!this.isOptedOut){const t=this.session.getSessionInfo(),i=this.storage.get(Me),e=null!==i&&i!==t.sessionId;(t.isNewSession||r||e)&&(this.trackSessionStart(),u=!0)}!this.config.trackPageViews||this.isOptedOut||u||(this.trackPageView(),"undefined"!=typeof document&&"loading"===document.readyState&&document.addEventListener("DOMContentLoaded",()=>{this.trackPageView()},{once:!0})),this.session.onNewSession(()=>{this.isOptedOut||(this.config.trackSessionStart&&(this.logger.debug("New session created (mid-visit), tracking session start"),this.trackSessionStart()),this.resyncInApp())}),this.canSend()&&(this.queue.start(),this.config.inApp.enabled&&this.inapp.initialize().catch(t=>{this.logger.error("Failed to initialize in-app messaging:",t)}),this.i.syncExistingSubscription().catch(()=>{}),this.releaseHeldWrites()),this.syncWorkerReporting(),this.isOptedOut||this.releaseDeferredIdentify(),this.flushLinkIdentity(),this.syncOptOutMarker(),this.scheduleRetiredTokenPrune(),this.outbox.kick(),this.i.retryPendingUnregister()}createOutbox(){return new ye({storage:this.storage,logger:this.logger,gate:t=>!this.isInitialized||this.disabled?"hold":t.withdrawal?"send":this.network.isSuspended()?"hold":this.isOptedOut?"drop":this.consentPending?"hold":"send",resolveOwner:t=>this.resolveOwner(t),ownerIsCurrentUser:t=>(t.userId||null)===this.effectiveUserId(),currentIdentity:()=>({anonymousId:this.identity.getAnonymousId(),userId:this.effectiveUserId()}),send:(t,i)=>this.sendWrite(t.record,i),beforeSend:()=>this.flushQueueForWrite(),isSdkAuthError:(t,i)=>this.network.isSdkAuthError(t,i),onSettled:(t,i)=>{this.onWriteSettled(t,i),this.scheduleRetiredTokenPrune()},keepalive:(t,i)=>{const e=this.writeRequest(t.record,i),s=JSON.stringify(e.body);return this.network.postKeepalive(e.url,e.body)?pt(s)+256:null}})}currentOwner(){const t=this.effectiveUserId();return Object.assign({anonymousId:this.identity.getAnonymousId()},t?{userId:t}:{})}effectiveUserId(){return this.withdrawalUserId||this.identity.getUserId()}deferIdentify(t){t!==this.effectiveUserId()&&(this.network.switchUser(t),this.withdrawalUserId=t===this.identity.getUserId()?null:t,this.withdrawalUserId?this.storage.set(xe,this.withdrawalUserId):this.storage.remove(xe),this.logger.debug("Tracking is off: identify kept on this device for withdrawals only, not sent"))}releaseDeferredIdentify(){const t=this.withdrawalUserId;t&&(this.forgetDeferredIdentify(),this.identify(t))}forgetDeferredIdentify(){this.withdrawalUserId=null,this.storage.remove(xe)}scheduleRetiredTokenPrune(t=0){null!==this.pruneTimer||this.disabled||(this.pruneTimer=setTimeout(()=>{this.pruneTimer=null,this.pruneRetiredTokens()},t))}pruneRetiredTokens(){var t;try{if(!this.network.retiredSdkAuthUsers().length)return;const i=new Set,e=this.network.getCurrentUserId();e&&i.add(e),this.withdrawalUserId&&i.add(this.withdrawalUserId);for(const t of this.queue.getQueuedEvents())t.userId&&i.add(t.userId);for(const t of this.queue.getPendingIdentifies())i.add(t.userId);for(const t of this.outbox.records()){const e=t.payload.userId;"string"==typeof e&&e&&i.add(e)}for(const e of this.identity.pending.serialize())(null===(t=e.owner)||void 0===t?void 0:t.userId)&&i.add(e.owner.userId);for(const t of this.i.pendingUnregisterUsers())i.add(t);for(const t of Ne)Fe(this.storage.get(t),i);const s=this.network.forgetRetiredSdkAuthTokensExcept(i);null!==s&&this.scheduleRetiredTokenPrune(s+50)}catch(t){this.logger.warn("Could not prune stored SDK authentication tokens:",t)}}handleStorageEvent(t){var i,e;try{if(!this.isInitialized||this.disabled||!t)return;const s=null!==(i=t.key)&&void 0!==i?i:null,n=t=>null===s||s===this.storage.storageKeyFor(t);if(null===s)this.repersistPrivacyDecisions(),this.outbox.persistNow();else if(n(Ae)||n($e)||n(De)||n(Ie)||n(Te)||n(_e)){const t=this.storedOptOut(),i=this.storedDenial();t&&(this.optedOutAt=this.storedStamp($e)),i&&(this.consentDeniedAt=this.storedStamp(Te)),this.noteDecisionStamps();let e=!1;t!==this.userOptedOut&&(this.userOptedOut=t,e=!0),i&&"denied"!==this.trackingConsent?(this.trackingConsent="denied",e=!0):i||"denied"!==this.trackingConsent?!i&&"pending"===this.trackingConsent&&n(_e)&&null!==this.storage.get(_e)&&(this.trackingConsent="granted",e=!0):(this.trackingConsent="granted",e=!0),e&&this.applyPrivacyState()}if(null!==s&&n(xe)){const t=this.storage.get(xe),i="string"==typeof t&&t&&t!==this.identity.getUserId()?t:null;i!==this.withdrawalUserId&&(this.network.switchUser(i||this.identity.getUserId()),this.withdrawalUserId=i)}if(null!==s&&n(Q)&&this.awaitingSessionOf&&(this.awaitingSessionOf===this.identity.getAnonymousId()&&this.storage.get(Q)&&this.session.followStoredSession(),this.awaitingSessionOf=null),n(qe)||n(ze)){const t=this.storage.get(qe),i=this.storage.get(ze)||null;if(!t)return;if(t===this.identity.getAnonymousId()&&i===this.identity.getUserId())return;this.logger.info("Another tab changed the visitor identity; following it");const s=t!==this.identity.getAnonymousId();this.config.inApp.enabled?this.inapp.clearAll():this.inapp.invalidate(),this.pinAnonymousWrites(),this.network.switchUser(i),this.identity.adopt(t,i),this.placements.invalidate(),this.cards.invalidate(!0),null===(e=this.pageEdits)||void 0===e||e.invalidate(),this.flags.onIdentityChanged(),this.withdrawalUserId=null,s&&(this.utm.reset(),this.session.followStoredSession(),this.awaitingSessionOf=t),this.resyncInApp(!0)}}catch(t){this.logger.error("Could not follow a change made in another tab:",t)}}repersistPrivacyDecisions(){this.userOptedOut&&!0!==this.storage.get(Ae)&&this.writeOptOut(this.optedOutAt),"denied"===this.trackingConsent&&"denied"!==this.storage.get(Ie)&&this.writeDenial(this.consentDeniedAt),this.withdrawalUserId&&this.storage.get(xe)!==this.withdrawalUserId&&this.storage.set(xe,this.withdrawalUserId)}storedStamp(t){const i=this.storage.get(t);return"number"==typeof i&&Number.isFinite(i)?i:0}noteDecisionStamps(){for(const t of[$e,De,Te,_e])this.lastDecisionStamp=Math.max(this.lastDecisionStamp,this.storedStamp(t))}nextDecisionStamp(){return this.noteDecisionStamps(),this.lastDecisionStamp=Math.max(Date.now(),this.lastDecisionStamp+1,this.optedOutAt+1,this.consentDeniedAt+1),this.lastDecisionStamp}storedOptOut(){return!0===this.storage.get(Ae)&&!(this.storedStamp(De)>this.storedStamp($e))}storedDenial(){return"denied"===this.storage.get(Ie)&&!(this.storedStamp(_e)>this.storedStamp(Te))}writeOptOut(t){const i=void 0===t?this.nextDecisionStamp():t;this.optedOutAt=i,this.storage.set(Ae,!0),this.storage.set($e,i)}writeOptIn(){const t=this.nextDecisionStamp();this.optedOutAt=0,this.storage.remove(Ae),this.storage.remove($e),this.storage.set(De,t)}writeDenial(t){const i=void 0===t?this.nextDecisionStamp():t;this.consentDeniedAt=i,this.storage.set(Ie,"denied"),this.storage.set(Te,i)}writeGrant(){const t=this.nextDecisionStamp();this.consentDeniedAt=0,this.storage.remove(Ie),this.storage.remove(Te),this.storage.set(_e,t)}resolveOwner(t){if(t.userId)return t;const i=this.effectiveUserId();return i&&t.anonymousId===this.identity.getAnonymousId()?this.queue.getPendingIdentifies().some(i=>i.anonymousId===t.anonymousId)?t:{anonymousId:t.anonymousId,userId:i}:t}pinAnonymousWrites(){const t=this.identity.getUserId();if(!t)return;const i=this.identity.getAnonymousId();this.identity.pending.pinOwner(i,t),this.persistAttributeWrites(),this.outbox.pinOwner(i,t)}writeRequest(t,i){const e=this.config.apiEndpoint,s=Object.assign(Object.assign({},i.userId?{userId:i.userId}:{}),{anonymousId:i.anonymousId});switch(t.kind){case"alias":return{url:e+"/v1/alias/add",body:Object.assign(Object.assign({},t.payload),s)};case"subscription":return{url:e+"/v1/subscriptions/channel",body:Object.assign(Object.assign({},t.payload),s)};case"group":return{url:e+"/v1/subscriptions/group",body:Object.assign(Object.assign({},t.payload),s)};default:return{url:e+"/v1/attributes",body:Object.assign(Object.assign({},i.userId?{userId:i.userId}:{anonymousId:i.anonymousId}),this.markerOps(t))}}}markerOps(t){const i=t.payload.value;return{attributes:{[Re]:i}}}sendWrite(t,i){const e=this.config.apiEndpoint,s=Object.assign(Object.assign({},i.userId?{userId:i.userId}:{}),{anonymousId:i.anonymousId});switch(t.kind){case"alias":return this.network.sendAddAlias(e,Object.assign(Object.assign({},t.payload),s));case"subscription":return this.network.sendSubscriptionUpdate(e,Object.assign(Object.assign({},t.payload),s));case"group":return this.network.sendSubscriptionGroupUpdate(e,Object.assign(Object.assign({},t.payload),s));default:return this.network.sendSetAttributes(e,this.markerOps(t),i.userId,i.anonymousId)}}onWriteSettled(t,i){if("marker"!==t.record.kind)return;const e=t.record.payload.value;"done"===i?(e?this.storage.set(Ce,!0):this.storage.remove(Ce),this.storage.remove(Pe)):this.storage.set(Pe,e),this.syncOptOutMarker()}syncWorkerReporting(){this.disabled||this.i.setTrackingOptedOut(this.isOptedOut||this.consentPending).catch(()=>{})}initialConsent(t){const i=this.storedDenial();return"granted"===t?(this.storage.remove(Ie),this.storage.remove(Te),"granted"):"denied"===t?(this.writeDenial(),"denied"):i?(this.consentDeniedAt=this.storedStamp(Te),"denied"):"pending"===t?"pending":"granted"}storeConsent(t){return"granted"===t?(this.writeGrant(),"granted"):"denied"===t?(this.writeDenial(),"denied"):this.storedDenial()?(this.logger.info("updateConsent('pending') ignored: consent was denied, and only 'granted' lifts that"),"denied"):"pending"}applyPreInitDecision(t){try{switch(t.method){case"optOut":this.userOptedOut=!0,this.writeOptOut();break;case"optIn":this.userOptedOut=!1,this.writeOptIn();break;case"updateConsent":"granted"!==t.consent&&"denied"!==t.consent&&"pending"!==t.consent||(this.trackingConsent=this.storeConsent(t.consent));break;case"wipeData":this.i.forget().catch(()=>{}),this.wipeLocalState(),this.config.userId&&(this.identity.identify(this.config.userId),this.network.setCurrentUserId(this.config.userId)),this.config.enableSdkAuthentication&&this.config.sdkAuthenticationToken&&this.network.setSdkAuthenticationToken(this.config.sdkAuthenticationToken)}}catch(i){this.logger.error(`Applying ${t.method} from before init failed:`,i)}}getTrackingConsent(){return this.trackingConsent}isUserOptedOut(){return this.userOptedOut}syncOptOutMarker(){if(this.disabled||!this.isInitialized)return;const t=this.userOptedOut,i=!0===this.storage.get(Ce),e=this.identity.getAnonymousId(),s=this.outbox.findLast(t=>"marker"===t.record.kind&&t.record.payload.anonymousId===e);if(s){if("marker"===s.record.kind&&s.record.payload.value===t)return;if(t===i&&!this.outbox.isInFlight(s))return void this.outbox.cancel(t=>"marker"===t.record.kind&&t.record.payload.anonymousId===e)}else{if(t===i)return;if(this.storage.get(Pe)===t)return}this.outbox.enqueue({kind:"marker",payload:Object.assign({value:t},this.currentOwner())})}recomputePrivacy(){this.isOptedOut=this.disabled||this.userOptedOut||this.dntEnabled||"denied"===this.trackingConsent,this.consentPending=!this.isOptedOut&&"pending"===this.trackingConsent}canSend(){return this.isInitialized&&!this.isOptedOut&&!this.consentPending&&!this.network.isSuspended()}applyPrivacyState(){var t,i,e,s;const n=this.isOptedOut,r=this.consentPending;if(this.recomputePrivacy(),this.syncWorkerReporting(),n===this.isOptedOut&&r===this.consentPending||(this.inapp.invalidate(),null===(t=this.placements)||void 0===t||t.invalidate(),null===(i=this.cards)||void 0===i||i.invalidate(!1),null===(e=this.pageEdits)||void 0===e||e.invalidate({siteSettings:!0}),null===(s=this.flags)||void 0===s||s.onIdentityChanged()),this.isOptedOut){const t=this.session.getSessionId(),i=i=>"Session Start"===i.type&&i.sessionId===t;return this.queue.getWaitingEvents().some(i)?this.storage.set(Me,""):t&&this.queue.getInflightEvents().some(i)&&(this.inflightSessionStartAtClear=t),this.queue.stop(),this.queue.clear(),this.queue.setPaused(!1),this.clearPendingAttributeWrites(),this.outbox.discardNonWithdrawals(),this.outbox.kick(),this.config.inApp.enabled&&this.inapp.stop(),void(this.pendingLinkToken=null)}if(n&&this.releaseDeferredIdentify(),n&&this.trackSessionStartIfMissing(),this.consentPending)return this.queue.stop(),this.queue.setPaused(!0),void(this.config.inApp.enabled&&this.inapp.stop());this.queue.setPaused(!1),this.queue.isStarted()||this.queue.start(),this.queue.flush().catch(t=>this.logger.error("Flush failed:",t)),this.releaseHeldWrites(),this.config.inApp.enabled&&this.inapp.initialize().catch(t=>{this.logger.error("Failed to initialize in-app messaging:",t)}),this.i.syncExistingSubscription().catch(()=>{}),this.flushLinkIdentity()}flushLinkIdentity(){const t=this.pendingLinkToken;t&&(this.disabled||this.isOptedOut?this.pendingLinkToken=null:this.canSend()&&(this.pendingLinkToken=null,this.sentLinkTokens.has(t)||(this.effectiveUserId()?this.logger.debug("Link identity not sent: a user is identified on this browser"):this.network.hasStorefrontIdentity()?this.logger.debug("Link identity not sent: a signed-in store customer is on this browser"):(this.sentLinkTokens.add(t),this.network.sendIdentifyLink(this.config.apiEndpoint,{token:t,anonymousId:this.identity.getAnonymousId()}).catch(t=>this.logger.debug("Link identity request failed:",t))))))}identifyFromLink(t){if(!this.isInitialized||this.disabled)return;const i=je(t);if(i){try{if("undefined"!=typeof window&&window.location&&je(window.location.href)===i){const t=Oe(window.location.href);t&&window.history&&"function"==typeof window.history.replaceState&&window.history.replaceState(window.history.state,"",t)}}catch(t){}this.pendingLinkToken=i,this.flushLinkIdentity()}}releaseHeldWrites(){this.identity.pending.isEmpty()||this.scheduleAttributeFlush(0),this.outbox.kick()}runWrite(t,i){this.isInitialized&&!this.disabled?!this.isOptedOut&&0>=this.dataGate.size||Vi(i)?(this.withdrawalUserId&&Vi(i)&&i.payload.anonymousId===this.identity.getAnonymousId()&&(i=Object.assign(Object.assign({},i),{payload:Object.assign(Object.assign({},i.payload),{userId:this.withdrawalUserId})})),this.outbox.enqueue(i)):this.logger.debug(t+" not sent: tracking is off"):this.logger.error(t+": SDK not initialized")}restoreAttributeWrites(){const t=this.storage.get(Le);if(this.isOptedOut)return this.storage.remove(Le),void this.outbox.discardNonWithdrawals();t&&"object"==typeof t&&(Array.isArray(t.entries)?this.identity.pending.restore(t.entries):(t.ops&&"object"==typeof t.ops&&this.identity.pending.mark(t.ops),t.increment&&"object"==typeof t.increment&&this.identity.pending.mark({increment:t.increment})))}persistAttributeWrites(){this.identity.pending.isEmpty()?this.storage.remove(Le):this.storage.set(Le,{entries:this.identity.pending.serialize()})}async flushQueueForWrite(){this.canSend()&&(this.queue.getPendingIdentify()||this.queue.getQueueSize()>0)&&await this.queue.flush().catch(()=>{})}trackSessionStart(){this.logger.debug("Tracking session start");const t={};this.config.trackDeviceProperties&&(Object.assign(t,(()=>{var t,i;if("undefined"==typeof window||"undefined"==typeof navigator)return{};const e=navigator.userAgent||"",s=navigator.language||"",n=Array.isArray(navigator.languages)?navigator.languages:void 0;return{$user_agent:e,$timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,$screen_width:null===(t=window.screen)||void 0===t?void 0:t.width,$screen_height:null===(i=window.screen)||void 0===i?void 0:i.height,$viewport_width:window.innerWidth,$viewport_height:window.innerHeight,$language:s,$languages:n,$platform:navigator.platform,$browser:qi(e)}})()),t.$device_id=this.deviceId),"undefined"!=typeof window&&window.location&&(t.landing_page=window.location.href,t.landing_path=window.location.pathname,t.landing_search=window.location.search,t.landing_title="undefined"!=typeof document?document.title:"",t.landing_referrer="undefined"!=typeof document&&document.referrer||null),this.track("Session Start",t),this.storage.set(Me,this.session.getSessionId())}trackSessionStartIfMissing(){this.config.trackSessionStart&&!this.isOptedOut&&(this.session.ensureSession(),this.storage.get(Me)!==this.session.getSessionId()&&this.trackSessionStart())}getOrCreateDeviceId(){const t="device_id",i=this.storage.get(t);if(i)return i;const e=X();return this.storage.set(t,e),e}trackPageView(){if("undefined"==typeof window||!window.location)return;const t=window.location.href;if(this.lastTrackedUrl===t)return;const i={url:t,path:window.location.pathname,search:window.location.search,title:"undefined"!=typeof document?document.title:""};this.config.trackPageProperties&&"undefined"!=typeof document&&(i.referrer=document.referrer||null,i.landing_page=this.utm.getSessionLandingPage()||null),this.lastTrackedUrl=t,this.track("Page Viewed",i)}track(t,i){var e,s;if(this.isInitialized){if(!this.isDroppingDataCalls("track"))if(this.isOptedOut)this.logger.debug("Tracking disabled, event not tracked:",t);else if("string"!=typeof t||1>t.length||t.length>255)this.logger.error("track() needs an event name of 1-255 characters; event dropped");else try{"Session Start"!==t&&this.session.refreshIfExpired(),this.session.ensureSession(),this.session.updateActivity();const n=i&&"object"==typeof i&&!Array.isArray(i)?Object.assign({},i):{};this.config.captureUTM&&Object.assign(n,this.utm.getUTMProperties()),this.deviceId&&!n.$device_id&&(n.$device_id=this.deviceId);let r={eventId:X(),type:t,properties:n,timestamp:(new Date).toISOString(),userId:this.identity.getUserId(),anonymousId:this.identity.getAnonymousId(),sessionId:this.session.getSessionId()};for(const t of this.config.plugins)if(t.beforeTrack){try{r=t.beforeTrack(r)}catch(i){this.logger.error(`Plugin ${t.name} beforeTrack threw; event kept unchanged:`,i)}if(null===r)return void this.logger.debug("Event blocked by plugin: "+t.name)}r&&r.properties&&"object"==typeof r.properties&&(r=Object.assign(Object.assign({},r),{properties:me(r.properties,(i,e)=>this.logger.warn(`Event "${t}": property "${i}" dropped - ${e}`))}));const o=r&&r.properties&&"object"==typeof r.properties?function(t){const i=Object.keys(t).length;if(i>200)return i+" property keys (the limit is 200)";const e=(t,i)=>i>5||null!==t&&"object"==typeof t&&(Array.isArray(t)?t:Object.values(t)).some(t=>null!==t&&"object"==typeof t&&e(t,i+1));if(e(t,1))return"properties nested deeper than 5 levels";let s;try{s=JSON.stringify(t)}catch(t){return"properties that cannot be serialized (a circular reference?)"}return s.length>51200?s.length+" characters of properties (the limit is 51200)":null}(r.properties):null;if(o)return void this.logger.error(`Event "${t}" dropped: ${o}`);if(this.queue.enqueue(r),this.canSend())try{null===(e=this.inapp)||void 0===e||e.onEventTracked(t,n),null===(s=this.placements)||void 0===s||s.onEventTracked(t,n)}catch(t){this.logger.error("In-app trigger evaluation failed:",t)}for(const t of this.config.plugins)if(t.afterTrack)try{t.afterTrack(r)}catch(i){this.logger.error(`Plugin ${t.name} afterTrack threw:`,i)}this.config.sendImmediately&&this.canSend()&&this.flush().catch(t=>this.logger.error("Immediate flush failed:",t))}catch(t){this.logger.error("track() failed:",t)}}else this.logger.error("SDK not initialized")}identify(t){var i;if(!this.isInitialized)return void this.logger.error("SDK not initialized");if("string"!=typeof t||!t.trim()||t.length>255)return void this.logger.error("identify() needs a userId of 1-255 characters");if(this.isOptedOut)return void(this.disabled||this.deferIdentify(t));this.withdrawalUserId&&this.forgetDeferredIdentify();const e=this.identity.getUserId(),s=this.identity.getAnonymousId();this.queue.setPendingIdentify({userId:t,anonymousId:s,attributes:{}});const n=!!e&&e!==t;n&&(this.pinAnonymousWrites(),this.config.inApp.enabled&&this.inapp.clearAll()),this.identity.identify(t),this.network.switchUser(t),e!==t&&(this.inapp.invalidate(),this.placements.invalidate(),this.cards.invalidate(!0),null===(i=this.pageEdits)||void 0===i||i.invalidate(),this.flags.onIdentityChanged()),this.canSend()&&this.queue.flush(!1,!0).catch(t=>{this.logger.error("Failed to flush with identify:",t)}).then(()=>{e!==t&&this.resyncInApp(n)})}addAlias(t,i){if(!this.isInitialized)return void this.logger.error("SDK not initialized");if(this.isDroppingDataCalls("addAlias"))return;if("string"!=typeof t||!t.trim()||"string"!=typeof i||!i.trim())return void this.logger.error("addAlias(aliasLabel, aliasName) needs two non-empty strings");const e=this.identity.getUserId(),s=Object.assign(Object.assign({anonymousId:this.identity.getAnonymousId()},e?{userId:e}:{}),{aliasLabel:t,aliasName:i});this.runWrite("addAlias",{kind:"alias",payload:s})}setAttributes(t){if(!this.isInitialized)return void this.logger.error("SDK not initialized");if(this.isDroppingDataCalls("setAttributes"))return;if(!t||"object"!=typeof t||Array.isArray(t))return void this.logger.error('setAttributes requires a plain object, e.g. setAttributes({ email: "user@example.com" })');const i={},e=[];for(const[s,n]of Object.entries(t)){if(!s)continue;if(null==n){e.push(s);continue}const t=ve(n);t?this.logger.warn(`Attribute "${s}" not set: its value is ${t}`):i[s]=n}this.identity.setAttributes(i);for(const t of e)this.identity.unsetAttribute(t);this.isOptedOut||!Object.keys(i).length&&!e.length||this.sendAttributesAfterPendingIdentify(Object.assign(Object.assign({},Object.keys(i).length?{attributes:i}:{}),e.length?{unset:e}:{}))}sendAttributesAfterPendingIdentify(t){this.identity.pending.mark(t,this.currentOwner()),this.persistAttributeWrites(),this.scheduleAttributeFlush(Ve.ATTRIBUTE_FLUSH_DEBOUNCE_MS)}scheduleAttributeFlush(t){null===this.attributeFlushTimer&&(this.attributeFlushTimer=setTimeout(()=>{this.attributeFlushTimer=null,this.canSend()&&this.flushAttributeOps()},t))}clearPendingAttributeWrites(){null!==this.attributeFlushTimer&&(clearTimeout(this.attributeFlushTimer),this.attributeFlushTimer=null),this.identity.pending.clear(),this.attributeGeneration++,this.attributeFlushInFlight=!1,this.attributeFlushAgain=!1,this.attributeFailures=0,this.storage.remove(Le)}flushAttributeOps(){(this.queue.getPendingIdentify()?this.queue.flush(!1,!0).catch(()=>{}):Promise.resolve()).then(()=>{var t;if(!this.canSend())return;if(this.queue.getPendingIdentify())return void this.scheduleAttributeFlush(this.attributeRetryDelay());if(this.attributeFlushInFlight)return void(this.attributeFlushAgain=!0);const i=this.identity.pending.nextRequest(t=>this.resolveOwner(null!=t?t:this.currentOwner()));if(!i)return;this.attributeFlushInFlight=!0;const e=this.attributeGeneration,{ops:s,entries:n}=i,r=this.resolveOwner(null!==(t=i.owner)&&void 0!==t?t:this.currentOwner());this.network.sendSetAttributes(this.config.apiEndpoint,s,r.userId,r.anonymousId).then(t=>{var i,o;if(e!==this.attributeGeneration)return;const h=Qi(t,{isSdkAuthError:this.network.isSdkAuthError(t.status,t.data),ownerIsCurrentUser:(r.userId||null)===this.identity.getUserId()});if("done"===h.action){this.attributeFailures=0,this.identity.pending.acknowledge(n),this.persistAttributeWrites();const t=null===(i=s.attributes)||void 0===i?void 0:i[Be];return"string"==typeof t&&this.storage.set(He,t),this.identity.pending.hasUnsent()&&(this.attributeFlushAgain=!0),void this.scheduleRetiredTokenPrune()}if("drop"===h.action)return this.logger.error("Attributes dropped: "+h.reason,t.error),this.identity.pending.drop(n),this.persistAttributeWrites(),this.identity.pending.hasUnsent()&&(this.attributeFlushAgain=!0),void this.scheduleRetiredTokenPrune();const a=!(t.softFailure||0!==t.status&&500>t.status),l=this.identity.pending.release(n,a);if(l>0&&this.logger.error(`Failed to send attributes (HTTP ${t.status||"no response"}); ${l} increment(s) are LOST (an $inc cannot be safely retried).`),"hold"===h.action)return this.persistAttributeWrites(),void this.logger.error(`Attributes not sent: ${h.reason}; they are kept for the next page view.`);if(h.counts){const i=n.filter(t=>(t.attempts=(t.attempts||0)+1,t.attempts>=10));i.length&&(this.logger.error(`Attributes failed (HTTP ${t.status}) too many times; dropping them`),this.identity.pending.drop(i))}this.persistAttributeWrites(),this.logger.warn(`Failed to send attributes (HTTP ${t.status||"no response"}); will retry`),this.attributeFailures++,this.scheduleAttributeFlush(Math.max(this.attributeRetryDelay(),Math.min(null!==(o=h.retryAfterMs)&&void 0!==o?o:0,3e5)))}).then(()=>{e===this.attributeGeneration&&(this.attributeFlushInFlight=!1,this.attributeFlushAgain&&(this.attributeFlushAgain=!1,this.flushAttributeOps()))}).catch(t=>{e===this.attributeGeneration&&(this.attributeFlushInFlight=!1),this.logger.error("Attribute flush bookkeeping failed:",t)})})}attributeRetryDelay(){const t=Math.max(1,this.attributeFailures);return Math.min(5e3*Math.pow(2,t-1),3e5)}reportPushPermissionIfChanged(){if(this.isInitialized&&!this.isOptedOut&&this.pushPermissionReported())try{const t=this.i.getPermissionState(),i="notDetermined"===t?"not_determined":t;if(this.storage.get(He)===i)return;this.logger.debug(`Push permission changed to ${i}; reporting`),this.setAttribute(Be,i)}catch(t){this.logger.warn("Could not report push permission:",t)}}pushPermissionReported(){return!0===this.config.webPush||!!this.i.usedOnThisPage()||!1!==this.config.webPush&&this.i.usedEarlier()}setAttribute(t,i){"string"==typeof t&&t?this.setAttributes({[t]:i}):this.logger.error("setAttribute(key, value) needs a non-empty key")}incrementAttribute(t,i=1){this.isInitialized?this.isDroppingDataCalls("incrementAttribute")||("string"==typeof t&&t&&"number"==typeof i&&Number.isFinite(i)?(this.identity.incrementAttribute(t,i),this.isOptedOut||this.sendAttributesAfterPendingIdentify({increment:{[t]:i}})):this.logger.error("incrementAttribute(key, value) needs a key and a finite number")):this.logger.error("SDK not initialized")}unsetAttribute(t){this.isInitialized?this.isDroppingDataCalls("unsetAttribute")||("string"==typeof t&&t?(this.identity.unsetAttribute(t),this.isOptedOut||this.sendAttributesAfterPendingIdentify({unset:[t]})):this.logger.error("unsetAttribute() needs a non-empty attribute key")):this.logger.error("SDK not initialized")}addToArray(t,i){if(!this.isInitialized)return void this.logger.error("SDK not initialized");if(this.isDroppingDataCalls("addToArray"))return;if("string"!=typeof t||!t)return void this.logger.error("addToArray() needs a non-empty attribute key");const e=ve(i);e?this.logger.warn(`addToArray("${t}") ignored: the value is ${e}`):(this.identity.addToArray(t,i),this.isOptedOut||this.sendAttributesAfterPendingIdentify({append:{[t]:i}}))}removeFromArray(t,i){if(!this.isInitialized)return void this.logger.error("SDK not initialized");if(this.isDroppingDataCalls("removeFromArray"))return;if("string"!=typeof t||!t)return void this.logger.error("removeFromArray() needs a non-empty attribute key");const e=ve(i);e?this.logger.warn(`removeFromArray("${t}") ignored: the value is ${e}`):(this.identity.removeFromArray(t,i),this.isOptedOut||this.sendAttributesAfterPendingIdentify({remove:{[t]:i}}))}async reset(){return this.resetIdentity(void 0)}async resetTo(t){if(!this.isInitialized)return this.logger.error("SDK not initialized"),!1;const i=this.identity.getUserId(),e=function(t,i,e=null,s=[]){return"string"==typeof t&&be.test(t)?ge.test(t)?"resetTo: the anonymous id has the shape of a Joryio profile id":i.some(i=>"string"==typeof i&&i===t)?"resetTo: the anonymous id is a user id":"string"==typeof e&&e===t||s.includes(t)?"resetTo: the anonymous id belongs to the signed-in user":null:'resetTo: the anonymous id must be 8 to 255 letters, digits, ".", "_", ":" or "-"'}(t,[i,this.withdrawalUserId],i?this.identity.getAnonymousId():null,this.signedInAnonymousIds());return e&&this.logger.error(e+"; a random anonymous id is used instead"),await this.resetIdentity(e?void 0:t),!e}signedInAnonymousIds(){const t=this.storage.get(we);return Array.isArray(t)?t.filter(t=>"string"==typeof t):[]}async resetIdentity(t){var i,e,s;this.isInitialized?(this.logger.info("Resetting user identity"),this.pendingLinkToken=null,this.config.inApp.enabled&&this.inapp.clearAll(),this.network.retireSdkAuthToken(),this.network.clearStorefrontIdentityToken(),this.forgetDeferredIdentify(),this.identity.getUserId()&&this.storage.set(we,(e=this.signedInAnonymousIds(),s=this.identity.getAnonymousId(),[...e.filter(t=>t!==s),s].slice(-20))),this.pinAnonymousWrites(),this.identity.reset(t),this.flags.onIdentityChanged(),this.network.setCurrentUserId(this.identity.getUserId()),this.placements.invalidate(),this.cards.invalidate(!0),null===(i=this.pageEdits)||void 0===i||i.invalidate({siteSettings:!0}),this.utm.reset(),this.session.resetSession(),await this.flush().catch(()=>{}),this.canSend()&&(this.resyncInApp(!0),this.i.syncExistingSubscription(!0).catch(()=>{})),this.outbox.kick(),this.logger.info("User identity reset")):this.logger.error("SDK not initialized")}async wipeData(){if(!this.isInitialized)return void this.logger.error("SDK not initialized");this.logger.info("Wiping local SDK data"),this.pendingLinkToken=null;const t=this.i.forget().catch(()=>{});this.wipeLocalState(),this.session.ensureSession(),this.trackSessionStartIfMissing(),await t,this.canSend()&&this.resyncInApp(!0),this.logger.info("Local SDK data wiped")}wipeLocalState(){var t,i;this.clearPendingAttributeWrites(),this.outbox.discardNonWithdrawals(),this.storage.remove(He),this.storage.remove(we),this.storage.set(Me,""),this.queue.clear(),this.config.inApp.enabled?this.inapp.clearAll():this.inapp.invalidate(),this.inapp.forgetImpressions();const e=new Set;for(const t of[this.effectiveUserId(),this.identity.getUserId(),this.network.getCurrentUserId()])t&&e.add(t);for(const t of this.outbox.records()){const i=t.payload.userId;"string"==typeof i&&i&&e.add(i)}for(const t of this.i.pendingUnregisterUsers())e.add(t);for(const t of[oe,ee])Fe(this.storage.get(t),e);this.network.retireSdkAuthToken(),this.network.dropStandbySdkAuthTokens(e),this.network.clearStorefrontIdentityToken(),this.forgetDeferredIdentify(),this.pinAnonymousWrites(),this.identity.reset(),this.flags.onIdentityChanged(),this.network.setCurrentUserId(null),this.placements.invalidate(),null===(t=this.cards)||void 0===t||t.invalidate(!0),null===(i=this.pageEdits)||void 0===i||i.invalidate({siteSettings:!0}),this.utm.reset(),this.session.clear(),this.lastTrackedUrl=null,this.storage.remove("device_id"),this.deviceId=this.getOrCreateDeviceId()}resyncInApp(t=!1){this.config.inApp.enabled&&this.canSend()&&(t?this.inapp.initialize():this.inapp.sync().then(()=>{})).catch(t=>this.logger.debug("In-app re-sync failed:",t))}async flush(){this.isInitialized?await this.queue.flush(!1,!0):this.logger.error("SDK not initialized")}async flushEvents(t,i){var e,s,n,r;if(!this.canSend())return{status:"retry"};this.logger.debug(`Sending ${t.length} events${i?" + identify":""} to backend`);const o=await this.network.sendEvents(this.config.apiEndpoint,t,i);if(o.ok||o.softFailure){const h=Array.isArray(null===(e=o.data)||void 0===e?void 0:e.rejectedIndices)?o.data.rejectedIndices:void 0;let a=!1,l=!1,u=!0;if(i&&!(null===(s=o.data)||void 0===s?void 0:s.identified)&&o.softFailure)a=!0;else if(i&&!(null===(n=o.data)||void 0===n?void 0:n.identified)){this.logger.debug("Backend did not confirm atomic identify, falling back to standalone");const t=await this.network.sendIdentify(this.config.apiEndpoint,i.userId,i.attributes||{},i.anonymousId);if(!t.ok){const e=!(t.softFailure||0!==t.status&&408!==t.status&&429!==t.status&&500>t.status);!0===t.softFailure||e||401===t.status&&this.network.isSdkAuthError(t.status,t.data)&&i.userId===this.identity.getUserId()||402===t.status?(this.logger.error("Standalone identify fallback failed; it is kept and retried:",t.error),a=!0,u=!e&&402!==t.status):(this.logger.error(`Standalone identify fallback refused (HTTP ${t.status}); dropping it:`,t.error),l=!0)}}return o.softFailure?{status:"ok",failedIndices:Array.isArray(null===(r=o.data)||void 0===r?void 0:r.failedIndices)?o.data.failedIndices:t.map((t,i)=>i),rejectedIndices:h,identifyFailed:a,identifyAttemptCounts:u,identifyDropped:l}:(this.logger.debug("Events sent successfully"),{status:"ok",rejectedIndices:h,identifyFailed:a,identifyAttemptCounts:u,identifyDropped:l})}return this.classifyFailure(o,t,i)}classifyFailure(t,i=[],e){var s,n;const r=t.status;if(400===r||413===r||422===r)return{status:"rejected",httpStatus:r};if(401===r){if(this.network.isSdkAuthError(r,t.data)){const r=null===(s=t.data)||void 0===s?void 0:s.reason,o=(null==e?void 0:e.userId)||(null===(n=i.find(t=>t.userId))||void 0===n?void 0:n.userId)||null;return o&&o!==this.identity.getUserId()?{status:"dropped",reason:"401 "+(r||"sdk_authentication_error")}:{status:"retry",counts:!0}}return{status:"suspended",reason:"the SDK key was refused (401)"}}return 402===r?{status:"suspended",reason:"event ingestion is paused for this workspace (402)"}:403===r?{status:"suspended",reason:"the request was forbidden (403)"}:0!==r&&408!==r&&429!==r&&500>r?{status:"suspended",reason:"the API answered HTTP "+r}:{status:"retry",retryAfterMs:t.retryAfterMs}}handlePageUnload(){if(this.isInitialized)if("undefined"==typeof navigator||!1!==navigator.onLine){try{this.outbox.handOffAtUnload(8192)}catch(t){this.logger.error("Page-unload write hand-off failed:",t)}if(!this.canSend()||this.queue.isSuspended()||this.queue.isBackingOff())this.queue.persistNow();else try{this.sendAttributesAtUnload();const t=Math.max(0,this.network.keepaliveBudget()-256),i=this.queue.getQueuedEvents(),e=this.queue.getPendingIdentify();if(0===i.length&&!e)return;if(!this.network.supportsKeepalive())return void this.queue.persistNow();const s=i[0],n=!e||s&&(s.anonymousId!==e.anonymousId||s.userId&&s.userId!==e.userId)?null:e;let r=64+(n?pt(JSON.stringify(n)):0);const o=[];let h=null;for(const e of i){if(s&&e.anonymousId!==s.anonymousId)break;if(e.userId&&h&&e.userId!==h)break;if(n&&(e.anonymousId!==n.anonymousId||e.userId&&e.userId!==n.userId))break;const i=pt(JSON.stringify(e))+1;if(r+i>t)break;o.push(e),e.userId&&(h=e.userId),r+=i}if(0===o.length&&!n)return void this.queue.persistNow();this.logger.debug(`Page unload: handing ${o.length} of ${i.length} events${n?" + identify":""} to keepalive`);const a=this.network.sendEventsKeepalive(this.config.apiEndpoint,o,n||void 0);if(!a)return void this.queue.persistNow();this.queue.markHandedOff(o,n),a.then(t=>{t.ok||!t.softFailure&&0!==t.status&&429!==t.status&&500>t.status||this.queue.takeBack(o,n)}).catch(()=>{})}catch(t){this.logger.error("Page-unload send failed:",t),this.queue.persistNow()}}else this.queue.persistNow()}sendAttributesAtUnload(){var t;if(this.queue.getPendingIdentify())return 0;const i=this.identity.pending.peekRequest(t=>this.resolveOwner(null!=t?t:this.currentOwner()));if(!i||!this.network.supportsKeepalive())return 0;try{const e=this.resolveOwner(null!==(t=i.owner)&&void 0!==t?t:this.currentOwner()),s=Object.assign({userId:e.userId||void 0,anonymousId:e.userId?void 0:e.anonymousId},i.ops),n=this.network.postKeepalive(this.config.apiEndpoint+"/v1/attributes",s);return n?(n.catch(()=>{}),this.identity.pending.dropIncrements(i.entries),this.persistAttributeWrites(),pt(JSON.stringify(s))+256):0}catch(t){return 0}}optOut(){this.isInitialized?(this.logger.info("User opted out of tracking"),this.userOptedOut=!0,this.writeOptOut(),this.storage.remove(Pe),this.syncOptOutMarker(),this.applyPrivacyState()):this.logger.error("SDK not initialized")}optIn(){this.isInitialized?(this.logger.info("User opted in to tracking"),this.userOptedOut=!1,this.liftDataGate("optedOut"),this.writeOptIn(),this.applyPrivacyState(),this.storage.remove(Pe),this.syncOptOutMarker()):this.logger.error("SDK not initialized")}updateConsent(t){this.isInitialized?"granted"===t||"denied"===t||"pending"===t?(this.trackingConsent=this.storeConsent(t),this.config.trackingConsent=this.trackingConsent,"granted"===t&&this.liftDataGate("denied"),this.applyPrivacyState(),this.syncOptOutMarker()):this.logger.error("updateConsent expects 'granted', 'denied' or 'pending', got "+t):this.logger.error("SDK not initialized")}isDoNotTrackEnabled(){if("undefined"==typeof window||"undefined"==typeof navigator)return!1;const t=navigator.doNotTrack||window.doNotTrack||navigator.msDoNotTrack;return"1"===t||"yes"===t}async loadPlugins(){for(const t of this.config.plugins)try{this.logger.debug(`Loading plugin: ${t.name} v${t.version}`),await t.load(this),this.logger.info("Plugin loaded: "+t.name)}catch(i){this.logger.error(`Failed to load plugin ${t.name}:`,i)}}async unloadPlugins(){for(const t of this.config.plugins)try{this.logger.debug("Unloading plugin: "+t.name),await t.unload()}catch(i){this.logger.error(`Failed to unload plugin ${t.name}:`,i)}}get user(){var t;return this.isInitialized||null===(t=this.logger)||void 0===t||t.error("SDK not initialized"),this.o}get push(){var t;return this.isInitialized||null===(t=this.logger)||void 0===t||t.error("SDK not initialized"),this.i}ecommerce(t){var i;return this.isInitialized||null===(i=this.logger)||void 0===i||i.error("SDK not initialized"),this.t&&!t||(this.t=Hi(this,t,this.logger)),this.t}setSdkAuthenticationToken(t){var i;this.isInitialized?this.config.enableSdkAuthentication?this.network.setSdkAuthenticationToken(t):this.logger.warn("setSdkAuthenticationToken called but enableSdkAuthentication is false - ignoring"):null===(i=this.logger)||void 0===i||i.error("SDK not initialized")}setStorefrontIdentityToken(t){var i;this.isInitialized?this.network.setStorefrontIdentityToken(t):null===(i=this.logger)||void 0===i||i.error("SDK not initialized")}setStorefrontIdentityTokenProvider(t){var i;this.isInitialized?this.network.setStorefrontIdentityTokenProvider(t):null===(i=this.logger)||void 0===i||i.error("SDK not initialized")}setSdkAuthenticationErrorCallback(t){var i;this.isInitialized?this.network.setSdkAuthenticationFailureCallback(t):null===(i=this.logger)||void 0===i||i.error("SDK not initialized")}getAnonymousId(){return this.identity?this.identity.getAnonymousId():""}getUserId(){return this.identity?this.identity.getUserId():null}liftDataGate(t){if(!this.dataGate.has(t))return;const i=new Set(this.dataGate);i.delete(t),this.dataGate=i}isDroppingDataCalls(t){return 0!==this.dataGate.size&&(this.logger.debug(t+"() in a ready() callback queued while tracking was off: dropped"),!0)}ready(t){if("function"==typeof t)try{t(this)}catch(t){this.logger.error("Error in ready() callback:",t)}else this.logger.error("ready(callback) requires a function")}getIdentity(){return this.identity.getIdentity()}getSessionInfo(){return this.session.getSessionInfo()}getUTMData(){return this.utm.getUTMData()}updateUTM(){this.isInitialized?(this.utm.updateUTM(),this.config.resetSessionOnNewCampaign&&this.utm.hasNewCampaign()&&(this.logger.info("New campaign detected, resetting session"),this.session.resetSession())):this.logger.error("SDK not initialized")}async syncInAppCampaigns(t){if(this.isInitialized)if(this.config.inApp.enabled)if(this.canSend())try{await this.inapp.sync(t)}catch(t){this.logger.error("In-app sync failed:",t)}else this.logger.debug("Tracking disabled or consent pending, not syncing in-app campaigns");else this.logger.warn("In-app messaging is not enabled");else this.logger.error("SDK not initialized")}getInAppCampaigns(){return this.isInitialized?this.config.inApp.enabled?this.inapp.getCampaigns():[]:(this.logger.error("SDK not initialized"),[])}async displayInAppCampaign(t){if(!this.isInitialized)return void this.logger.error("SDK not initialized");if(!this.config.inApp.enabled)return void this.logger.warn("In-app messaging is not enabled");if(!this.canSend())return void this.logger.debug("Tracking disabled or consent pending, not displaying in-app campaign");const i=this.inapp.getCampaigns().find(i=>i.id===t);if(i)try{await this.inapp.displayCampaign(i)}catch(t){this.logger.error("In-app display failed:",t)}else this.logger.error(`Campaign ${t} not found`)}dismissInAppMessage(t){this.isInitialized?this.config.inApp.enabled&&this.inapp.dismiss(t).catch(t=>this.logger.error("In-app dismiss failed:",t)):this.logger.error("SDK not initialized")}async trackInAppConversion(t,i){if(this.isInitialized){if(!this.isDroppingDataCalls("trackInAppConversion"))if(this.config.inApp.enabled)if(this.canSend())try{await this.inapp.trackConversion(t,i)}catch(t){this.logger.error("In-app conversion failed:",t)}else this.logger.debug("Tracking disabled or consent pending, not tracking in-app conversion");else this.logger.warn("In-app messaging is not enabled")}else this.logger.error("SDK not initialized")}placementConsent(){return!this.isInitialized||this.disabled||this.network.isSuspended()?null:this.canSend()?"granted":this.consentPending?"pending":"denied"}setLinkHandler(t){var i;"function"==typeof t?this.links.setHandler(t):null===(i=this.logger)||void 0===i||i.warn("setLinkHandler() needs a function; use clearLinkHandler() to remove one")}clearLinkHandler(){this.links.setHandler(null)}setPageVariables(t){var i;try{null===(i=this.pageContext)||void 0===i||i.setPageVariables(t)}catch(t){this.logger.warn("setPageVariables failed:",t)}}insertPlacement(t,i,e){return this.isInitialized?this.placements.insertPlacement(t,i,e):(this.logger.error("SDK not initialized"),null)}async getPlacements(t){return this.isInitialized?this.placements.getPlacements(t):(this.logger.error("SDK not initialized"),{})}async refreshPlacements(t){this.isInitialized&&await this.placements.refreshPlacements(t)}onPlacementsUpdated(t){return this.isInitialized?this.placements.onPlacementsUpdated(t):(this.logger.error("SDK not initialized"),ti(()=>{}))}async getCards(t){return this.isInitialized?this.cards.getCards(t):(this.logger.error("SDK not initialized"),{cards:[],unreadCount:0,nextCursor:null,stateScope:"server"})}getUnreadCardCount(){return this.isInitialized?this.cards.getUnreadCardCount():0}markCardViewed(t){this.isInitialized&&this.cards.markCardViewed(t)}markCardRead(t){this.isInitialized&&this.cards.markCardRead(t)}markCardClicked(t){this.isInitialized&&this.cards.markCardClicked(t)}dismissCard(t){this.isInitialized&&this.cards.dismissCard(t)}async refreshCards(){this.isInitialized&&await this.cards.refreshCards()}onCardsUpdated(t){return this.isInitialized?this.cards.onCardsUpdated(t):(this.logger.error("SDK not initialized"),ti(()=>{}))}mountCardFeed(t,i){return this.isInitialized?this.cards.mountCardFeed(t,i):(this.logger.error("SDK not initialized"),null)}getFlag(t,i){return this.isInitialized?this.flags.getFlag(t,i):i}getBoolFlag(t,i){return this.isInitialized?this.flags.getBoolFlag(t,i):i}getStringFlag(t,i){return this.isInitialized?this.flags.getStringFlag(t,i):i}getNumberFlag(t,i){return this.isInitialized?this.flags.getNumberFlag(t,i):i}getJsonFlag(t,i){return this.isInitialized?this.flags.getJsonFlag(t,i):i}getAllFlags(){return this.isInitialized?this.flags.getAllFlags():{}}async refreshFlags(){this.isInitialized&&await this.flags.refreshFlags()}onFlagsUpdated(t){return this.isInitialized?this.flags.onFlagsUpdated(t):(this.logger.error("SDK not initialized"),ti(()=>{}))}async destroy(){var t,i,e;this.isInitialized&&(this.logger.info("Destroying SDK instance"),null!==this.attributeFlushTimer&&(clearTimeout(this.attributeFlushTimer),this.attributeFlushTimer=null,this.canSend()&&this.flushAttributeOps()),this.outbox.destroy(),this.i.destroy(),"undefined"!=typeof window&&"function"==typeof window.removeEventListener&&(this.boundHandlePageUnload&&(window.removeEventListener("pagehide",this.boundHandlePageUnload),window.removeEventListener("beforeunload",this.boundHandlePageUnload)),this.boundHandleOnline&&window.removeEventListener("online",this.boundHandleOnline),this.boundHandleStorage&&window.removeEventListener("storage",this.boundHandleStorage)),this.boundHandlePageUnload=null,this.boundHandleOnline=null,this.boundHandleStorage=null,null!==this.pruneTimer&&(clearTimeout(this.pruneTimer),this.pruneTimer=null),await this.queue.flush().catch(()=>{}),this.queue.stop(),await this.unloadPlugins(),this.session.destroy(),this.inapp.clearAll(),this.inapp.destroy(),this.placements.destroy(),this.cards.destroy(),null===(t=this.pageEdits)||void 0===t||t.destroy(),null===(i=this.editor)||void 0===i||i.stop(),null===(e=this.pageContext)||void 0===e||e.destroy(),this.flags.destroy(),this.isInitialized=!1,Ve.instance===this&&(Ve.instance=null),this.logger.info("SDK destroyed"))}static getInstance(){return Ve.instance}}Ve.instance=null,Ve.ATTRIBUTE_FLUSH_DEBOUNCE_MS=800;const We=["init","optOut","optIn","updateConsent","wipeData"],Xe=["track","setAttributes","setAttribute","incrementAttribute","unsetAttribute","addToArray","removeFromArray","addAlias","trackInAppConversion"];function Ge(t){var i,e;try{const s=t&&t.joryio;if(!Array.isArray(s))return;const n=s.find(t=>Array.isArray(t)&&"init"===t[0]);if(!n){if(s.__joryioWaitingForInit)return;return s.__joryioWaitingForInit=!0,void(s.push=function(...i){for(let t=s.length+i.length-1e3;t>0;t--){const t=s.findIndex(t=>!(Array.isArray(t)&&We.includes(t[0])));if(0>t)break;s.splice(t,1)}const e=Array.prototype.push.apply(s,i);return i.some(t=>Array.isArray(t)&&"init"===t[0])&&Ge(t),e})}const r=s.slice(),o=r.indexOf(n),h=[],a=new Set;r.forEach((t,i)=>{if(!Array.isArray(t))return;const[e,s]=t;if("optOut"===e||"optIn"===e)h.push({method:e});else if("updateConsent"===e)h.push({method:e,consent:s});else{if("wipeData"!==e||i>=o)return;h.push({method:e})}a.add(t)});let l=null;try{l=new Ve(n[1],h)}catch(t){console.error("[Joryio] init failed:",t)}if(!l||Ve.getInstance()!==l){const i=s.indexOf(n);return 0>i||s.splice(i,1),s.__joryioWaitingForInit=!1,void Ge(t)}const u=new Map,c=function(t,i,e=t.length,s=new Map){const n=new Set,r=(t,i)=>{n.add(t);const e=s.get(t)||new Set;e.add(i),s.set(t,e)};let o=!!(null==i?void 0:i.optedOut),h=(null==i?void 0:i.consent)||"granted";const a=[],l=(t=!1)=>{const i=a.filter(i=>t&&"ready"===i[0]);a.forEach(t=>{i.includes(t)||r(t,"purged")}),a.length=0,a.push(...i)};return t.forEach((t,i)=>{if(!Array.isArray(t))return;const[s,n]=t;"optOut"===s?(o=!0,l()):"optIn"===s?o=!1:"updateConsent"===s?("granted"===n||"denied"===n?h=n:"pending"===n&&"denied"!==h&&(h="pending"),"denied"===n&&l()):"wipeData"===s&&e>i?l(!0):(Xe.includes(s)||"ready"===s)&&(o&&r(t,"optedOut"),"denied"===h&&r(t,"denied"),o||"denied"===h||a.push(t))}),n}(r,Ee.get(l),o,u);t.joryio=l;for(const t of r){if(!Array.isArray(t)||a.has(t))continue;const[s,...n]=t;if("init"===s)continue;const r=c.has(t);if(r&&"ready"!==s){null===(e=null===(i=l.logger)||void 0===i?void 0:i.debug)||void 0===e||e.call(i,s+" queued before load dropped: tracking was off when it was called");continue}const o=l[s];if("function"==typeof o)try{let i;r?Ue(l,u.get(t)||[],()=>i=o.apply(l,n)):i=o.apply(l,n),i&&"function"==typeof i.catch&&i.catch(t=>{console.error(`[Joryio] Error executing ${s+""}:`,t)})}catch(t){console.error(`[Joryio] Error executing ${s+""}:`,t)}else console.warn("[Joryio] Unknown method queued before load: "+s)}}catch(t){console.error("[Joryio] Could not process the snippet queue:",t)}}return"undefined"!=typeof window&&(window.Joryio=Ve,Ge(window)),t.CARD_FEED_TTL_SECONDS=mi,t.CARD_MIN_REFRESH_SECONDS=30,t.EcommerceTracker=Li,t.FLAGS_MIN_REFRESH_SECONDS=60,t.FLAG_SYNC_PUSH_VALUE="flags",t.IN_APP_DISPLAY_DWELL_MS=Lt,t.JoryioSDK=Ve,t.PLACEMENT_MIN_REFRESH_SECONDS=30,t.PLACEMENT_PRODUCT_CARD_WIDTH=160,t.PLACEMENT_PRODUCT_ELEMENT_PREFIX=ii,t.PLACEMENT_VIEWABLE_FRACTION=.5,t.PushManager=ne,t.SDK_VERSION=s,t.User=Fi,t.createEcommerceTracker=Hi,t.default=Ve,t.installSnippetQueue=Ge,t.placementProductElementId=ei,Object.defineProperty(t,"__esModule",{value:!0}),function(t,i){if("object"==typeof module&&module&&"object"==typeof module.exports)module.exports=i;else if(t&&(t.JoryioSDK=i),"function"==typeof define&&define.amd){var e="undefined"!=typeof document?document.currentScript:null;e&&"function"==typeof e.getAttribute&&e.getAttribute("data-requiremodule")?define(function(){return i}):define("joryio-web-sdk",[],function(){return i})}}("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:null,t),t}({});
6
+ var JoryioSDK=function(t){"use strict";const i=16777619;function e(t){let e=2166136261;for(let s=0;s<t.length;s++){const n=t.charCodeAt(s);e^=255&n,e=Math.imul(e,i),e^=n>>>8&255,e=Math.imul(e,i)}return s=e>>>0,s=Math.imul(s^=s>>>16,2246822507),s=Math.imul(s^=s>>>13,3266489909),(s^=s>>>16)>>>0;var s}const s="1.4.0-beta.7",n="X-Joryio-SDK",r="X-Joryio-SDK-Version";function o(){return{[n]:"web",[r]:s}}function h(t){const i=(t||"").trim();if(!i)return"https://api-eu1.joryio.com/api";const e=(/^https?:\/\//i.test(i)?i:"https://"+i).replace(/\/+$/,"");try{const t=new URL(e);if(""===t.pathname||"/"===t.pathname)return e+"/api"}catch(t){}return e}const a={allowHtmlJsInAppMessages:"inApp",evaluationMode:"inApp",syncInterval:"inApp",displayOptions:"inApp"};const l=["source","medium","campaign","term","content"],u=["page_view","exit_intent","scroll_depth","time_on_page"],c="page_context",d=/^[A-Za-z_$][A-Za-z0-9_$.-]{0,63}$/;function f(t){const i=(t||"/").toLowerCase();return i.length>1&&i.endsWith("/")?i.slice(0,-1):i}function p(t,i){var e;const s=/^(https?:\/\/[^/]+)(.*)$/i.exec(i);if(!s)return!1;const n=s[1].toLowerCase(),r=s[2]||"/";let o=((null!==(e=t.value)&&void 0!==e?e:"")+"").trim();const h="contains"===t.op?n+r:r,a="contains"===t.op?null:/^(https?:\/\/[^/?#]+)([^?#]*)/i.exec(o);if(a){if(a[1].toLowerCase()!==n)return!1;o=a[2]||"/"}switch(t.op){case"equals":return f(o)===f(h);case"contains":return!!o&&h.toLowerCase().includes(o.toLowerCase());case"matches":return function(t,i){const e=f(t),s=f(i),n=[];for(let t=0;t<e.length;t++)if("*"===e[t])if("*"===e[t+1])for(n.push("**");"*"===e[t+1];)t++;else n.push("*");else n.push(e[t]);let r=Array(s.length+1).fill(!1);r[0]=!0;for(const t of n){const i=Array(s.length+1).fill(!1);if("*"===t||"**"===t)for(let e=0;e<=s.length;e++)(r[e]||e>0&&i[e-1]&&("**"===t||"/"!==s[e-1]))&&(i[e]=!0);else for(let e=1;e<=s.length;e++)i[e]=r[e-1]&&s[e-1]===t;r=i}return r[s.length]}(o,h);default:return!1}}function y(t){var i,e,s,n,r;return!(!t||!(null===(e=null===(i=t.urls)||void 0===i?void 0:i.include)||void 0===e?void 0:e.length)&&!(null===(n=null===(s=t.urls)||void 0===s?void 0:s.exclude)||void 0===n?void 0:n.length)&&!(null===(r=t.variables)||void 0===r?void 0:r.length))}const v=t=>!!t&&u.includes(t.type+"");function m(){try{const t="undefined"!=typeof window?window.location:void 0;return t&&t.origin&&"null"!==t.origin?`${t.origin}${t.pathname}`:null}catch(t){return null}}function b(t){return"string"==typeof t?t.slice(0,200):"number"==typeof t&&Number.isFinite(t)||"boolean"==typeof t?t:void 0}function g(t,i){let e=t;for(const t of i.split(".")){if(null===e||"object"!=typeof e||!Object.prototype.hasOwnProperty.call(e,t))return;e=e[t]}return e}class w{constructor(t={}){this.options=t,this.explicit={},this.listeners=new Set,this.url=m(),this.maxScrollPercent=0,this.visibleMs=0,this.visibleSince=null,this.exitFired=!1,this.timer=null,this.undo=[],this.started=!1,this.utmSource=null}setUtmSource(t){this.utmSource=t}utm(){let t=null;try{t=this.utmSource?this.utmSource():null}catch(t){return}if(!t)return;const i=t=>{if(!t||"object"!=typeof t)return;const i=t,e={};for(const t of l){const s=i["utm_"+t];"string"==typeof s&&s.trim()&&(e[t]=s.trim().slice(0,200))}return Object.keys(e).length?e:void 0},e=i(t.current),s=i(t.firstTouch);return e||s?Object.assign(Object.assign({},e?{session:e}:{}),s?{firstTouch:s}:{}):void 0}setPageVariables(t){const i={};let e=0;for(const[s,n]of Object.entries(t||{})){if(e>=20||!d.test(s))continue;const t=b(n);void 0!==t&&(i[s]=t,e++)}this.explicit=i}current(){const t=Object.assign({},this.explicit),i="undefined"!=typeof window?window:{};for(const e of(this.options.pageVariables||[]).slice(0,20)){if(Object.keys(t).length>=20)break;if(d.test(e)&&!(e in t))try{const s=b(g(i,e));void 0!==s&&(t[e]=s)}catch(t){}}const e={},s=(this.options.dataLayerVariables||[]).filter(t=>d.test(t)).slice(0,20);if(s.length)try{const t=i[this.options.dataLayerName||"dataLayer"];if(Array.isArray(t))for(let i=t.length-1;i>=0&&Object.keys(e).length<s.length;i--){const n=t[i];if(n&&"object"==typeof n&&!Array.isArray(n))for(const t of s){if(t in e)continue;const i=b(g(n,t));void 0!==i&&(e[t]=i)}}}catch(t){}const n=this.utm();return Object.assign({url:this.url,pageVariables:t,dataLayer:e},n?{utm:n}:{})}progress(){const t=null!==this.visibleSince?Date.now()-this.visibleSince:0;return{scrollPercent:this.maxScrollPercent,seconds:Math.floor((this.visibleMs+t)/1e3),exitIntent:this.exitFired}}onSignal(t){return this.listeners.add(t),()=>this.listeners.delete(t)}start(){if(this.started||"undefined"==typeof window||"undefined"==typeof document)return;this.started=!0,this.patchHistory();const t=(t,i,e,s)=>{t.addEventListener(i,e,s),this.undo.push(()=>t.removeEventListener(i,e,s))};t(window,"popstate",()=>this.checkRoute()),t(window,"scroll",()=>this.measureScroll(),{passive:!0}),t(document,"mouseout",t=>{this.exitFired||t.relatedTarget||t.toElement||"number"!=typeof t.clientY||t.clientY>0||(this.exitFired=!0,this.emit({type:"exit_intent"}))}),t(document,"visibilitychange",()=>this.visibilityChanged()),"hidden"!==document.visibilityState&&(this.visibleSince=Date.now()),this.timer=setInterval(()=>{const{seconds:t}=this.progress();null!==this.visibleSince&&this.emit({type:"time_on_page",seconds:t}),this.checkRoute()},1e3)}destroy(){this.timer&&clearInterval(this.timer),this.timer=null;for(const t of this.undo.splice(0).reverse())try{t()}catch(t){}this.listeners.clear(),this.started=!1}checkRoute(){const t=m();t!==this.url&&(this.url=t,this.maxScrollPercent=0,this.visibleMs=0,this.visibleSince="undefined"!=typeof document&&"hidden"===document.visibilityState?null:Date.now(),this.exitFired=!1,this.emit({type:"page_change",url:t}))}patchHistory(){const t="undefined"!=typeof history?history:null;if(t)for(const i of["pushState","replaceState"]){const e=t[i];if("function"!=typeof e)continue;const s=this,n=function(...t){const i=e.apply(this,t);try{s.checkRoute()}catch(t){}return i};t[i]=n,this.undo.push(()=>{t[i]===n&&(t[i]=e)})}}measureScroll(){var t;try{const i=document.documentElement,e=Math.max(i.scrollHeight,(null===(t=document.body)||void 0===t?void 0:t.scrollHeight)||0)-window.innerHeight,s=e>0?Math.min(100,Math.round((window.scrollY||i.scrollTop)/e*100)):100;s>this.maxScrollPercent&&(this.maxScrollPercent=s,this.emit({type:"scroll_depth",percent:s}))}catch(t){}}visibilityChanged(){"hidden"===document.visibilityState?(null!==this.visibleSince&&(this.visibleMs+=Date.now()-this.visibleSince),this.visibleSince=null):null===this.visibleSince&&(this.visibleSince=Date.now())}emit(t){for(const i of Array.from(this.listeners))try{i(t)}catch(t){}}}function k(t,i,e){const s=+t.value;switch(t.type){case"page_view":return"page_change"===i.type;case"exit_intent":return"exit_intent"===i.type;case"scroll_depth":return("scroll_depth"===i.type||"page_change"===i.type)&&Number.isFinite(s)&&s>0&&e.scrollPercent>=s;case"time_on_page":return"time_on_page"===i.type&&Number.isFinite(s)&&s>0&&e.seconds>=s;default:return!1}}const S=["before","after","prepend","append","replace"],j=/^[a-z0-9][a-z0-9_]{0,63}$/,O="joryio-page-edits-anti-flicker",A="data-joryio-applied",I="data-joryio-orig",_="data-joryio-server-spot",T=(t,i)=>{var e,s,n,r,o,h;return t.id===i.id&&t.selector===i.selector&&t.operation===i.operation&&(null!==(e=t.value)&&void 0!==e?e:null)===(null!==(s=i.value)&&void 0!==s?s:null)&&(null!==(n=t.placementKey)&&void 0!==n?n:null)===(null!==(r=i.placementKey)&&void 0!==r?r:null)&&(null!==(o=t.position)&&void 0!==o?o:null)===(null!==(h=i.position)&&void 0!==h?h:null)&&!i.personalized};function $(t){if("string"!=typeof t||t.length>2048)return null;if(/[\u0000-\u001f\u007f]/.test(t))return null;const i=t.trim();return/^https?:\/\//i.test(i)?t:/^[a-z][a-z0-9+.-]*:/i.test(i)?null:t}const D=t=>"string"==typeof t&&t.split(",").every(t=>!t.trim()||null!==$(t.trim().split(/\s+/)[0]))?t:null;function C(t){const i=t.style.getPropertyValue("display"),e=t.style.getPropertyPriority("display");return t.style.setProperty("display","none","important"),()=>i?t.style.setProperty("display",i,e):t.style.removeProperty("display")}function P(t,i){var e;const s=t.getAttribute("style")||"",n="string"==typeof i.style?i.style:null,r=null===n?"":n.trim().replace(/;+$/,"");s===(r?r+";":"")+"display:none !important"?null===n?t.removeAttribute("style"):t.setAttribute("style",n):"none"===(null===(e=t.style)||void 0===e?void 0:e.getPropertyValue("display"))&&t.style.removeProperty("display")}const M=new Set(["A","ABBR","B","BDI","BDO","BR","CITE","CODE","DATA","DEL","DFN","EM","I","IMG","INS","KBD","MARK","Q","S","SAMP","SMALL","SPAN","STRONG","SUB","SUP","TIME","U","VAR","WBR"]),x=new Set(["class","id","title","lang","dir","alt","width","height","datetime","href","src","srcset","rel","target"]);function K(t){const i=document.createDocumentFragment();let e=500;const s=(t,i)=>{for(const n of Array.from(t.childNodes)){if(0>=e--)return;if(3===n.nodeType)i.appendChild(document.createTextNode(n.nodeValue||""));else if(1===n.nodeType){const t=n;if("http://www.w3.org/1999/xhtml"!==t.namespaceURI||!M.has(t.tagName)){/^(SCRIPT|STYLE|TEMPLATE|IFRAME|OBJECT|EMBED|NOSCRIPT|TEXTAREA|TITLE)$/.test(t.tagName)||s(t,i);continue}const e=document.createElement(t.tagName.toLowerCase());for(const i of Array.from(t.attributes)){const t=i.name.toLowerCase();if(x.has(t))if("href"===t||"src"===t){const s=$(i.value);null!==s&&e.setAttribute(t,s)}else if("srcset"===t){const s=D(i.value);null!==s&&e.setAttribute(t,s)}else e.setAttribute(t,i.value)}i.appendChild(e),s(t,e)}}};return s(t,i),i}const N=t=>(t.getAttribute(A)||"").split(/\s+/).filter(Boolean);function F(t){if("string"!=typeof t)return!1;const i=t.trim();if(!i||i.length>500)return!1;if(/[{};<@]/.test(i)||i.includes("/*")||i.includes("*/"))return!1;if(/[\u0000-\u001f\u007f]/.test(i))return!1;try{"undefined"!=typeof document&&document.createDocumentFragment().querySelector(i)}catch(t){return!1}return!0}function E(t){if(!t||"object"!=typeof t||"string"!=typeof t.id||!F(t.selector))return null;const i=Object.assign({id:t.id,selector:t.selector.trim()},!0===t.personalized?{personalized:!0}:{});switch(t.operation){case"hide":return Object.assign(Object.assign({},i),{operation:"hide"});case"replace_text":return"string"!=typeof t.value||t.value.length>2e3?null:Object.assign(Object.assign({},i),{operation:"replace_text",value:t.value});case"replace_image":case"replace_link":return function(t){if("string"!=typeof t)return!1;const i=t.trim();return!(!i||i.length>2048)&&!/[\u0000-\u001f\u007f\s]/.test(i)&&/^https?:\/\/[^/?#\s]+/i.test(i)}(t.value)?Object.assign(Object.assign({},i),{operation:t.operation,value:t.value.trim()}):null;case"insert_placement":return"string"==typeof t.placementKey&&j.test(t.placementKey)?Object.assign(Object.assign({},i),{operation:"insert_placement",placementKey:t.placementKey,position:S.includes(t.position)?t.position:"after"}):null;default:return null}}class U{constructor(t,i,s,n,r,o,h){this.apiEndpoint=t,this.sdkKey=i,this.identity=s,this.session=n,this.logger=r,this.runtime=o,this.auth=h,this.page=null,this.pageUnsubscribe=null,this.experiences=[],this.applied=[],this.reported=new Set,this.observer=null,this.scheduled=!1,this.flickerTimer=null,this.pageStartedAt=0,this.site=null,this.siteRequest=null,this.server=null,this.serverUrl=null,this.generation=0,this.started=!1,this.destroyed=!1,this.stores=(t=>{const i=e(t).toString(36);return{answers:"jry_page_edits_"+i,selectors:"jry_page_edit_selectors_"+i,site:"jry_page_edit_site_"+i}})(i);try{localStorage.removeItem("jry_page_edit_selectors"),sessionStorage.removeItem("jry_page_edits")}catch(t){}}setPageContext(t){var i;null===(i=this.pageUnsubscribe)||void 0===i||i.call(this),this.pageUnsubscribe=null,this.page=t,t&&(this.pageUnsubscribe=t.onSignal(t=>{"page_change"===t.type&&this.started&&this.loadPage()}))}start(){this.started||this.destroyed||"undefined"==typeof document||(this.started=!0,"undefined"!=typeof MutationObserver&&document.documentElement&&(this.observer=new MutationObserver(()=>this.schedule()),this.observer.observe(document.documentElement,{childList:!0,subtree:!0})),this.loadPage())}invalidate(t={}){this.generation++,this.reported.clear(),t.siteSettings&&this.forgetSite();try{sessionStorage.removeItem(this.stores.answers)}catch(t){}this.started&&this.loadPage()}destroy(){var t,i;this.destroyed=!0,null===(t=this.pageUnsubscribe)||void 0===t||t.call(this),null===(i=this.observer)||void 0===i||i.disconnect(),this.observer=null,this.revertAll(),this.showAll()}appliedCount(){return this.applied.length}serverAppliedCount(){return this.serverEdits().size}url(){return this.page?this.page.current().url:m()}loadPage(){const t=++this.generation;this.revertAll();const i=this.url();if(!i)return void(this.experiences=[]);this.pageStartedAt=Date.now();const e=this.serverEdits();null===this.serverUrl?this.serverUrl=i:i!==this.serverUrl&&e.size&&this.reconcileServer([]);const s=this.rememberedSelectors(i);this.hide(s),this.experiences=this.cachedExperiences(i),this.applyAll(),this.siteThenFetch(i,t,s.length>0)}async siteThenFetch(t,i,e){const s=this.storedSite();let n;if(s?(n=s.value,6e5>Date.now()-s.at||this.requestSite().then(e=>{!(e&&e.enabled&&e.active)||n.enabled&&n.active||i!==this.generation||this.destroyed||this.fetch(t,i)})):n=await this.siteSettings(),i===this.generation&&!this.destroyed){if(n&&(!n.enabled||!n.active))return this.revertAll(),this.reconcileServer([]),this.experiences=[],void this.showAll();n&&!e&&n.antiFlickerSelectors.length&&this.hide(n.antiFlickerSelectors),await this.fetch(t,i)}}siteSettings(){const t=this.storedSite();return t&&6e5>Date.now()-t.at?Promise.resolve(t.value):this.requestSite()}storedSite(){const t=this.session.getSessionId();if(!t)return null;if(this.site&&this.site.sid===t)return this.site;this.site=null;try{const i=JSON.parse(sessionStorage.getItem(this.stores.site)||"null"),e=null==i?void 0:i.value;i&&i.sid===t&&"number"==typeof i.at&&i.at<=Date.now()&&e&&"object"==typeof e?this.site={sid:t,at:i.at,value:{enabled:!1!==e.enabled,active:!1!==e.active,antiFlickerSelectors:(Array.isArray(e.antiFlickerSelectors)?e.antiFlickerSelectors:[]).filter(F).slice(0,200)}}:i&&sessionStorage.removeItem(this.stores.site)}catch(t){}return this.site}forgetSite(){this.site=null;try{sessionStorage.removeItem(this.stores.site)}catch(t){}}requestSite(){if(this.siteRequest)return this.siteRequest;const t=(async()=>{var t,i;const e=this.session.getSessionId();try{const s=await fetch(`${this.apiEndpoint}/v1/in-app/site-settings?sdkKey=${encodeURIComponent(this.sdkKey)}`,{method:"GET",credentials:"omit"});if(!s.ok)return null===(i=(t=this.runtime).noteStatus)||void 0===i||i.call(t,s.status,null),this.forgetSite(),null;const n=await s.json(),r=null==n?void 0:n.pageEdits;if(!r||"object"!=typeof r)return this.forgetSite(),null;const o={enabled:!1!==r.enabled,active:!1!==r.active,antiFlickerSelectors:(Array.isArray(r.antiFlickerSelectors)?r.antiFlickerSelectors:[]).filter(F).slice(0,200)};if(e){this.site={sid:e,at:Date.now(),value:o};try{sessionStorage.setItem(this.stores.site,JSON.stringify(this.site))}catch(t){}}return o}catch(t){return this.logger.debug("Site settings request failed",t),this.forgetSite(),null}finally{this.siteRequest=null}})();return this.siteRequest=t,t}async fetch(t,i){var e,s,n,r;const h=this.runtime.consent();if(null===h||this.destroyed)return void this.showAll();const a="granted"===h,l=a?this.identity.getUserId():null,u=a?this.identity.getAnonymousId():null,d=Object.assign(Object.assign(Object.assign(Object.assign({},l?{userId:l}:{}),u?{anonymousId:u}:{}),a?{sessionId:this.session.getSessionId()}:{}),{deviceType:"web",locale:"undefined"!=typeof navigator?navigator.language:void 0,capabilities:[c,"page_edits"],trackingConsent:h,context:this.page?this.page.current():{url:t,pageVariables:{},dataLayer:{}}}),f="undefined"!=typeof AbortController?new AbortController:null,p=setTimeout(()=>null==f?void 0:f.abort(),null!==(e=this.runtime.requestTimeoutMs)&&void 0!==e?e:1e4);try{const e=await fetch(this.apiEndpoint+"/v1/in-app/page-edits",Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),a&&(null===(s=this.auth)||void 0===s?void 0:s.getSdkAuthHeaders(l,l?null:u))||{}),body:JSON.stringify(d)},f?{signal:f.signal}:{}));if(i!==this.generation)return;if(!e.ok)return void(null===(r=(n=this.runtime).noteStatus)||void 0===r||r.call(n,e.status,null));const h=await e.json();if(i!==this.generation||!h||!1===h.success||!Array.isArray(h.experiences))return;const c=h.experiences.filter(t=>t&&"string"==typeof t.id).map(t=>({wire:t,edits:(Array.isArray(t.edits)?t.edits:[]).map(E).filter(t=>!!t)}));this.revertAll(),this.experiences=c,this.reconcileServer(c),this.remember(t,c,h.ttlSeconds),this.applyAll()}catch(t){this.logger.debug("Page edits request failed",t)}finally{clearTimeout(p),i===this.generation&&this.showAll()}}schedule(){if(this.scheduled||this.destroyed)return;this.scheduled=!0;const t=()=>{this.scheduled=!1,this.applyAll()};"function"==typeof queueMicrotask?queueMicrotask(t):Promise.resolve().then(t)}applyAll(){var t,i;if(!this.destroyed&&"undefined"!=typeof document){null===(t=this.observer)||void 0===t||t.disconnect();try{for(const t of this.experiences){if(t.wire.isControl){(t.wire.selectors||[]).some(t=>F(t)&&this.query(t).length>0)&&this.reportControl(t.wire);continue}let e=!1;for(const s of t.edits){const n=`${t.wire.id}:${s.id}`,r=this.serverEdits().get(n),o=!!r&&r.variantId===(null!==(i=t.wire.variantId)&&void 0!==i?i:null)&&T(r.edit,s);for(const t of this.query(s.selector)){if(this.applied.some(i=>i.el===t&&i.editId===s.id)){e=!0;continue}if(o&&N(t).includes(n)){e=!0;continue}const i=this.applyOne(t,s);i&&(this.applied.push({el:t,editId:s.id,undo:i}),e=!0)}}e&&this.reportDisplayed(t.wire)}}finally{this.observer&&document.documentElement&&this.observer.observe(document.documentElement,{childList:!0,subtree:!0})}}}query(t){try{return Array.from(document.querySelectorAll(t)).filter(t=>{var i,e;return!(null===(e=(i=t).closest)||void 0===e?void 0:e.call(i,"[data-joryio-editor]"))})}catch(t){return[]}}applyOne(t,i){var e;const s=t;switch(i.operation){case"replace_text":{const s=Array.from(t.childNodes);return t.textContent=null!==(e=i.value)&&void 0!==e?e:"",()=>{t.textContent="",s.forEach(i=>t.appendChild(i))}}case"replace_image":{if("IMG"!==t.tagName)return null;const e=t.getAttribute("src"),s=t.getAttribute("srcset");return t.setAttribute("src",i.value),t.removeAttribute("srcset"),()=>{null===e?t.removeAttribute("src"):t.setAttribute("src",e),null!==s&&t.setAttribute("srcset",s)}}case"replace_link":{if("A"!==t.tagName)return null;const e=t.getAttribute("href");return t.setAttribute("href",i.value),()=>null===e?t.removeAttribute("href"):t.setAttribute("href",e)}case"hide":return C(s);case"insert_placement":{const e=document.createElement("div");e.setAttribute("data-joryio-placement",i.placementKey),e.setAttribute("data-joryio-edit",i.id);const n="before"===i.position?"beforebegin":"prepend"===i.position?"afterbegin":"append"===i.position?"beforeend":"afterend";if(t.insertAdjacentElement(n,e),"replace"!==i.position)return()=>e.remove();const r=C(s);return()=>{e.remove(),r()}}default:return null}}revertAll(){var t;const i=this.applied.splice(0).reverse();if(i.length){null===(t=this.observer)||void 0===t||t.disconnect();try{for(const t of i)try{t.undo()}catch(t){}}finally{this.observer&&"undefined"!=typeof document&&document.documentElement&&this.observer.observe(document.documentElement,{childList:!0,subtree:!0})}}}hide(t){const i=t.filter(F);if(!i.length||"undefined"==typeof document)return;const e=300-(Date.now()-(this.pageStartedAt||Date.now()));if(0>=e)return;let s=document.getElementById(O);s||(s=document.createElement("style"),s.id=O,(document.head||document.documentElement).appendChild(s)),s.textContent=this.serverEdits().size?`:is(${i.join(",")}):not([${A}]){opacity:0 !important}`:i.join(",")+"{opacity:0 !important}",this.flickerTimer&&clearTimeout(this.flickerTimer),this.flickerTimer=setTimeout(()=>this.showAll(),e)}showAll(){var t;this.flickerTimer&&clearTimeout(this.flickerTimer),this.flickerTimer=null;try{null===(t=document.getElementById(O))||void 0===t||t.remove()}catch(t){}}subjectKey(){return`${this.identity.getUserId()||""}|${this.identity.getAnonymousId()}`}remember(t,i,e){const s=[...new Set(i.flatMap(t=>t.wire.isControl?[]:t.edits.map(t=>t.selector)))];try{const i=JSON.parse(localStorage.getItem(this.stores.selectors)||"{}")||{};delete i[t],s.length&&(i[t]=s.slice(0,50));const e=Object.keys(i);for(const t of e.slice(0,Math.max(0,e.length-50)))delete i[t];localStorage.setItem(this.stores.selectors,JSON.stringify(i))}catch(t){}try{const s=JSON.parse(sessionStorage.getItem(this.stores.answers)||"{}")||{},n=s.subject===this.subjectKey()&&s.pages?s.pages:{};n[t]={at:Date.now(),ttl:1e3*(e&&e>0?e:300),experiences:i.filter(t=>!t.wire.isControl).map(t=>Object.assign(Object.assign({},t.wire),{deliveryToken:null,edits:t.edits.filter(t=>!t.personalized)})).filter(t=>t.edits.length)},sessionStorage.setItem(this.stores.answers,JSON.stringify({subject:this.subjectKey(),pages:n}))}catch(t){}}rememberedSelectors(t){try{const i=JSON.parse(localStorage.getItem(this.stores.selectors)||"{}")||{};return Array.isArray(i[t])?i[t].filter(t=>"string"==typeof t):[]}catch(t){return[]}}cachedExperiences(t){var i;try{const e=JSON.parse(sessionStorage.getItem(this.stores.answers)||"{}")||{};if(e.subject!==this.subjectKey())return[];const s=null===(i=e.pages)||void 0===i?void 0:i[t];return!s||Date.now()-s.at>s.ttl?[]:(s.experiences||[]).map(t=>({wire:Object.assign(Object.assign({},t),{isControl:!1,deliveryToken:null}),edits:(t.edits||[]).map(E).filter(t=>!!t&&!t.personalized)}))}catch(t){return[]}}serverEdits(){if(this.server)return this.server;const t=new Map;if("undefined"==typeof document)return t;const i=function(){const t=document.head;if(!t)return null;for(const i of Array.from(t.children))if("joryio-server-page-edits"===i.id)return"SCRIPT"===i.tagName&&"application/json"===(i.getAttribute("type")||"").trim().toLowerCase()?i:null;return null}();if(!i)return"loading"!==document.readyState&&(this.server=t),t;try{const e=JSON.parse(i.textContent||"{}");if(e&&1===e.v&&Array.isArray(e.experiences))for(const i of e.experiences)if(i&&"string"==typeof i.id&&Array.isArray(i.edits))for(const e of i.edits){const s=E(e);s&&!s.personalized&&t.set(`${i.id}:${s.id}`,{experienceId:i.id,variantId:"string"==typeof i.variantId?i.variantId:null,edit:s})}}catch(t){}return this.server=t,t}reconcileServer(t){var i,e;const s=this.serverEdits();if(!s.size||"undefined"==typeof document)return;const n=new Set;for(const e of t)if(!e.wire.isControl)for(const t of e.edits){const r=`${e.wire.id}:${t.id}`,o=s.get(r);o&&o.variantId===(null!==(i=e.wire.variantId)&&void 0!==i?i:null)&&T(o.edit,t)&&n.add(r)}const r=[...s.keys()].filter(t=>!n.has(t));if(r.length){null===(e=this.observer)||void 0===e||e.disconnect();try{for(const t of r)this.undoServerEdit(t,s.get(t).edit),s.delete(t)}finally{this.observer&&document.documentElement&&this.observer.observe(document.documentElement,{childList:!0,subtree:!0})}}}undoServerEdit(t,i){for(const e of Array.from(document.querySelectorAll(`[${A}]`))){const s=N(e);if(!s.includes(t))continue;let n={};try{n=JSON.parse(e.getAttribute(I)||"{}")||{}}catch(t){n={}}const r=n[t]||{};try{switch(i.operation){case"replace_text":{const s=Array.from(e.children).find(i=>"TEMPLATE"===i.tagName&&i.getAttribute(I)===t);if(s&&s.content&&e.textContent===i.value){const t=K(s.content);e.textContent="",e.appendChild(t)}break}case"replace_image":if("IMG"===e.tagName&&e.getAttribute("src")===i.value){const t=$(r.src),i=D(r.srcset);null===t?e.removeAttribute("src"):e.setAttribute("src",t),null!==i&&e.setAttribute("srcset",i)}break;case"replace_link":if("A"===e.tagName&&e.getAttribute("href")===i.value){const t=$(r.href);null===t?e.removeAttribute("href"):e.setAttribute("href",t)}break;case"hide":P(e,r);break;case"insert_placement":"replace"===i.position&&P(e,r)}}catch(t){}const o=s.filter(i=>i!==t);o.length?e.setAttribute(A,o.join(" ")):e.removeAttribute(A),delete n[t],Object.keys(n).length?e.setAttribute(I,JSON.stringify(n)):e.removeAttribute(I)}if("insert_placement"===i.operation)for(const e of Array.from(document.querySelectorAll(`div[${_}][data-joryio-placement]`)))e.getAttribute(_)===t&&e.getAttribute("data-joryio-placement")===i.placementKey&&e.remove()}reportDisplayed(t){if(!t.deliveryToken||"granted"!==this.runtime.consent())return;const i="displayed:"+(t.deliveryId||t.deliveryToken);this.reported.has(i)||(this.reported.add(i),this.post(Object.assign(Object.assign({campaignId:t.id},t.variantId?{variantId:t.variantId}:{}),{deliveryToken:t.deliveryToken,action:"displayed",displayedAt:(new Date).toISOString()})))}reportControl(t){if(!t.controlToken||"granted"!==this.runtime.consent())return;const i="control:"+t.controlToken;this.reported.has(i)||(this.reported.add(i),this.post({action:"control_viewed",controlToken:t.controlToken,viewedAt:(new Date).toISOString()}))}post(t){var i;const e=this.identity.getUserId(),s=Object.assign(Object.assign(Object.assign({},t),e?{userId:e}:{}),{anonymousId:this.identity.getAnonymousId(),sessionId:this.session.getSessionId(),deviceType:"web"});fetch(this.apiEndpoint+"/v1/in-app/track",{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(i=this.auth)||void 0===i?void 0:i.getSdkAuthHeaders(e,e?null:this.identity.getAnonymousId()))||{}),body:JSON.stringify(s),keepalive:!0}).then(t=>{var i,e;t.ok||null===(e=(i=this.runtime).noteStatus)||void 0===e||e.call(i,t.status,null)}).catch(t=>this.logger.debug("Page edit report failed",t))}}const q="https://sdk.joryio.com",z=/\/joryio(?:\.umd)?(?:\.min)?\.js$/;function J(t){if(!t||"string"!=typeof t)return null;let i;try{i=new URL(t)}catch(t){return null}return"https:"===i.protocol&&z.test(i.pathname)?`${i.origin}${i.pathname.replace(/[^/]*$/,"")}`:null}const R=function(){if("undefined"==typeof document)return null;try{const t=document.currentScript,i=J(t&&t.src);if(i||t&&t.src)return i;const e=document.querySelectorAll("script[src]");for(let t=e.length-1;t>=0;t--){const i=J(e[t].src);if(i)return i}}catch(t){}return null}();function L(t,i,e=R,n=s){if(i)return[i];const r=n.split(".")[0],o=`${q}/web/${n}/${t}`,h=`${q}/web/${r}/${t}`,a=n.includes("-");let l=e&&e!==`${q}/web/${r}/`?[`${e}${t}`,o,h]:[o,h];return a&&(l=l.filter(t=>t!==h)),l.filter((t,i)=>l.indexOf(t)===i)}function H(t,i){return new Promise((e,s)=>{const n=document.createElement("script");n.src=t,n.async=!0,n.setAttribute(i,"bundle"),n.onload=()=>e(),n.onerror=()=>{n.remove(),s(Error("could not load "+t))},(document.head||document.documentElement).appendChild(n)})}const B="__joryioEditor";function V(){try{return"undefined"!=typeof window&&!!window.opener&&"1"===new URLSearchParams(window.location.search).get("joryio_editor")}catch(t){return!1}}function W(t){return H(t,"data-joryio-editor")}class X{constructor(t,i,e,s={}){this.apiEndpoint=t,this.sdkKey=i,this.logger=e,this.options=s,this.opener=null,this.dashboardOrigin=null,this.verifying=!1,this.session=null,this.off=null}start(){if(!V()||this.opener)return;this.opener=window.opener;const t=t=>{this.onMessage(t)};window.addEventListener("message",t),this.off=()=>window.removeEventListener("message",t);try{this.opener.postMessage({type:"joryio:editor-ready"},"*")}catch(t){}}isActive(){return!!this.session}stop(){var t;const i=this.session;this.session=null,null==i||i.stop(),null===(t=this.off)||void 0===t||t.call(this),this.off=null,this.dashboardOrigin=null,this.opener=null}async onMessage(t){var i;const e=t.data;if(e&&"string"==typeof e.type&&!this.dashboardOrigin&&"joryio:editor-token"===e.type&&t.source===this.opener&&"string"==typeof e.token&&!this.verifying){this.verifying=!0;try{const s=await fetch(this.apiEndpoint+"/v1/in-app/editor/verify",{method:"POST",headers:Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),body:JSON.stringify({token:e.token})}),n=s.ok?await s.json():null;if(!(null==n?void 0:n.valid)||"string"!=typeof n.dashboardOrigin||n.dashboardOrigin!==t.origin)return void this.logger.warn("Joryio editor: the editor token was not accepted for this site");this.dashboardOrigin=n.dashboardOrigin,null===(i=this.off)||void 0===i||i.call(this),this.off=null,await this.loadAndStart(n.dashboardOrigin)}catch(t){this.logger.debug("Joryio editor verification failed",t)}finally{this.verifying=!1}}}async loadAndStart(t){var i;const e=null!==(i=this.options.load)&&void 0!==i?i:W;let s=window[B];for(const t of s?[]:L("joryio-editor.min.js",this.options.scriptUrl))try{if(await e(t),s=window[B],s)break}catch(t){this.logger.debug("Joryio editor bundle failed to load",t)}s&&1===s.version&&"function"==typeof s.start&&this.opener?this.session=s.start({dashboardOrigin:t,opener:this.opener,logger:this.logger,onStop:()=>this.stop()}):this.logger.warn("Joryio editor: the editor could not be loaded (check that your Content-Security-Policy allows sdk.joryio.com)")}}class G{static hashKey(t){return e(t).toString(36)}constructor(t,i){this.memoryStore=new Map,this.prefix=`jry_${G.hashKey(t)}_`,this.logger=i,this.isLocalStorageAvailable=this.checkLocalStorageAvailable(),this.isLocalStorageAvailable||this.logger.warn("LocalStorage not available, using in-memory storage")}checkLocalStorageAvailable(){try{const t="__jry_test__";return localStorage.setItem(t,"test"),localStorage.removeItem(t),!0}catch(t){return!1}}getKey(t){return`${this.prefix}${t}`}storageKeyFor(t){return this.getKey(t)}set(t,i,e){const s={value:i,expiresAt:e?Date.now()+864e5*e:null};if(this.isLocalStorageAvailable)try{localStorage.setItem(this.getKey(t),JSON.stringify(s)),this.memoryStore.delete(t)}catch(i){this.logger.error("Failed to write to localStorage:",i);try{localStorage.removeItem(this.getKey(t))}catch(t){}this.memoryStore.set(t,s)}else this.memoryStore.set(t,s)}get(t){var i;let e=null;if(this.isLocalStorageAvailable)try{const i=localStorage.getItem(this.getKey(t));i&&(e=JSON.parse(i))}catch(i){this.logger.error("Failed to read from localStorage:",i);try{localStorage.removeItem(this.getKey(t))}catch(t){}}return e||(e=this.memoryStore.get(t)||null),e&&e.expiresAt&&e.expiresAt<Date.now()?(this.remove(t),null):null!==(i=null==e?void 0:e.value)&&void 0!==i?i:null}remove(t){if(this.isLocalStorageAvailable)try{localStorage.removeItem(this.getKey(t))}catch(t){this.logger.error("Failed to remove from localStorage:",t)}this.memoryStore.delete(t)}clear(){if(this.isLocalStorageAvailable)try{const t=[];for(let i=0;i<localStorage.length;i++){const e=localStorage.key(i);e&&e.startsWith(this.prefix)&&t.push(e)}t.forEach(t=>localStorage.removeItem(t))}catch(t){this.logger.error("Failed to clear localStorage:",t)}this.memoryStore.clear()}}function Q(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const i=16*Math.random()|0;return("x"===t?i:3&i|8).toString(16)})}function Z(){if("undefined"!=typeof crypto&&crypto.getRandomValues){const t=new Uint8Array(6);return crypto.getRandomValues(t),Date.now().toString(36)+Array.from(t,t=>t.toString(16).padStart(2,"0")).join("")}return Date.now().toString(36)+Math.random().toString(36).substr(2,9)}const Y="session_id",tt="session_start",it="last_activity",et=864e5;class st{constructor(t,i,e){this.currentSessionId=null,this.lastActivityAt=0,this.lastActivityPersistedAt=0,this.isNewSession=!1,this.onNewSessionCallback=null,this.boundVisibilityHandler=null,this.storage=t,this.logger=i,this.sessionTimeoutMs=e||18e5,this.initializeSession(),"undefined"!=typeof document&&(this.boundVisibilityHandler=()=>{"visible"===document.visibilityState&&this.checkAndRefreshSession()},document.addEventListener("visibilitychange",this.boundVisibilityHandler))}onNewSession(t){this.onNewSessionCallback=t}initializeSession(){const t=this.storage.get(Y),i=this.storage.get(it),e=this.storage.get(tt);if(t&&i){const s=Date.now(),n=s-i,r=e?s-e:1/0;if(n<this.sessionTimeoutMs&&et>r)return this.currentSessionId=t,this.isNewSession=!1,this.updateActivity(),void this.logger.debug("Resumed session: "+this.currentSessionId);et>r?this.logger.debug(`Session expired (${n}ms since last activity)`):this.logger.debug(`Session too old (${Math.round(r/1e3/60/60)}h), creating new session`)}this.startNewSession()}startNewSession(){const t=this.currentSessionId;this.currentSessionId=Z(),this.isNewSession=!0;const i=Date.now();this.storage.set(Y,this.currentSessionId),this.storage.set(tt,i),this.storage.set(it,i),this.lastActivityAt=i,this.lastActivityPersistedAt=i,this.logger.debug("Started new session: "+this.currentSessionId),t&&this.onNewSessionCallback&&this.onNewSessionCallback()}checkAndRefreshSession(){const t=this.storage.get(it),i=this.storage.get(tt);if(t&&i){const e=Date.now(),s=e-t,n=e-i;s<this.sessionTimeoutMs?et>n||(this.logger.debug(`Session too old on tab focus (${Math.round(n/1e3/60/60)}h old)`),this.startNewSession()):(this.logger.debug(`Session expired on tab focus (${Math.round(s/1e3/60)} min inactive)`),this.startNewSession())}}refreshIfExpired(){if(!this.currentSessionId)return!1;const t=Date.now(),i=Math.max(this.lastActivityAt,this.storage.get(it)||0)||t,e=this.storage.get(tt)||t;return t-i<this.sessionTimeoutMs?t-e>=et&&(this.logger.debug("Session reached its maximum age"),this.startNewSession(),!0):(this.logger.debug(`Session expired (${Math.round((t-i)/1e3/60)} min inactive)`),this.startNewSession(),!0)}updateActivity(){if(!this.currentSessionId)return;const t=Date.now();this.lastActivityAt=t,3e4>t-this.lastActivityPersistedAt||(this.lastActivityPersistedAt=t,this.storage.set(it,t))}getSessionInfo(){return{sessionId:this.currentSessionId||this.storage.get(Y)||"",sessionStart:this.storage.get(tt)||Date.now(),lastActivity:this.lastActivityAt||this.storage.get(it)||Date.now(),isNewSession:this.isNewSession}}getSessionId(){return this.currentSessionId||this.storage.get(Y)||""}ensureSession(){if(this.currentSessionId)return this.currentSessionId;const t=this.storage.get(Y);if(t)return this.currentSessionId=t,t;this.currentSessionId=Z(),this.isNewSession=!0;const i=Date.now();return this.storage.set(Y,this.currentSessionId),this.storage.set(tt,i),this.storage.set(it,i),this.lastActivityAt=i,this.lastActivityPersistedAt=i,this.logger.debug("Started new session: "+this.currentSessionId),this.onNewSessionCallback&&this.onNewSessionCallback(),this.currentSessionId}followStoredSession(){const t=this.storage.get(Y);return t!==this.currentSessionId&&(this.currentSessionId=t||null,this.isNewSession=!1,this.lastActivityAt=t?this.storage.get(it)||Date.now():0,this.lastActivityPersistedAt=this.lastActivityAt,this.logger.debug("Following the session another tab started: "+(t||"(none)")),!0)}renewSession(){this.updateActivity(),this.logger.debug("Session renewed: "+this.currentSessionId)}resetSession(){this.logger.debug(`Resetting session (was: ${this.currentSessionId})`),this.startNewSession()}clear(){this.currentSessionId=null,this.isNewSession=!1,this.lastActivityAt=0,this.lastActivityPersistedAt=0,this.storage.remove(Y),this.storage.remove(tt),this.storage.remove(it)}destroy(){this.boundVisibilityHandler&&"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.boundVisibilityHandler=null)}}function nt(t,i){return t&&i?t.anonymousId===i.anonymousId&&(t.userId||null)===(i.userId||null):!t&&!i}class rt{constructor(t=500){this.maxEntries=t,this.entries=[]}add(t,i,e,s){if(!i)return;const n=s?Object.assign({},s):void 0;if("set"===t||"unset"===t)return this.entries=this.entries.filter(t=>t.key!==i||t.inFlight||!nt(t.owner,n)),this.entries.push("set"===t?{key:i,kind:t,value:e,owner:n}:{key:i,kind:t,owner:n}),void this.trim();const r=this.lastFor(i);if(r&&!r.inFlight&&r.kind===t&&nt(r.owner,n))if("increment"===t)r.value=(+r.value||0)+ +e;else for(const t of ot(e))ht(r.values,t)||r.values.push(t);else"increment"===t?this.entries.push({key:i,kind:t,value:+e,owner:n}):this.entries.push({key:i,kind:t,values:at(ot(e)),owner:n}),this.trim()}mark(t,i){for(const[e,s]of Object.entries(t.attributes||{}))this.add("set",e,s,i);for(const e of t.unset||[])this.add("unset",e,void 0,i);for(const[e,s]of Object.entries(t.increment||{}))"number"==typeof s&&Number.isFinite(s)&&this.add("increment",e,s,i);for(const[e,s]of Object.entries(t.append||{}))this.add("append",e,s,i);for(const[e,s]of Object.entries(t.remove||{}))this.add("remove",e,s,i)}isEmpty(){return 0===this.entries.length}hasUnsent(){return this.entries.some(t=>!t.inFlight)}nextRequest(t){return this.build(!0,t)}peekRequest(t){return this.build(!1,t)}toOps(){var t,i;return null!==(i=null===(t=this.peekRequest())||void 0===t?void 0:t.ops)&&void 0!==i?i:null}acknowledge(t){const i=new Set(t);this.entries=this.entries.filter(t=>!i.has(t))}release(t,i){let e=0;const s=new Set(t);return this.entries=this.entries.filter(t=>!s.has(t)||(t.inFlight=!1,!i||"increment"!==t.kind||(e++,!1))),e}drop(t){this.acknowledge(t)}dropIncrements(t){const i=new Set(t.filter(t=>"increment"===t.kind));this.entries=this.entries.filter(t=>!i.has(t))}pending(t){const i={};for(const e of this.entries)t&&e.owner&&e.owner.anonymousId!==t||("set"===e.kind?i[e.key]=e.value:"unset"===e.kind&&delete i[e.key]);return i}serialize(){return this.entries.map(t=>{const i={key:t.key,kind:t.kind};return"set"!==t.kind&&"increment"!==t.kind||(i.value=t.value),t.values&&(i.values=[...t.values]),t.owner&&(i.owner=Object.assign({},t.owner)),t.attempts&&(i.attempts=t.attempts),i})}restore(t){if(Array.isArray(t))for(const i of t){if(!i||"object"!=typeof i||"string"!=typeof i.key)continue;const t=i.kind,e=i.owner&&"object"==typeof i.owner&&"string"==typeof i.owner.anonymousId?Object.assign({anonymousId:i.owner.anonymousId},"string"==typeof i.owner.userId?{userId:i.owner.userId}:{}):void 0,s=this.entries.length;"set"===t?this.add("set",i.key,i.value,e):"unset"===t?this.add("unset",i.key,void 0,e):"increment"===t&&"number"==typeof i.value&&Number.isFinite(i.value)?this.add("increment",i.key,i.value,e):"append"!==t&&"remove"!==t||!Array.isArray(i.values)||this.add(t,i.key,i.values,e);const n=this.entries.length>s?this.entries[this.entries.length-1]:void 0;n&&Number.isInteger(i.attempts)&&i.attempts>0&&(n.attempts=i.attempts)}}pinOwner(t,i){for(const e of this.entries)e.owner&&(e.owner.anonymousId!==t||e.owner.userId)||(e.owner={anonymousId:t,userId:i})}clear(){this.entries=[]}build(t,i=t=>t){var e,s,n,r,o;const h=new Set(this.entries.filter(t=>t.inFlight).map(t=>t.key)),a=new Set,l={},u=[];let c,d=!1;for(const t of this.entries){if(t.inFlight||h.has(t.key)||a.has(t.key)){a.add(t.key);continue}const f=i(t.owner);if(!d||nt(f,c))switch(d||(d=!0,c=f),a.add(t.key),u.push(t),t.kind){case"set":(null!==(e=l.attributes)&&void 0!==e?e:l.attributes={})[t.key]=t.value;break;case"unset":(null!==(s=l.unset)&&void 0!==s?s:l.unset=[]).push(t.key);break;case"increment":(null!==(n=l.increment)&&void 0!==n?n:l.increment={})[t.key]=t.value;break;case"append":(null!==(r=l.append)&&void 0!==r?r:l.append={})[t.key]=[...t.values];break;case"remove":(null!==(o=l.remove)&&void 0!==o?o:l.remove={})[t.key]=[...t.values]}else a.add(t.key)}if(!u.length)return null;if(t)for(const t of u)t.inFlight=!0;return Object.assign({ops:l,entries:u},c?{owner:Object.assign({},c)}:{})}lastFor(t){for(let i=this.entries.length-1;i>=0;i--)if(this.entries[i].key===t)return this.entries[i]}trim(){for(;this.entries.length>this.maxEntries;){const t=this.entries.findIndex(t=>!t.inFlight);if(0>t)break;this.entries.splice(t,1)}}}function ot(t){return Array.isArray(t)?[...t]:[t]}function ht(t,i){if(null!==i&&"object"==typeof i){const e=lt(i);return t.some(t=>null!==t&&"object"==typeof t&&lt(t)===e)}return t.some(t=>Object.is(t,i))}function at(t){const i=[];for(const e of t)ht(i,e)||i.push(e);return i}function lt(t){try{return JSON.stringify(t)}catch(i){return t+""}}const ut="user_id",ct="anonymous_id",dt="user_attributes";class ft{constructor(t,i,e,s){this.pending=new rt,this.userId=null,this.attributes={},this.storage=t,this.logger=i,this.anonymousId=s||this.storage.get(ct)||Q(),this.storage.get(ct)||(this.storage.set(ct,this.anonymousId),this.logger.debug("Generated new anonymous ID: "+this.anonymousId)),this.userId=e||this.storage.get(ut)||null,this.userId&&this.logger.debug("Loaded user ID: "+this.userId),this.attributes={},this.storage.remove(dt)}identify(t,i){const e=this.userId;this.userId=t,this.storage.set(ut,t),i&&this.setAttributes(i),e!==t&&this.logger.info(`User identified: ${t} (was: ${e||"anonymous"})`)}reset(t){this.logger.debug(`Resetting identity (was: ${this.userId||"anonymous"})`),this.userId=null,this.attributes={},this.anonymousId=t||Q(),this.storage.remove(ut),this.storage.remove(dt),this.storage.set(ct,this.anonymousId),this.logger.debug("New anonymous ID: "+this.anonymousId)}adopt(t,i){t!==this.anonymousId&&(this.attributes={}),this.anonymousId=t,this.userId=i}setAttributes(t){t&&"object"==typeof t&&!Array.isArray(t)?(this.attributes=Object.assign(Object.assign({},this.attributes),t),this.logger.debug("Updated user attributes:",this.attributes)):this.logger.error("setAttributes requires a plain object")}setAttribute(t,i){this.attributes[t]=i,this.logger.debug(`Set attribute: ${t} = ${i}`)}incrementAttribute(t,i=1){const e=this.attributes[t],s="number"==typeof e?e:0;this.setAttribute(t,s+i),this.logger.debug(`Incremented attribute: ${t} by ${i} (now: ${this.attributes[t]})`)}unsetAttribute(t){delete this.attributes[t],this.logger.debug("Unset attribute: "+t)}addToArray(t,i){const e=this.attributes[t];let s=[];Array.isArray(e)?s=[...e]:null!=e&&(this.logger.warn(`Attribute ${t} is not an array, converting to array`),s=[e]),s.includes(i)?this.logger.debug(`Value already exists in array: ${t} = ${i}`):(s.push(i),this.setAttribute(t,s),this.logger.debug(`Added to array: ${t} = ${i}`))}removeFromArray(t,i){const e=this.attributes[t];if(!Array.isArray(e))return void this.logger.warn(`Attribute ${t} is not an array, cannot remove value`);const s=e.filter(t=>t!==i);s.length!==e.length?(this.setAttribute(t,s),this.logger.debug(`Removed from array: ${t} = ${i}`)):this.logger.debug(`Value not found in array: ${t} = ${i}`)}getIdentity(){return{userId:this.userId,anonymousId:this.anonymousId,attributes:Object.assign({},this.attributes)}}getUserId(){return this.userId}getAnonymousId(){return this.anonymousId}getAttributes(){return Object.assign({},this.attributes)}getAttribute(t){return this.attributes[t]}isIdentified(){return null!==this.userId}}function pt(t){return!!t&&"object"==typeof t&&!Array.isArray(t)&&!1===t.success}function yt(t){return{userId:t.userId,anonymousId:t.anonymousId,attributes:t.attributes||{}}}function vt(t){let i=0;for(let e=0;e<t.length;e++){const s=t.charCodeAt(e);128>s?i+=1:2048>s?i+=2:55296>s||s>56319?i+=3:(i+=4,e++)}return i}function mt(t,i=Date.now()){if(!t)return;const e=+t;if(Number.isFinite(e)&&e>=0)return Math.round(1e3*e);const s=Date.parse(t);return Number.isFinite(s)?Math.max(0,s-i):void 0}const bt="X-Joryio-Auth",gt=2592e6;function wt(t,i=Date.now()){if("string"==typeof t)return t?{token:t,at:i}:null;if(!t||"object"!=typeof t)return null;const{token:e,at:s,standby:n}=t;return"string"==typeof e&&e&&"number"==typeof s&&Number.isFinite(s)?!0===n?{token:e,at:s,standby:!0}:{token:e,at:s}:null}function kt(t){var i;const e=null===(i=St(t))||void 0===i?void 0:i.sub;return"string"==typeof e&&e?e:null}function St(t){if(!t)return null;try{const i=t.split(".")[1];if(!i)return null;const e=i.replace(/-/g,"+").replace(/_/g,"/"),s=e+"=".repeat((4-e.length%4)%4),n="function"==typeof atob?atob:t=>globalThis.Buffer.from(t,"base64").toString("binary"),r=decodeURIComponent(Array.prototype.map.call(n(s),t=>"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)).join("")),o=JSON.parse(r);return o&&"object"==typeof o&&!Array.isArray(o)?o:null}catch(t){return null}}function jt(t,i){const e=((t||"")+"").split("?")[0],s=i&&"object"==typeof i?i:{};if(e.endsWith("/v1/push/unregister"))return!0;if(e.endsWith("/v1/subscriptions/channel"))return"unsubscribed"===s.status;if(e.endsWith("/v1/subscriptions/group"))return"unsubscribe"===s.action;if(e.endsWith("/v1/attributes")){if(["increment","append","remove","unset"].some(t=>null!=s[t]&&Object.keys(s[t]).length>0))return!1;const t=s.attributes;if(!t||"object"!=typeof t||Array.isArray(t))return!1;const i=Object.keys(t);return i.length>0&&i.every(i=>"tracking_opted_out"===i&&!0===t[i])}return!1}function Ot(t){if(!t||"object"!=typeof t)return null;if("string"==typeof t.userId&&t.userId)return t.userId;if("string"==typeof t.externalId&&t.externalId)return t.externalId;if(t.identify&&"string"==typeof t.identify.userId&&t.identify.userId)return t.identify.userId;for(const i of[t.events,t.impressions])if(Array.isArray(i)){const t=i.find(t=>t&&"string"==typeof t.userId&&t.userId);if(t)return t.userId}return null}function At(t){const i=St(t);return i&&"joryio-storefront"===i.iss&&"string"==typeof i.vid&&i.vid&&"number"==typeof i.exp?{vid:i.vid,exp:i.exp}:null}function It(t){if(!t||"object"!=typeof t)return null;if(Ot(t))return null;const i=new Set,e=t=>{"string"==typeof t&&t&&i.add(t)};e(t.anonymousId),t.identify&&e(t.identify.anonymousId);for(const i of[t.events,t.impressions])Array.isArray(i)&&i.forEach(t=>t&&e(t.anonymousId));return 1===i.size?i.values().next().value:null}const _t={failureThreshold:5,cooldownMs:3e4};class Tt{constructor(t,i,e,s){this.circuitState="closed",this.consecutiveFailures=0,this.circuitOpenedAt=0,this.sdkAuthEnabled=!1,this.sdkAuthFailureCallback=null,this.retiredSdkAuthTokens=new Map,this.retiredTokenStore=null,this.sdkAuthTokenUser=null,this.keepaliveBytesInFlight=0,this.currentUserId=null,this.storefrontTokenProvider=null,this.storefrontRefresh=null,this.anonymousIdSource=null,this.suspended=!1,this.sdkKey=t,this.logger=i,this.retryConfig=e,this.circuitBreakerConfig=Object.assign(Object.assign({},_t),s)}setAnonymousIdSource(t){this.anonymousIdSource=t}setStorefrontIdentityToken(t){const i="string"==typeof t&&t?t:void 0;!i||At(i)?this.storefrontToken=i:this.logger.warn("setStorefrontIdentityToken: not a storefront identity token - ignored")}setStorefrontIdentityTokenProvider(t){this.storefrontTokenProvider=t}clearStorefrontIdentityToken(){this.storefrontToken=void 0,this.storefrontRefresh=null}isStorefrontIdentityError(t,i){return 401===t&&!!i&&"object"==typeof i&&"storefront_identity_error"===i.error}storefrontTokenFor(t,i){const e=this.storefrontToken;if(!e)return;if(void 0===t?this.currentUserId:t)return;const s=At(e),n=this.anonymousIdSource?this.anonymousIdSource():null;if(s&&n&&s.vid===n&&null!==i&&(void 0===i||i===s.vid)){if(1e3*s.exp-Date.now()>=3e4)return e;this.refreshStorefrontToken()}}refreshStorefrontToken(){if(!this.storefrontTokenProvider)return Promise.resolve(void 0);if(this.storefrontRefresh)return this.storefrontRefresh;const t=this.storefrontToken,i=this.storefrontTokenProvider;return this.storefrontRefresh=(async()=>{try{const e=await Promise.resolve(i());if("string"==typeof e&&e&&At(e))return this.storefrontToken=e,e!==t?e:void 0}catch(t){this.logger.warn("The storefront identity token provider failed:",t)}})().finally(()=>{this.storefrontRefresh=null}),this.storefrontRefresh}async handleStorefrontIdentityError(t){const i=t&&"object"==typeof t?t.reason:void 0;if(this.logger.warn(`Storefront identity token refused (${i||"invalid"})`),"expired"===i){const t=this.storefrontToken;return await this.refreshStorefrontToken()||this.storefrontToken===t&&(this.storefrontToken=void 0),!0}return this.storefrontToken=void 0,!0}setSdkAuthenticationEnabled(t){this.sdkAuthEnabled=t}setSdkAuthenticationToken(t){const i="string"==typeof t&&t?t:void 0,e=this.sdkAuthToken;if(e&&i&&e!==i){const t=kt(e),s=kt(i),n=t||this.sdkAuthTokenUser,r=t&&s?t!==s:!!n&&n!==this.currentUserId;n&&r&&this.retireToken(n,e)}this.sdkAuthToken=i,this.sdkAuthTokenUser=i?this.currentUserId:null}retireSdkAuthToken(){const t=kt(this.sdkAuthToken),i=t||this.currentUserId,e=!!t&&t!==this.currentUserId;i&&this.sdkAuthToken&&this.retireToken(i,this.sdkAuthToken,e),this.sdkAuthToken=void 0,this.sdkAuthTokenUser=null}retireToken(t,i,e=!1){const s=new Map,n=this.retiredSdkAuthTokens.get(t);for(n&&n.token!==i&&s.set(t,n.token),this.retiredSdkAuthTokens.delete(t),this.retiredSdkAuthTokens.set(t,e?{token:i,at:Date.now(),standby:!0}:{token:i,at:Date.now()});this.retiredSdkAuthTokens.size>4;){const t=this.retiredSdkAuthTokens.keys().next().value;s.set(t,this.retiredSdkAuthTokens.get(t).token),this.retiredSdkAuthTokens.delete(t)}this.saveRetiredTokens(s)}switchUser(t){const i=this.currentUserId;if(i&&i!==t&&this.sdkAuthToken){const i=kt(this.sdkAuthToken);t&&i===t||this.retireSdkAuthToken()}if(this.currentUserId=t,!this.sdkAuthToken&&t){const i=this.retiredSdkAuthTokens.get(t);i&&kt(i.token)===t&&(this.sdkAuthToken=i.token,this.sdkAuthTokenUser=t)}this.adoptStandbyToken(t)}adoptStandbyToken(t){if(!t)return;const i=this.retiredSdkAuthTokens.get(t);i&&i.standby&&kt(i.token)===t&&(this.retiredSdkAuthTokens.set(t,{token:i.token,at:i.at}),this.saveRetiredTokens())}dropStandbySdkAuthTokens(t=new Set){if(this.retiredSdkAuthTokens.forEach((i,e)=>{i.standby&&!t.has(e)&&this.retiredSdkAuthTokens.delete(e)}),this.retiredTokenStore)try{this.retiredTokenStore.update(i=>{const e={},s=Date.now();for(const n of Object.keys(i||{})){const r=wt(i[n],s);!r||r.standby&&!t.has(n)||s-r.at>gt||(e[n]=r)}return e})}catch(t){this.logger.warn("Could not store the SDK authentication tokens:",t)}}setRetiredTokenStore(t){if(this.retiredTokenStore=t,!t)return;let i=null;try{i=t.load()}catch(t){this.logger.warn("Could not read the stored SDK authentication tokens:",t)}if(!i||"object"!=typeof i)return;const e=Date.now();for(const t of Object.keys(i)){const s=wt(i[t],e);s&&e-s.at<=gt&&(this.retiredSdkAuthTokens.has(t)||this.retiredSdkAuthTokens.set(t,s))}}retiredSdkAuthUsers(){return Array.from(this.retiredSdkAuthTokens.keys())}forgetRetiredSdkAuthTokensExcept(t,i=Date.now()){const e=new Map;let s=null;return this.retiredSdkAuthTokens.forEach((n,r)=>{const o=i-n.at;o>gt?e.set(r,n.token):n.standby||t.has(r)||(6e4>o?s=Math.min(null!=s?s:1/0,6e4-o):e.set(r,n.token))}),e.forEach((t,i)=>this.retiredSdkAuthTokens.delete(i)),e.size&&this.saveRetiredTokens(e),s}saveRetiredTokens(t=new Map){if(this.retiredTokenStore)try{this.retiredTokenStore.update(i=>{const e={},s=Date.now();for(const n of Object.keys(i||{})){const r=wt(i[n],s);r&&s-r.at<=gt&&t.get(n)!==r.token&&(e[n]=r)}return this.retiredSdkAuthTokens.forEach((t,i)=>{const n=wt(e[i],s);if(!n||n.token===t.token)return void(e[i]=Object.assign({},t));const r=function(t,i){const e=St(t),s=St(i),n=t=>"number"==typeof t&&Number.isFinite(t)?t:null;for(const r of["exp","iat"]){const o=n(null==e?void 0:e[r]),h=n(null==s?void 0:s[r]);if(null!==o&&null!==h&&o!==h)return o>h?t:i}return null}(n.token,t.token);(r?r!==t.token:n.at>t.at)?this.retiredSdkAuthTokens.set(i,n):e[i]=Object.assign({},t)}),e})}catch(t){this.logger.warn("Could not store the SDK authentication tokens:",t)}}sdkAuthTokenFor(t){var i;const e=void 0===t?this.currentUserId:t;if(!e)return;const s=this.sdkAuthEnabled?this.sdkAuthToken:void 0,n=kt(s);return s&&n===e?s:!s||n||e!==this.currentUserId||null!==this.sdkAuthTokenUser&&this.sdkAuthTokenUser!==e?null===(i=this.retiredSdkAuthTokens.get(e))||void 0===i?void 0:i.token:s}getCurrentUserId(){return this.currentUserId}setSdkAuthenticationFailureCallback(t){this.sdkAuthFailureCallback=t}setCurrentUserId(t){this.currentUserId=t,this.adoptStandbyToken(t)}isSuspended(){return this.suspended}noteSuspended(t,i){return 402===t&&(this.suspended||(this.suspended=!0,console.warn(`[Joryio SDK] The API refused this request with 402 ${(null==i?void 0:i.code)||""} - event ingestion is paused for this workspace. Nothing more will be sent this page view; queued events are kept.`)),!0)}getSdkAuthHeaders(t,i){var e;const s=null!==(e=this.sdkAuthTokenFor(t))&&void 0!==e?e:this.storefrontTokenFor(t,i);return s?{[bt]:s}:{}}keepaliveBudget(){return Math.max(0,61440-this.keepaliveBytesInFlight)}isSdkAuthError(t,i){return 401===t&&!!i&&"object"==typeof i&&"sdk_authentication_error"===i.error}async refreshSdkAuthToken(t){if(!this.sdkAuthEnabled||!this.sdkAuthFailureCallback)return;const i=this.sdkAuthToken;let e;try{e=await Promise.resolve(this.sdkAuthFailureCallback(t))}catch(t){return void this.logger.error("SDK authentication failure callback threw:",t)}"string"==typeof e&&e&&this.setSdkAuthenticationToken(e);const s=this.sdkAuthToken;return s&&s!==i?s:void 0}async request(t){var i,e;if(this.suspended&&!jt(t.url,t.body))return{ok:!1,status:402,error:"Ingestion suspended",data:{code:"SDK_INGESTION_SUSPENDED"}};if("open"===this.circuitState){const t=Date.now()-this.circuitOpenedAt;if(t<this.circuitBreakerConfig.cooldownMs)return this.logger.warn(`Circuit breaker OPEN – failing fast (${Math.round((this.circuitBreakerConfig.cooldownMs-t)/1e3)}s remaining)`),{ok:!1,status:0,error:"Circuit breaker is open – API requests are temporarily blocked"};this.circuitState="half-open",this.logger.info("Circuit breaker transitioning to HALF-OPEN – allowing probe request")}const{url:s,method:n="POST",headers:r={}}=t;let o;try{o=t.body?JSON.stringify(t.body):void 0}catch(t){return this.logger.error(`Request to ${s} not sent: its body cannot be serialized`,t),{ok:!1,status:400,error:"The request body cannot be serialized"}}const h=void 0===t.subjectUserId||(t.subjectUserId||null)===this.currentUserId,a=t.body?It(t.body):void 0;let l,u,c=null,d=0,f=0,p=!1,y=!1;for(;f<=this.retryConfig.maxRetries;){try{this.logger.debug(`Request attempt ${f+1}/${this.retryConfig.maxRetries+1}: ${n} ${s}`);let{response:v,responseData:m}=await this.performFetch(s,n,r,o,t.subjectUserId,a);if(!y&&this.isStorefrontIdentityError(v.status,m)&&(y=!0,await this.handleStorefrontIdentityError(m)&&({response:v,responseData:m}=await this.performFetch(s,n,r,o,t.subjectUserId,a))),!p&&this.sdkAuthEnabled&&h&&this.isSdkAuthError(v.status,m)&&(p=!0,this.logger.warn(`SDK authentication rejected (${(null==m?void 0:m.reason)||"invalid"}) on ${s} – refreshing token`),await this.refreshSdkAuthToken({reason:(null==m?void 0:m.reason)||(this.sdkAuthToken?"invalid":"missing"),endpoint:s,userId:void 0===t.subjectUserId?this.currentUserId:t.subjectUserId||null})&&(this.logger.debug("SDK authentication token refreshed – retrying request once"),({response:v,responseData:m}=await this.performFetch(s,n,r,o,t.subjectUserId,a)))),v.ok)return this.onRequestSuccess(),pt(m)?(this.logger.warn(`Request to ${s} answered ${v.status} with success: false`),{ok:!1,status:v.status,data:m,error:(null==m?void 0:m.error)||(null==m?void 0:m.message)||"The server reported success: false",softFailure:!0}):(this.logger.debug("Request successful: "+v.status),{ok:!0,status:v.status,data:m});if(!this.shouldRetry(v.status))return this.logger.warn("Request failed with non-retryable status: "+v.status),this.noteSuspended(v.status,m),{ok:!1,status:v.status,error:(null==m?void 0:m.message)||v.statusText,data:m};d=v.status,l=m,u=mt(null===(e=null===(i=v.headers)||void 0===i?void 0:i.get)||void 0===e?void 0:e.call(i,"retry-after")),c=Error(`HTTP ${v.status}: ${v.statusText}`),this.logger.warn(`Request failed (attempt ${f+1}): ${c.message}`)}catch(t){c=t,d=0,l=void 0,u=void 0,this.logger.error(`Request error (attempt ${f+1}):`,t)}if(f<this.retryConfig.maxRetries){const t=Math.max(this.calculateBackoff(f),Math.min(null!=u?u:0,3e4));this.logger.debug(`Retrying in ${t}ms...`),await this.sleep(t)}f++}return this.onRequestFailure(),this.logger.error(`Request failed after ${this.retryConfig.maxRetries+1} attempts`),Object.assign({ok:!1,status:d,data:l,error:(null==c?void 0:c.message)||"Network request failed"},void 0!==u?{retryAfterMs:u}:{})}onRequestSuccess(){(this.consecutiveFailures>0||"closed"!==this.circuitState)&&this.logger.info(`Circuit breaker CLOSED – request succeeded after ${this.consecutiveFailures} consecutive failure(s)`),this.consecutiveFailures=0,this.circuitState="closed",this.circuitOpenedAt=0}onRequestFailure(){if(this.consecutiveFailures++,"half-open"===this.circuitState)return this.circuitState="open",this.circuitOpenedAt=Date.now(),void this.logger.warn(`Circuit breaker re-OPENED – probe request failed (${this.consecutiveFailures} consecutive failures)`);this.consecutiveFailures<this.circuitBreakerConfig.failureThreshold||(this.circuitState="open",this.circuitOpenedAt=Date.now(),this.logger.warn(`Circuit breaker OPENED – ${this.consecutiveFailures} consecutive failures reached threshold of ${this.circuitBreakerConfig.failureThreshold}`))}getCircuitBreakerState(){return{state:this.circuitState,consecutiveFailures:this.consecutiveFailures,openedAt:this.circuitOpenedAt}}async performFetch(t,i,e,s,n,r){var h;const a=new AbortController,l=setTimeout(()=>a.abort(),this.retryConfig.timeoutMs||1e4),u=Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},e),o()),c=null!==(h=this.sdkAuthTokenFor(n))&&void 0!==h?h:this.storefrontTokenFor(n,r);let d;c&&(u[bt]=c);try{d=await fetch(t,{method:i,headers:u,body:s,signal:a.signal,credentials:"omit"})}finally{clearTimeout(l)}return{response:d,responseData:await this.parseResponse(d)}}async parseResponse(t){var i,e;const s=null===(e=null===(i=t.headers)||void 0===i?void 0:i.get)||void 0===e?void 0:e.call(i,"content-type");if(s&&s.includes("application/json"))try{return await t.json()}catch(t){return this.logger.warn("Failed to parse JSON response"),null}return await t.text()}shouldRetry(t){return 408===t||429===t||t>=500}calculateBackoff(t){const{backoffMs:i,maxBackoffMs:e=3e4}=this.retryConfig,s=Math.min(i*Math.pow(2,t),e),n=.25*s*(2*Math.random()-1);return Math.max(0,Math.floor(s+n))}sleep(t){return new Promise(i=>setTimeout(i,t))}async sendEvents(t,i,e){var s;const n={events:i};return e&&(n.identify=yt(e)),this.request({url:t+"/v1/track/batch",method:"POST",body:n,subjectUserId:(null==e?void 0:e.userId)||(null===(s=i.find(t=>t&&t.userId))||void 0===s?void 0:s.userId)||null})}supportsKeepalive(){try{return"function"==typeof fetch&&"undefined"!=typeof Request&&"keepalive"in Request.prototype}catch(t){return!1}}sendEventsKeepalive(t,i,e){const s={events:i};return e&&(s.identify=yt(e)),this.postKeepalive(t+"/v1/track/batch",s)}postKeepalive(t,i){var e;if(this.suspended&&!jt(t,i)||!this.supportsKeepalive())return null;let s;try{s=JSON.stringify(i)}catch(t){return null}const n=vt(s)+256;if(this.keepaliveBytesInFlight+n>61440)return null;const r=Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),h=Ot(i),a=null!==(e=this.sdkAuthTokenFor(h))&&void 0!==e?e:this.storefrontTokenFor(h,It(i));a&&(r[bt]=a);try{this.keepaliveBytesInFlight+=n;let i=!1;const e=()=>{i||(i=!0,this.keepaliveBytesInFlight=Math.max(0,this.keepaliveBytesInFlight-n))};return fetch(t,{method:"POST",headers:r,body:s,keepalive:!0,credentials:"omit"}).then(async t=>{e();const i=await this.parseResponse(t).catch(()=>null),s=t.ok&&pt(i);return Object.assign({ok:t.ok&&!s,status:t.status,data:i},s?{softFailure:!0}:{})},t=>(e(),{ok:!1,status:0,error:((null==t?void 0:t.message)||t)+""}))}catch(t){return this.keepaliveBytesInFlight=Math.max(0,this.keepaliveBytesInFlight-n),this.logger.warn("keepalive request could not be started:",t),null}}async sendIdentify(t,i,e,s){return this.request({url:t+"/v1/identify",method:"POST",body:{userId:i,attributes:e,anonymousId:s},subjectUserId:i})}async sendIdentifyLink(t,i){return this.request({url:t+"/v1/identify-link",method:"POST",body:{token:i.token,anonymousId:i.anonymousId},subjectUserId:null})}hasStorefrontIdentity(){const t=this.storefrontToken;if(!t)return!1;const i=At(t),e=this.anonymousIdSource?this.anonymousIdSource():null;return!!i&&!!e&&i.vid===e}async sendAddAlias(t,i){return this.request({url:t+"/v1/alias/add",method:"POST",body:i,subjectUserId:i.userId||null})}async sendDeviceSession(t,i){return this.request({url:t+"/v1/device/session",method:"POST",body:i})}async sendSetAttributes(t,i,e,s){return this.request({url:t+"/v1/attributes",method:"POST",body:Object.assign({userId:e||void 0,anonymousId:e?void 0:s},i),subjectUserId:e||null})}async sendSubscriptionUpdate(t,i){return this.request({url:t+"/v1/subscriptions/channel",method:"POST",body:i,subjectUserId:i.userId||null})}async sendSubscriptionGroupUpdate(t,i){return this.request({url:t+"/v1/subscriptions/group",method:"POST",body:i,subjectUserId:i.userId||null})}}const $t="event_queue",Dt="event_queue_inflight",Ct="pending_identify",Pt=921600,Mt=3e5;function xt(t,i){return i.every(i=>i.anonymousId===t.anonymousId&&(!i.userId||i.userId===t.userId))}class Kt{constructor(t,i,e,s,n=!0,r=1e3,o=1e3){if(this.queue=[],this.flushTimer=null,this.flushCallback=null,this.pendingPersist=!1,this.persistTimer=null,this.isFlushing=!1,this.flushWaiters=[],this.pendingIdentifies=[],this.inflightEvents=[],this.paused=!1,this.suspended=!1,this.consecutiveFailures=0,this.nextAttemptAt=0,this.retryAfterUntil=0,this.generation=0,this.clearedInflightCallback=null,this.storage=t,this.logger=i,this.batchSize=e>0?Math.floor(e):50,this.flushInterval=s,this.persistQueue=n,this.maxQueueSize=r>0?Math.floor(r):1e3,this.retryBackoffMs=o>0?o:1e3,this.persistQueue){const t=this.storage.get(Dt)||[],i=this.storage.get($t)||[];this.queue=[...t,...i],t.length>0&&(this.storage.remove(Dt),this.logger.debug(`Recovered ${t.length} in-flight events from previous page`)),this.queue.length>this.maxQueueSize&&(this.queue=this.queue.slice(-this.maxQueueSize)),this.queue.length>0&&(this.logger.debug(`Loaded ${this.queue.length} events from storage`),this.persistQueueToStorage());const e=this.storage.get(Ct),s=Array.isArray(e)?e:e?[e]:[];this.pendingIdentifies=s.filter(t=>t&&"string"==typeof t.userId&&"string"==typeof t.anonymousId).slice(-20),this.pendingIdentifies.length&&this.logger.debug(`Recovered ${this.pendingIdentifies.length} pending identify(s) from a previous page`)}}setFlushCallback(t){this.flushCallback=t}setPaused(t){this.paused=t}isPaused(){return this.paused}isSuspended(){return this.suspended}isBackingOff(){return this.consecutiveFailures>0||Date.now()<this.retryAfterUntil}resetBackoff(){this.consecutiveFailures=0,this.nextAttemptAt=0}setPendingIdentify(t){const i=this.pendingIdentifies[this.pendingIdentifies.length-1],e={userId:t.userId,anonymousId:t.anonymousId,attributes:t.attributes||{}};if(!i||i.userId!==e.userId||i.anonymousId!==e.anonymousId){if(this.pendingIdentifies.push(e),this.pendingIdentifies.length>20){const t=this.pendingIdentifies.shift();this.logger.warn(`Too many identify calls waiting to be sent; dropped the oldest (${t.userId})`)}this.persistIdentifies()}}persistIdentifies(){if(this.persistQueue)try{this.pendingIdentifies.length?this.storage.set(Ct,this.pendingIdentifies):this.storage.remove(Ct)}catch(t){this.logger.error("Failed to persist pending identify:",t)}}getPendingIdentify(){return this.pendingIdentifies[0]||null}getPendingIdentifies(){return[...this.pendingIdentifies]}removeIdentify(t){const i=this.pendingIdentifies.indexOf(t);0>i||this.pendingIdentifies.splice(i,1),this.persistIdentifies()}identifyAttemptFailed(t,i){i?(t.attempts=(t.attempts||0)+1,10>t.attempts?this.persistIdentifies():(this.logger.error(`Identify for ${t.userId} failed ${t.attempts} times; dropping it`),this.removeIdentify(t))):this.persistIdentifies()}start(){this.flushTimer?this.logger.debug("Queue manager already started"):(this.flushTimer=setInterval(()=>{this.flush().catch(t=>this.logger.error("Scheduled flush failed:",t))},this.flushInterval),this.logger.debug(`Queue manager started (batch: ${this.batchSize}, interval: ${this.flushInterval}ms)`),(this.queue.length>0||this.pendingIdentifies.length)&&this.flush().catch(t=>this.logger.error("Startup flush failed:",t)))}isStarted(){return null!==this.flushTimer}stop(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null,this.logger.debug("Queue manager stopped")),this.persistNow()}enqueue(t){this.queue.push(t),this.logger.debug(`Event queued: ${t.type} (queue size: ${this.queue.length})`),this.schedulePersist(),this.trimToMax(),this.queue.length<this.batchSize||this.isFlushing||(this.logger.debug("Batch size reached, flushing queue"),this.flush())}trimToMax(){if(this.queue.length>this.maxQueueSize){const t=this.queue.length-this.maxQueueSize;this.queue=this.queue.slice(-this.maxQueueSize),this.logger.warn(`Queue exceeded max size (${this.maxQueueSize}), dropped ${t} oldest event(s)`),this.schedulePersist()}}takeBatch(){const t=Math.min(this.batchSize,500),i=[];let e=64,s=null;for(;this.queue.length>0&&i.length<t;){const t=this.queue[0];if(i.length>0){if(t.anonymousId!==i[0].anonymousId)break;if(t.userId&&s&&t.userId!==s)break}let n;try{n=vt(JSON.stringify(t))+1}catch(t){n=1/0}if(n>Pt)this.queue.shift(),this.logger.error(`Dropping event "${t.type}": it is too large to send (${n} bytes)`);else{if(i.length>0&&e+n>Pt)break;i.push(this.queue.shift()),t.userId&&(s=t.userId),e+=n}}return i}restoreToFront(t){if(!t.length)return;const i=new Set(this.queue.map(t=>t.eventId)),e=t.filter(t=>!i.has(t.eventId));this.queue.unshift(...e),this.trimToMax()}backOff(t){this.consecutiveFailures++;const i=Math.min(this.retryBackoffMs*Math.pow(2,Math.min(this.consecutiveFailures-1,20)),Mt),e=.2*i*Math.random(),s=Math.max(i+e,Math.min(null!=t?t:0,Mt));this.nextAttemptAt=Date.now()+s,t&&t>0&&(this.retryAfterUntil=Date.now()+Math.min(t,Mt)),this.logger.debug(`Event send failed; next attempt in ${Math.round(s)}ms`)}async sendBatch(t,i,e=[]){let s;this.inflightEvents=e.length?[...t,...e]:t,this.persistQueue&&(this.persistQueueToStorage(),this.persistInflightToStorage());try{s=await this.flushCallback(t,null!=i?i:void 0)||{status:"ok"}}catch(t){this.logger.error("Failed to flush events:",t),s={status:"retry"}}return this.inflightEvents=[],this.persistQueue&&this.storage.remove(Dt),s}async flush(t=!1,i=!1){var e,s;if(0===this.queue.length&&!this.pendingIdentifies.length&&!this.isFlushing)return;if(this.paused||this.suspended){if(t)throw Error(this.paused?"Sending is paused":"Sending is suspended");return}if(this.isFlushing)return await new Promise(t=>this.flushWaiters.push(t)),this.queue.length>0||this.pendingIdentifies.length?this.flush(t,i):void 0;const n=Date.now();if(n<this.retryAfterUntil||!i&&n<this.nextAttemptAt||"undefined"!=typeof navigator&&!1===navigator.onLine){if(t)throw Error("Waiting to retry");return}if(!this.flushCallback)return void this.logger.warn("No flush callback set, cannot flush queue");this.isFlushing=!0;let r=null;const o=this.generation;try{let t=null;const i=[];let n=this.queue.length;const h=new Set;for(;;){let a;i.length>0?a=i.shift():n>0?(a=this.takeBatch(),n-=a.length,0===a.length&&(n=0)):a=this.pendingIdentifies[0]&&!h.has(this.pendingIdentifies[0])&&this.pendingIdentifies[0]!==t&&this.queue.length>0&&xt(this.pendingIdentifies[0],[this.queue[0]])?this.takeBatch():[];const l=this.pendingIdentifies[0]||null;let u=null;if(l&&!h.has(l)&&(0===a.length||l!==t&&xt(l,a))&&(u=l),0===a.length&&!u)break;0===a.length&&u&&h.add(u),this.logger.debug(`Flushing ${a.length} events${u?" + identify":""}`);const c=await this.sendBatch(a,u,i.flat());if(this.generation!==o){if(this.logger.debug("Queue cleared during a flush; the in-flight batch is not restored"),this.clearedInflightCallback){let t=[];if("ok"===c.status){const i=new Set([...c.failedIndices||[],...c.rejectedIndices||[]]);t=a.filter((t,e)=>!i.has(e))}try{this.clearedInflightCallback(t)}catch(t){this.logger.warn("Cleared in-flight callback failed:",t)}}break}if("dropped"!==c.status){if("ok"===c.status){const t=t=>new Set((t||[]).filter(t=>Number.isInteger(t)&&t>=0&&t<a.length)),e=t(c.rejectedIndices);for(const t of e)this.logger.error(`Event "${a[t].type}" was refused by the server for good and has been dropped`);const s=[...t(c.failedIndices)].filter(t=>!e.has(t)).map(t=>a[t]);if(u&&c.identifyDropped&&(this.logger.error(`Identify for ${u.userId} was refused by the server; dropping it`),this.removeIdentify(u),u=null),u&&c.identifyFailed){this.identifyAttemptFailed(u,!1!==c.identifyAttemptCounts),this.restoreToFront([...s,...i.flat()]),this.backOff(),r="The identify was not confirmed";break}if(u&&this.removeIdentify(u),this.consecutiveFailures=0,this.nextAttemptAt=0,s.length>0){this.logger.warn(`${s.length} of ${a.length} events were not stored by the server; will retry them`),this.restoreToFront([...s,...i.flat()]),this.backOff(),r="Some events were not stored";break}continue}if("rejected"!==c.status){this.restoreToFront([...a,...i.flat()]),u&&"retry"===c.status&&this.identifyAttemptFailed(u,!0===c.counts),"suspended"===c.status?(this.suspended||(this.suspended=!0,console.warn(`[Joryio SDK] Event sending stopped for this page view (${c.reason||"refused"}). `+this.queue.length+" queued event(s) are kept.")),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),r="Sending is suspended"):(this.backOff(c.retryAfterMs),r="Events could not be delivered; will retry");break}if(u){if(0===a.length){this.logger.error(`Identify for ${u.userId} was refused by the server (HTTP ${null!==(e=c.httpStatus)&&void 0!==e?e:"4xx"}); dropping it`),this.removeIdentify(u);continue}t=u,i.unshift(a);continue}if(a.length>1){const t=Math.ceil(a.length/2);i.unshift(a.slice(0,t),a.slice(t));continue}1===a.length&&this.logger.error(`Event "${a[0].type}" was refused by the server (HTTP ${null!==(s=c.httpStatus)&&void 0!==s?s:"4xx"}) and has been dropped`)}else this.logger.error(`${a.length} event(s)${u?" and an identify":""} of a user who is no longer signed in were refused by SDK authentication (${c.reason||"401"}) and have been dropped`),u&&this.removeIdentify(u)}this.persistQueue&&this.persistQueueToStorage()}finally{this.isFlushing=!1;const t=this.flushWaiters;this.flushWaiters=[],t.forEach(t=>t())}if(r&&t)throw Error(r)}persistQueueToStorage(){this.pendingPersist=!1,null!==this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null);try{this.storage.set($t,this.queue)}catch(t){this.logger.error("Failed to persist queue to storage:",t)}}schedulePersist(){this.persistQueue&&!this.pendingPersist&&(this.pendingPersist=!0,this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.pendingPersist&&this.persistQueueToStorage()},150))}persistNow(){this.persistQueue&&this.pendingPersist&&this.persistQueueToStorage()}persistInflightToStorage(){try{this.inflightEvents.length>0?this.storage.set(Dt,this.inflightEvents):this.storage.remove(Dt)}catch(t){this.logger.error("Failed to persist in-flight events to storage:",t)}}getQueueSize(){return this.queue.length}getQueuedEvents(){return[...this.inflightEvents,...this.queue]}getWaitingEvents(){return[...this.queue]}getInflightEvents(){return[...this.inflightEvents]}setClearedInflightCallback(t){this.clearedInflightCallback=t}markHandedOff(t,i){const e=new Set(t.map(t=>t.eventId));this.queue=this.queue.filter(t=>!e.has(t.eventId)),this.inflightEvents=this.inflightEvents.filter(t=>!e.has(t.eventId)),i&&this.removeIdentify(i),this.persistQueue&&(this.persistQueueToStorage(),this.persistInflightToStorage())}takeBack(t,i){this.restoreToFront(t),i&&!this.pendingIdentifies.includes(i)&&(this.pendingIdentifies.unshift(i),this.persistIdentifies()),this.persistQueue&&this.persistQueueToStorage()}clear(){this.generation++,this.queue=[],this.inflightEvents=[],this.persistQueue&&(this.storage.remove($t),this.storage.remove(Dt),this.storage.remove(Ct)),this.pendingIdentifies=[],this.logger.debug("Queue cleared")}async destroy(){this.stop(),this.queue.length>0&&(this.logger.debug("Flushing remaining events before destroy"),await this.flush())}}const Nt="first_touch_utm",Ft="last_touch_utm",Et="session_utm",Ut="session_referrer",qt="session_landing_page";class zt{constructor(t,i,e=!1){this.newCampaignDetected=!1,this.storage=t,this.logger=i,this.resetSessionOnNewCampaign=e,this.resetSessionOnNewCampaign&&(this.newCampaignDetected=this.detectNewCampaign()),this.captureUTMParameters()}captureUTMParameters(){if("undefined"==typeof window)return;const t=new URLSearchParams(window.location.search),i={};let e=!1;const s=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"];for(const n of s){const s=t.get(n);s&&(i[n]=s,e=!0)}document.referrer&&(i.referrer=document.referrer),i.landing_page=window.location.href,i.captured_at=Date.now(),e?(this.logger.debug("Captured UTM parameters:",i),this.storage.set(Et,i),this.storage.set(Ut,i.referrer||null),this.storage.set(qt,i.landing_page),this.storage.get(Nt)||(this.storage.set(Nt,i),this.logger.debug("Set first touch UTM:",i)),this.storage.set(Ft,i),this.logger.debug("Updated last touch UTM:",i)):this.storage.get(Et)||(this.storage.set(Et,i),this.storage.set(Ut,i.referrer||null),this.storage.set(qt,i.landing_page),this.logger.debug("Captured session referrer and landing page"))}getUTMData(){return{current:this.storage.get(Et)||null,firstTouch:this.storage.get(Nt)||null,lastTouch:this.storage.get(Ft)||null}}getCurrentUTM(){return this.storage.get(Et)||null}getFirstTouchUTM(){return this.storage.get(Nt)||null}getLastTouchUTM(){return this.storage.get(Ft)||null}getSessionReferrer(){return this.storage.get(Ut)||null}getSessionLandingPage(){return this.storage.get(qt)||null}hasNewCampaign(){return this.newCampaignDetected}detectNewCampaign(){if("undefined"==typeof window)return!1;const t=new URLSearchParams(window.location.search),i=this.getCurrentUTM();if(!i)return t.has("utm_source")||t.has("utm_medium")||t.has("utm_campaign");const e=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"];for(const s of e){const e=t.get(s),n=i[s];if(e&&e!==n)return!0}return!1}updateUTM(){this.resetSessionOnNewCampaign&&(this.newCampaignDetected=this.detectNewCampaign()),this.captureUTMParameters()}clearSessionUTM(){this.storage.remove(Et),this.storage.remove(Ut),this.storage.remove(qt),this.logger.debug("Cleared session UTM")}clearAllUTM(){this.storage.remove(Et),this.storage.remove(Nt),this.storage.remove(Ft),this.storage.remove(Ut),this.storage.remove(qt),this.logger.debug("Cleared all UTM data")}reset(){this.clearAllUTM()}getUTMProperties(){const t=this.getCurrentUTM(),i=this.getFirstTouchUTM(),e=this.getLastTouchUTM(),s={};return t&&(t.utm_source&&(s.utm_source=t.utm_source),t.utm_medium&&(s.utm_medium=t.utm_medium),t.utm_campaign&&(s.utm_campaign=t.utm_campaign),t.utm_content&&(s.utm_content=t.utm_content),t.utm_term&&(s.utm_term=t.utm_term),t.referrer&&(s.referrer=t.referrer),t.landing_page&&(s.landing_page=t.landing_page)),i&&(i.utm_source&&(s.first_touch_utm_source=i.utm_source),i.utm_medium&&(s.first_touch_utm_medium=i.utm_medium),i.utm_campaign&&(s.first_touch_utm_campaign=i.utm_campaign),i.utm_content&&(s.first_touch_utm_content=i.utm_content),i.utm_term&&(s.first_touch_utm_term=i.utm_term),i.referrer&&(s.first_touch_referrer=i.referrer),i.landing_page&&(s.first_touch_landing_page=i.landing_page),i.captured_at&&(s.first_touch_captured_at=new Date(i.captured_at).toISOString())),e&&e!==t&&(e.utm_source&&(s.last_touch_utm_source=e.utm_source),e.utm_medium&&(s.last_touch_utm_medium=e.utm_medium),e.utm_campaign&&(s.last_touch_utm_campaign=e.utm_campaign),e.utm_content&&(s.last_touch_utm_content=e.utm_content),e.utm_term&&(s.last_touch_utm_term=e.utm_term),e.referrer&&(s.last_touch_referrer=e.referrer),e.landing_page&&(s.last_touch_landing_page=e.landing_page),e.captured_at&&(s.last_touch_captured_at=new Date(e.captured_at).toISOString())),s}}const Jt={modal:600,slideup:400};function Rt(t,i,e=16){const s=Math.max(0,Math.floor(i)-2*e);return Math.max(0,Math.min(Math.floor(t),s))}const Lt="__joryioInApp",Ht="inapp_impressions",Bt=1e3,Vt=new Set(["close_button","backdrop","button","bridge_close"]);function Wt(t,i){var e,s;const n=t=>t.split(",").map(t=>{const e=t.trim();return e?/^(?:html|body|:root)$/i.test(e)?i:`${i} ${e}`:""}).filter(Boolean).join(", "),r=[];for(let o=0;o<t.length;o++){const h=t[o];if(void 0!==h.selectorText&&h.style){const t=n(h.selectorText);t&&r.push(`${t} { ${h.style.cssText} }`)}else if(h.cssRules&&void 0!==h.conditionText){const t=(null!==(e=h.cssText)&&void 0!==e?e:"").slice(0,(null!==(s=h.cssText)&&void 0!==s?s:"").indexOf("{")).trim(),n=Wt(h.cssRules,i);t&&n&&r.push(`${t} { ${n} }`)}else 7===h.type&&h.cssText&&r.push(h.cssText)}return r.join("\n")}const Xt=new Set(["click","clicked","button","link","cta_click","link_click","button_click"]);function Gt(t){if("string"!=typeof t)return;const i=t.trim();return i&&!Xt.has(i.toLowerCase())?i.slice(0,128):void 0}const Qt=new Set(["modal","banner","slideup","fullscreen"]);function Zt(t){if("string"!=typeof t)return null;const i=t.trim();return!i||i.length>100||/[;{}<>\\]/.test(i)?null:i}class Yt{capabilities(){const t=["content.native","placements","content.data"];return this.allowHtmlJsInAppMessages&&t.push("content.html"),this.page&&t.push(c),t}setPageContext(t){var i;null===(i=this.pageUnsubscribe)||void 0===i||i.call(this),this.pageUnsubscribe=null,this.page=t,t&&(this.pageUnsubscribe=t.onSignal(t=>this.onPageSignal(t)))}pageAllows(t){return!y(t.pageTargeting)||!!this.page&&function(t,i){var e,s,n,r,o;if(!y(t))return!0;const h=null!==(s=null===(e=t.urls)||void 0===e?void 0:e.include)&&void 0!==s?s:[],a=null!==(r=null===(n=t.urls)||void 0===n?void 0:n.exclude)&&void 0!==r?r:[];if(h.length||a.length){if(!i.url)return!1;if(h.length&&!h.some(t=>p(t,i.url)))return!1;if(a.some(t=>p(t,i.url)))return!1}return(null!==(o=t.variables)&&void 0!==o?o:[]).every(t=>function(t,i){var e,s,n,r,o,h,a;const l="data_layer"===t.source?i.dataLayer:"page"===t.source?i.pageVariables:"utm_session"===t.source?null!==(s=null===(e=i.utm)||void 0===e?void 0:e.session)&&void 0!==s?s:{}:"utm_first_touch"===t.source?null!==(r=null===(n=i.utm)||void 0===n?void 0:n.firstTouch)&&void 0!==r?r:{}:void 0;if(!l)return!1;const u=Object.prototype.hasOwnProperty.call(l,t.key),c=u?l[t.key]:void 0;switch(t.op){case"exists":return u;case"not_exists":return!u;case"equals":return u&&(c+"").toLowerCase()===((null!==(o=t.value)&&void 0!==o?o:"")+"").toLowerCase();case"not_equals":return!u||(c+"").toLowerCase()!==((null!==(h=t.value)&&void 0!==h?h:"")+"").toLowerCase();case"contains":return u&&(c+"").toLowerCase().includes(((null!==(a=t.value)&&void 0!==a?a:"")+"").toLowerCase());case"gt":case"lt":{const i=+c,e=+t.value;return!!(u&&Number.isFinite(i)&&Number.isFinite(e))&&("gt"===t.op?i>e:e>i)}default:return!1}}(t,i))}(t.pageTargeting,this.page.current())}onPageSignal(t){if(!this.page)return;"page_change"===t.type&&this.pageFired.clear();const i=this.page.progress();for(const e of this.campaigns.values()){const s=e.triggers||[],n=s.find(e=>v(e)&&k(e,t,i)),r="page_change"===t.type&&y(e.pageTargeting)&&s.some(t=>"immediate"===t.type);(n||r)&&(this.pageFired.has(e.id)||this.pageAllows(e)&&(this.pageFired.add(e.id),this.displayCampaign(e).catch(t=>this.logger.error("In-app display failed:",t))))}}callHost(t,i){try{i()}catch(i){this.logger.error(`The ${t} callback threw; ignored:`,i)}}invalidate(){this.generation++,this.isSyncing&&(this.syncAgain=!0)}setAllowHtmlJsInAppMessages(t){this.allowHtmlJsInAppMessages=t}constructor(t,i,e,s,n,r,o,h,a,l){this.links=null,this.pendingDelays=new Map,this.campaigns=new Map,this.displayedMessages=new Map,this.impressionTimestamps=new Map,this.watchedAttributes=new Set,this.displayOptions={},this.isSyncing=!1,this.syncRetried=!1,this.generation=0,this.syncAgain=!1,this.claimed=new Set,this.awaitingDwell=new Map,this.pageLeaving=!1,this.settleWaiters=new Set,this.pageListeners=[],this.iframes=new Map,this.frameMaxWidths=new Map,this.allowHtmlJsInAppMessages=!1,this.page=null,this.pageUnsubscribe=null,this.pageFired=new Set,this.bridge=null,this.auth=null,this.runtime={canSend:(null==l?void 0:l.canSend)||(()=>!0),requestTimeoutMs:(null==l?void 0:l.requestTimeoutMs)||1e4,syncIntervalMs:(null==l?void 0:l.syncIntervalMs)||0,evaluationMode:(null==l?void 0:l.evaluationMode)||"differential-sync",noteStatus:null==l?void 0:l.noteStatus},this.apiEndpoint=t,this.sdkKey=i,this.identity=e,this.session=s,this.logger=n,this.storage=r||null,this.displayOptions=o||{},this.bridge=h||null,this.auth=a||null,this.loadImpressionTimestamps(),this.installHostBridge(),this.installPageLifecycle()}pageHidden(){return"undefined"!=typeof document&&("hidden"===document.visibilityState||!0===document.hidden)}installPageLifecycle(){if("undefined"==typeof window||"function"!=typeof window.addEventListener)return;const t=(t,i,e)=>{t&&"function"==typeof t.addEventListener&&(t.addEventListener(i,e),this.pageListeners.push([t,i,e]))},i=()=>{this.pageLeaving=!0,this.pauseDwells(),this.settleWaiters.forEach(t=>t())},e=()=>{this.pageLeaving&&(this.pageLeaving=!1,this.resumeDwells())};t(window,"beforeunload",i),t(window,"pagehide",i),t(window,"pageshow",()=>{this.pageLeaving=!1,this.resumeDwells()}),t(window,"pointerdown",e),t(window,"keydown",e),"undefined"!=typeof document&&t(document,"visibilitychange",()=>{this.pageHidden()?this.pauseDwells():(this.pageLeaving=!1,this.resumeDwells())})}removePageLifecycle(){var t;for(const[i,e,s]of this.pageListeners)try{null===(t=i.removeEventListener)||void 0===t||t.call(i,e,s)}catch(t){}this.pageListeners=[]}whenPageSettled(){return"undefined"==typeof window||"undefined"==typeof document?Promise.resolve(!0):this.pageLeaving?Promise.resolve(!1):new Promise(t=>{let i,e,s=!1;const n=window,r=r=>{s||(s=!0,this.settleWaiters.delete(o),i&&clearTimeout(i),e&&clearTimeout(e),"function"==typeof n.removeEventListener&&n.removeEventListener("load",a),t(r&&!this.pageLeaving))},o=()=>r(!1),h=()=>{s||("function"==typeof n.requestIdleCallback?n.requestIdleCallback(()=>r(!0),{timeout:500}):e=setTimeout(()=>r(!0),50))},a=()=>{i&&clearTimeout(i),i=void 0,h()};this.settleWaiters.add(o);const l=document.readyState;l&&"complete"!==l&&"function"==typeof n.addEventListener?(n.addEventListener("load",a,{once:!0}),i=setTimeout(a,1e4)):h()})}isMounted(t){if(!this.displayedMessages.has(t)||"undefined"==typeof document)return!1;const i=document.getElementById("joryio-inapp-"+t);return!!i&&!1!==i.isConnected}scheduleDwell(t,i){const e=this.awaitingDwell.get(t);if((null==e?void 0:e.timer)&&clearTimeout(e.timer),this.pageLeaving||this.pageHidden())return void this.awaitingDwell.set(t,{timer:null,generation:i});const s=setTimeout(()=>{const i=this.awaitingDwell.get(t);i&&i.timer===s&&(i.timer=null,this.pageLeaving||this.pageHidden()||!this.isMounted(t)||i.generation===this.generation&&this.confirmDisplay(t).catch(()=>{}))},Bt);this.awaitingDwell.set(t,{timer:s,generation:i})}pauseDwells(){this.awaitingDwell.forEach(t=>{t.timer&&clearTimeout(t.timer),t.timer=null})}resumeDwells(){this.pageLeaving||this.pageHidden()||this.awaitingDwell.forEach((t,i)=>{!t.timer&&this.isMounted(i)&&this.scheduleDwell(i,t.generation)})}dropDwell(t){const i=this.awaitingDwell.get(t);(null==i?void 0:i.timer)&&clearTimeout(i.timer),this.awaitingDwell.delete(t)}confirmDisplay(t){if(!this.awaitingDwell.has(t))return Promise.resolve();this.dropDwell(t);const i=this.impressionTimestamps.get(t)||[];i.push(Date.now()),this.boundedMapSet(this.impressionTimestamps,t,i,500),this.persistImpressionTimestamps();const e=this.trackImpression(t,"displayed"),s=this.displayedMessages.get(t);return s&&this.callHost("onMessageDisplay",()=>{var t,i;return null===(i=(t=this.displayOptions).onDisplay)||void 0===i?void 0:i.call(t,s)}),e}loadImpressionTimestamps(){if(this.storage)try{const t=this.storage.get(Ht);if(t&&"object"==typeof t)for(const[i,e]of Object.entries(t))Array.isArray(e)&&this.impressionTimestamps.set(i,e.filter(t=>"number"==typeof t))}catch(t){this.logger.error("Failed to load persisted impression timestamps:",t)}}persistImpressionTimestamps(){if(this.storage)try{const t={};this.impressionTimestamps.forEach((i,e)=>{t[e]=i}),this.storage.set(Ht,t)}catch(t){this.logger.error("Failed to persist impression timestamps:",t)}}installHostBridge(){"undefined"!=typeof window&&(window[Lt]={logCustomEvent:(t,i,e)=>{var s;this.displayedMessages.has(t)&&i&&(null===(s=this.bridge)||void 0===s||s.logCustomEvent(i,e))},setCustomUserAttribute:(t,i,e)=>{var s;this.displayedMessages.has(t)&&i&&(null===(s=this.bridge)||void 0===s||s.setCustomUserAttribute(i,e))},changeUser:(t,i)=>{var e;this.displayedMessages.has(t)&&i&&(null===(e=this.bridge)||void 0===e||e.changeUser(i))},requestPushPermission:t=>{var i;this.displayedMessages.has(t)&&(null===(i=this.bridge)||void 0===i||i.requestPushPermission())},logConversion:(t,i)=>{this.displayedMessages.has(t)&&i&&this.trackConversion(t,i).catch(()=>{})},logClick:(t,i)=>{if(!this.displayedMessages.has(t))return;const e=Gt(i);this.trackImpression(t,"clicked",e?{elementId:e}:void 0).catch(()=>{});const s=this.displayedMessages.get(t);s&&this.callHost("onMessageClick",()=>{var t,e;return null===(e=(t=this.displayOptions).onClick)||void 0===e?void 0:e.call(t,s,i||"click")})},navigate:(t,i,e)=>{if(!this.displayedMessages.has(t)||"string"!=typeof i)return;if(!/^(https?:\/\/|\/(?!\/))/i.test(i))return;const s=()=>{"_top"===e||"_self"===e?window.top&&(window.top.location.href=i):window.open(i,"_blank","noopener")};if(!this.links)return s();let n=i;try{n=new URL(i,window.location.href).href}catch(t){}this.links.route(n,"in_app",{campaignId:t},s)},closeMessage:t=>{this.displayedMessages.has(t)&&this.dismiss(t,"bridge_close").catch(()=>{})},submitForm:(t,i)=>this.displayedMessages.has(t)&&i&&"object"==typeof i?(this.trackImpression(t,"clicked").catch(()=>{}),this.submitForm(t,i)):Promise.resolve({ok:!1,message:"This message is no longer open."}),setSize:(t,i,e)=>{var s;const n=this.iframes.get(t);if(!n||!Number.isFinite(e)||0>=e)return;const r=null===(s=this.displayedMessages.get(t))||void 0===s?void 0:s.campaign.type;n.style.height="fullscreen"===r?"100%":Math.ceil(e)+"px"}})}async initialize(){this.runtime.canSend()&&(this.logger.info("Initializing in-app messaging"),this.stop(),await this.sync().catch(t=>{this.logger.error("Initial in-app sync failed:",t)}),this.startAttributeWatching(),this.startPeriodicSync())}stop(){this.syncInterval&&(clearInterval(this.syncInterval),this.syncInterval=void 0),this.periodicSyncTimer&&(clearInterval(this.periodicSyncTimer),this.periodicSyncTimer=void 0),this.syncRetryTimer&&(clearTimeout(this.syncRetryTimer),this.syncRetryTimer=void 0),this.syncRetried=!1,this.pendingDelays.forEach(t=>clearTimeout(t)),this.pendingDelays.clear(),this.settleWaiters.forEach(t=>t())}startPeriodicSync(){this.periodicSyncTimer&&(clearInterval(this.periodicSyncTimer),this.periodicSyncTimer=void 0),"differential-sync"===this.runtime.evaluationMode&&this.runtime.syncIntervalMs>0&&(this.periodicSyncTimer=setInterval(()=>{"undefined"!=typeof document&&document.hidden||this.runtime.canSend()&&this.sync().catch(t=>this.logger.debug("Periodic in-app sync failed:",t))},this.runtime.syncIntervalMs))}subject(){const t=this.identity.getUserId();return Object.assign(Object.assign({},t?{userId:t}:{}),{anonymousId:this.identity.getAnonymousId()})}async maybeHandleSdkAuthError(t,i,e){var s,n,r,o;if(!this.auth||401!==t.status)return;if((e||null)!==((this.auth.getCurrentUserId?this.auth.getCurrentUserId():this.identity.getUserId())||null))return;let h=null;try{h=await t.clone().json()}catch(t){return}if(null===(n=(s=this.auth).isStorefrontIdentityError)||void 0===n?void 0:n.call(s,t.status,h))await(null===(o=(r=this.auth).handleStorefrontIdentityError)||void 0===o?void 0:o.call(r,h).catch(()=>!1));else if(this.auth.isSdkAuthError(t.status,h)){this.logger.warn(`In-app request rejected by SDK authentication (${(null==h?void 0:h.reason)||"invalid"}) on ${i} – refreshing token`);try{await this.auth.refreshSdkAuthToken({reason:(null==h?void 0:h.reason)||"invalid",endpoint:i,userId:e})}catch(t){this.logger.error("Failed to refresh SDK authentication token for in-app request:",t)}}}async sync(t){var i,e,s;if(!this.runtime.canSend())return{success:!1,campaigns:[],evaluatedAt:(new Date).toISOString()};if(this.isSyncing)return this.syncAgain=!0,t&&(this.syncAgainChanges=Object.assign(Object.assign({},this.syncAgainChanges||{}),t)),{success:!1,campaigns:[],evaluatedAt:(new Date).toISOString()};this.isSyncing=!0;const n=this.generation;this.logger.debug("Syncing in-app campaigns");const r=this.session.getSessionId(),h=this.identity.getAttributes(),a=new AbortController,l=this.runtime.requestTimeoutMs,u=setTimeout(()=>a.abort(),l),c=this.identity.getUserId();try{const l=await fetch(this.apiEndpoint+"/v1/in-app/sync",{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(i=this.auth)||void 0===i?void 0:i.getSdkAuthHeaders(c,c?null:this.identity.getAnonymousId()))||{}),body:JSON.stringify(Object.assign(Object.assign({},this.subject()),{sessionId:r,userAttributes:t||h,pendingAttributes:this.identity.pending.pending(this.identity.getAnonymousId()),deviceType:"web",locale:navigator.language,capabilities:this.capabilities()})),signal:a.signal});if(!l.ok)throw null===(s=(e=this.runtime).noteStatus)||void 0===s||s.call(e,l.status,null),await this.maybeHandleSdkAuthError(l,this.apiEndpoint+"/v1/in-app/sync",c),Error(`Sync failed: ${l.status} ${l.statusText}`);const u=await l.json();if(n!==this.generation)return this.logger.debug("Discarding an in-app sync answer that predates an identity or consent change"),this.syncAgain=!0,{success:!1,campaigns:[],evaluatedAt:(new Date).toISOString()};if(!u||!1===u.success||!Array.isArray(u.campaigns))throw Error("Sync failed: the server reported success: false");this.syncRetried=!1,this.campaigns.clear();for(const t of u.campaigns)this.campaigns.set(t.id,t),"differential-sync"===t.evaluationMode&&t.watchedAttributes&&t.watchedAttributes.forEach(t=>this.boundedSetAdd(this.watchedAttributes,t,200));return this.logger.info(`Synced ${u.campaigns.length} eligible campaigns`),this.processImmediateTriggers(),u}catch(t){const i="AbortError"===(null==t?void 0:t.name);throw this.logger.error(i?`Campaign sync timed out after ${l}ms`:"Failed to sync campaigns:",t),n===this.generation&&!this.syncRetried&&this.runtime.canSend()&&(this.syncRetried=!0,this.syncRetryTimer=setTimeout(()=>{this.syncRetryTimer=void 0,this.sync().catch(()=>{})},5e3)),i?Error("Campaign sync timed out"):t}finally{if(clearTimeout(u),this.isSyncing=!1,this.syncAgain){this.syncAgain=!1;const t=this.syncAgainChanges;this.syncAgainChanges=void 0,this.runtime.canSend()&&this.sync(n!==this.generation?void 0:t).catch(t=>this.logger.debug("Follow-up in-app sync failed:",t))}}}processImmediateTriggers(){for(const t of this.campaigns.values())(t.triggers||[]).some(t=>"immediate"===t.type||"page_view"===t.type&&!!this.page)&&this.displayCampaign(t).catch(t=>this.logger.error("In-app display failed:",t))}onEventTracked(t,i){if(t)for(const e of this.campaigns.values())if((e.triggers||[]).find(e=>"event"===e.type&&e.event===t&&this.triggerFilterMatches(e,i)))return void this.displayCampaign(e).catch(t=>this.logger.error("In-app display failed:",t))}triggerFilterMatches(t,i){return ii(t,i)}async resolveForDisplay(t){var i,e,s;if(!this.runtime.canSend())return null;const n=this.generation,r=new AbortController,h=setTimeout(()=>r.abort(),this.runtime.requestTimeoutMs);try{const h=await fetch(this.apiEndpoint+"/v1/in-app/resolve",{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(i=this.auth)||void 0===i?void 0:i.getSdkAuthHeaders(this.identity.getUserId(),this.identity.getUserId()?null:this.identity.getAnonymousId()))||{}),body:JSON.stringify(Object.assign(Object.assign(Object.assign({},this.subject()),{campaignId:t.id,sessionId:this.session.getSessionId(),userAttributes:this.identity.getAttributes(),pendingAttributes:this.identity.pending.pending(this.identity.getAnonymousId()),deviceType:"web",capabilities:this.capabilities()}),this.page?{context:this.page.current()}:{})),signal:r.signal});if(!h.ok)return null===(s=(e=this.runtime).noteStatus)||void 0===s||s.call(e,h.status,null),null;const a=await h.json();return n!==this.generation?null:(null==a?void 0:a.eligible)&&a.campaign?a.campaign:null}catch(t){return null}finally{clearTimeout(h)}}canPromptForPush(){try{return"undefined"!=typeof Notification&&"default"===Notification.permission}catch(t){return!1}}async displayCampaign(t){const i=t.id;if(!this.pageAllows(t))return void this.logger.debug(`Campaign ${i} not for this page`);if(this.claimed.has(i)||this.displayedMessages.has(i)||this.pendingDelays.has(i))return void this.logger.debug(`Campaign ${i} already displayed, scheduled or being prepared`);this.claimed.add(i);const e=this.generation;try{if(t.reevaluateBeforeDisplay){const i=await this.resolveForDisplay(t);if(!i)return void this.logger.info(`Campaign ${t.id} not displayed: re-check said no`);t=i}if(this.displayedMessages.has(t.id)||this.pendingDelays.has(t.id))return void this.logger.debug(`Campaign ${t.id} already displayed or scheduled`);if(!this.checkFrequencyCap(t))return void this.logger.debug(`Campaign ${t.id} blocked by frequency cap`);const s=await this.renderTemplate(t);if(e!==this.generation||!this.runtime.canSend())return void this.logger.debug(`Campaign ${t.id} not displayed: the visitor or consent changed meanwhile`);const n=this.undisplayableReason(t,s);if(n)return void this.logger.warn(`Campaign ${t.id} not displayed (${n}). No impression recorded and no frequency cap consumed, so it stays eligible.`);if(s.includes("requestPushPermission")&&!this.canPromptForPush())return void this.logger.debug(`Campaign ${t.id} is a push primer but the browser can't be prompted (permission not 'default'); suppressing.`);const r=()=>{const i={campaign:t,renderedHtml:s,displayedAt:new Date};this.boundedMapSet(this.displayedMessages,t.id,i,500),this.display(i),this.scheduleDwell(t.id,e)},o=async()=>{await this.whenPageSettled()?e===this.generation&&this.runtime.canSend()?!this.displayedMessages.has(t.id)&&this.checkFrequencyCap(t)&&r():this.logger.debug(`Campaign ${t.id} not displayed: the visitor or consent changed`):this.logger.debug(`Campaign ${t.id} not displayed: the page is unloading. It stays eligible.`)},h=1e3*Math.max(0,+t.delay||0);if(h>0){const e=setTimeout(()=>{this.pendingDelays.delete(t.id),this.claimed.has(i)||this.displayedMessages.has(i)||(this.claimed.add(i),o().catch(t=>this.logger.error("In-app display failed:",t)).finally(()=>this.claimed.delete(i)))},h);return void this.pendingDelays.set(t.id,e)}await o()}finally{this.claimed.delete(i)}}async renderTemplate(t){const i=t.content;return i&&"html"===i.kind?i.html:""}undisplayableReason(t,i){var e;const s=null===(e=t.content)||void 0===e?void 0:e.kind;return t.content?"native"===s?null:"html"===s?i.trim()?this.allowHtmlJsInAppMessages?null:"it is an HTML message and allowHtmlJsInAppMessages is false":"its `content.html` is empty":`this SDK cannot render content kind '${s+""}'`:"the payload carries no `content`"}display(t){var i,e,s,n,r,o,h;const{campaign:a,renderedHtml:l}=t,u=document.createElement("div");u.id="joryio-inapp-"+a.id;const c=Qt.has(a.type)?null:["top","center","bottom"].find(t=>t===this.displayOptions.defaultPosition)||"center",d=["fade","slide","none"].find(t=>t===this.displayOptions.defaultAnimation)||"fade";u.className="joryio-inapp joryio-inapp-"+a.type+(c?" joryio-inapp-pos-"+c:"")+("none"!==d?" joryio-inapp-anim-"+d:"");const f=document.createElement("style");f.id="joryio-style-"+a.id;const p=Number.isFinite(this.displayOptions.zIndex)?+this.displayOptions.zIndex:999999,y=Zt(this.displayOptions.backdropColor)||"rgba(0, 0, 0, 0.5)",v=Zt(this.displayOptions.closeButtonColor)||"inherit";f.textContent=`\n .joryio-inapp {\n position: fixed;\n z-index: ${p};\n }\n\n /* displayOptions.defaultPosition - only for types with no placement of their own. */\n .joryio-inapp-pos-top {\n top: 20px;\n left: 50%;\n transform: translateX(-50%);\n max-width: 90%;\n }\n .joryio-inapp-pos-center {\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n max-width: 90%;\n max-height: 90%;\n }\n .joryio-inapp-pos-bottom {\n bottom: 20px;\n left: 50%;\n transform: translateX(-50%);\n max-width: 90%;\n }\n\n /* displayOptions.defaultAnimation. The individual \`translate\` property\n composes with the positioning \`transform\` above instead of\n replacing it. Motion is skipped for visitors who asked for less. */\n @keyframes joryio-inapp-fade-in { from { opacity: 0; } to { opacity: 1; } }\n @keyframes joryio-inapp-slide-in { from { opacity: 0; translate: 0 16px; } to { opacity: 1; translate: 0 0; } }\n .joryio-inapp-anim-fade { animation: joryio-inapp-fade-in 200ms ease-out both; }\n .joryio-inapp-anim-slide { animation: joryio-inapp-slide-in 240ms ease-out both; }\n @media (prefers-reduced-motion: reduce) {\n .joryio-inapp-anim-fade, .joryio-inapp-anim-slide { animation: none; }\n }\n\n /* The message content lives in a sandboxed iframe; its own CSS stays\n inside it (no leak to/from the host page). Only SDK chrome is here. */\n .joryio-inapp > iframe {\n border: 0;\n width: 100%;\n display: block;\n background: transparent;\n color-scheme: normal;\n }\n\n .joryio-inapp-modal {\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n max-width: 90%;\n max-height: 90%;\n }\n\n .joryio-inapp-banner {\n top: 0;\n left: 0;\n right: 0;\n }\n\n .joryio-inapp-slideup {\n bottom: 20px;\n right: 20px;\n max-width: 400px;\n }\n\n .joryio-inapp-fullscreen {\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n }\n\n /* Native card. Deliberately minimal and system-font: the host page's\n typography is the closest thing the web has to "the app's look", and\n a shipped palette would clash with every site.\n\n Every author-settable value comes through a CUSTOM PROPERTY with the\n system default as its fallback. That is what lets the campaign's own\n CSS override the colour pickers: inline styles beat a stylesheet, so\n setting the pickers inline would have made "advanced" strictly weaker\n than "basic" - the opposite of what an escape hatch is for. */\n .joryio-inapp-native {\n /* Positioning context for the close button, which sits in the card's\n top trailing corner rather than in the content flow. */\n position: relative;\n background: var(--joryio-inapp-bg, Canvas);\n color: var(--joryio-inapp-fg, CanvasText);\n color-scheme: light dark;\n border-radius: var(--joryio-inapp-radius, 14px);\n padding: 20px;\n box-shadow: 0 10px 40px rgba(0,0,0,0.18);\n font: menu;\n font-family: var(--joryio-inapp-font, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif);\n /* Direction-relative, so a Hebrew or Arabic message reads from the\n right without the campaign having to know which way it runs. The\n card carries dir=auto, so 'start' resolves per message. */\n text-align: var(--joryio-inapp-align, start);\n max-width: 420px;\n }\n .joryio-inapp-fullscreen .joryio-inapp-native {\n border-radius: 0;\n max-width: none;\n height: 100%;\n }\n .joryio-inapp-native img {\n width: 100%;\n height: 140px;\n object-fit: cover;\n border-radius: 8px;\n display: block;\n margin-bottom: 14px;\n }\n .joryio-inapp-native h2 {\n margin: 0 0 8px;\n /* Room for the close button in the trailing corner. Logical, so in a\n Hebrew message the gap is on the left, where the button is. */\n padding-inline-end: 28px;\n /* Derived from the body size so one control keeps the hierarchy. */\n font-size: calc(var(--joryio-inapp-size, 14.5px) * 1.3);\n font-weight: var(--joryio-inapp-title-weight, 700);\n line-height: 1.3;\n }\n .joryio-inapp-native p {\n margin: 0 0 16px;\n font-size: var(--joryio-inapp-size, 14.5px);\n line-height: 1.5;\n opacity: 0.85;\n }\n .joryio-inapp-buttons {\n display: flex;\n gap: 8px;\n }\n .joryio-inapp-buttons.stacked {\n flex-direction: column;\n }\n .joryio-inapp-native button {\n flex: 1;\n min-height: 44px;\n border-radius: 8px;\n font: inherit;\n font-size: 14px;\n cursor: pointer;\n border: 1px solid transparent;\n }\n .joryio-inapp-native button.primary {\n background: var(--joryio-inapp-primary, AccentColor);\n color: var(--joryio-inapp-primary-fg, AccentColorText);\n }\n .joryio-inapp-native button.secondary {\n background: transparent;\n color: inherit;\n border-color: rgba(128,128,128,0.4);\n }\n /*\n * Native messages used to override the shared close button into a\n * full-width "Close" text row under the buttons, while HTML messages in\n * this same SDK drew an ✕ in the corner. One SDK, two dismiss designs -\n * and the text row also hardcoded the English word "Close", which is\n * wrong in a Hebrew or Arabic app. The ✕ needs no translation, so native\n * now uses the shared button and this override is gone.\n */\n\n .joryio-inapp-backdrop {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: ${y};\n z-index: ${p-1};\n }\n\n .joryio-inapp-close {\n position: absolute;\n top: 6px;\n /* inset-inline-end, not right: the card carries dir=auto, so a Hebrew\n or Arabic message puts the ✕ in ITS trailing corner - the left one -\n without the campaign having to know which way the text runs. */\n inset-inline-end: 6px;\n display: flex;\n align-items: center;\n justify-content: center;\n /* 32px is the tap target; the glyph inside is smaller. Anything less\n is hard to hit on a phone, and it is the only way out of a\n full-screen message. */\n width: 32px;\n height: 32px;\n padding: 0;\n cursor: pointer;\n background: transparent;\n border: none;\n border-radius: 50%;\n font: inherit;\n font-size: 22px;\n line-height: 1;\n opacity: 0.55;\n color: ${v};\n }\n .joryio-inapp-close:hover,\n .joryio-inapp-close:focus-visible {\n opacity: 1;\n }\n `;const m=document.createElement("iframe");let b;if(m.id="joryio-iframe-"+a.id,"native"===(null===(i=a.content)||void 0===i?void 0:i.kind)){const i=a.content,s=document.createElement("div");s.className="joryio-inapp-native",s.dir="auto";const n=i.style;if("string"==typeof(null==n?void 0:n.customCss)&&(b=n.customCss),n){const t=(t,i,e="")=>{"string"==typeof i&&i.trim()?s.style.setProperty(t,i.trim()+e):"number"==typeof i&&Number.isFinite(i)&&s.style.setProperty(t,i+""+e)};t("--joryio-inapp-bg",n.backgroundColor),t("--joryio-inapp-fg",n.textColor),t("--joryio-inapp-font",n.fontFamily),t("--joryio-inapp-radius",n.cornerRadius,"px"),t("--joryio-inapp-size",n.fontSize,"px"),"string"==typeof n.titleWeight&&t("--joryio-inapp-title-weight",{regular:"400",medium:"500",semibold:"600",bold:"700"}[n.titleWeight]),"string"==typeof n.textAlign&&"auto"!==n.textAlign&&t("--joryio-inapp-align",n.textAlign),t("--joryio-inapp-primary",n.primaryButtonColor),t("--joryio-inapp-primary-fg","string"==typeof n.primaryButtonTextColor&&n.primaryButtonTextColor.trim()?n.primaryButtonTextColor:function(t){if("string"!=typeof t)return;const i=t.trim().replace(/^#/,""),e=3===i.length?i.replace(/(.)/g,"$1$1"):i;if(!/^[0-9a-f]{6}$/i.test(e))return;const[s,n,r]=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16));return.2126*s+.7152*n+.0722*r>150?"#0A1240":"#FFFFFF"}(n.primaryButtonColor))}if(i.imageUrl&&/^https:\/\//i.test(i.imageUrl)){const t=document.createElement("img");t.src=i.imageUrl,t.alt="",t.onerror=()=>t.remove(),s.appendChild(t)}if(i.title){const t=document.createElement("h2");t.textContent=i.title,s.appendChild(t)}const r=document.createElement("p");if(r.textContent=i.body,s.appendChild(r),null===(e=i.buttons)||void 0===e?void 0:e.length){const e=document.createElement("div");e.className=i.buttons.length>2?"joryio-inapp-buttons stacked":"joryio-inapp-buttons",i.buttons.forEach((i,s)=>{const n=document.createElement("button");n.type="button",n.textContent=i.text,n.className=0===s?"primary":"secondary",n.addEventListener("click",()=>{var e;const s=Gt(i.id);if(this.trackImpression(a.id,"clicked",Object.assign(Object.assign({},i.url&&/^https?:\/\//i.test(i.url)?{clickedUrl:i.url}:{}),s?{elementId:s}:{})).catch(()=>{}),this.callHost("onMessageClick",()=>{var e,s;return null===(s=(e=this.displayOptions).onClick)||void 0===s?void 0:s.call(e,t,i.id||i.action||"button")}),"request_push_permission"===i.action)this.canPromptForPush()&&(null===(e=this.bridge)||void 0===e||e.requestPushPermission());else if(("url"===i.action||"deep_link"===i.action)&&i.url){const t=i.url,e=()=>{/^https?:\/\//i.test(t)&&window.open(t,"_blank","noopener")};this.links?this.links.route(t,"in_app",{campaignId:a.id},e):e()}this.dismiss(a.id,"button").catch(()=>{})}),e.appendChild(n)}),s.appendChild(e)}if(!1!==i.closeButton){const t=document.createElement("button");t.type="button",t.className="joryio-inapp-close",t.innerHTML="&times;",t.setAttribute("aria-label","Close"),t.addEventListener("click",()=>{this.dismiss(a.id,"close_button").catch(()=>{})}),s.appendChild(t)}u.appendChild(s)}let g=!1;if("native"!==(null===(s=a.content)||void 0===s?void 0:s.kind)){if(!this.allowHtmlJsInAppMessages)return void this.logger.warn(`Campaign ${a.id} is an HTML in-app message, but allowHtmlJsInAppMessages is false - not displaying it.`);m.setAttribute("sandbox","allow-scripts allow-same-origin allow-popups");let t=0;m.addEventListener("load",()=>{var i,e;t++;let s=!0;try{const t=null===(e=null===(i=m.contentWindow)||void 0===i?void 0:i.location)||void 0===e?void 0:e.href;s=void 0===t||"about:srcdoc"===t}catch(t){s=!1}1>=t&&s||(this.logger.warn(`In-app message ${a.id} tried to navigate its frame; it has been closed`),this.dismiss(a.id,"navigation_blocked").catch(()=>{}))}),m.setAttribute("title",a.name||"Message"),m.style.height="0","banner"!==a.type&&"fullscreen"!==a.type||(m.style.width="100%");const i=function(t){var i;if("modal"!==t.type&&"slideup"!==t.type)return null;if("html"!==(null===(i=t.content)||void 0===i?void 0:i.kind))return null;const e=t.content.maxWidth;return"number"==typeof e&&Number.isFinite(e)&&e>0?Math.floor(e):Jt[t.type]}(a);if(null!==i&&(u.style.maxWidth="none",this.frameMaxWidths.set(a.id,i),m.style.width=Rt(i,this.hostViewportWidth())+"px",this.watchViewport()),m.srcdoc=this.buildSrcdoc(a.id,l,"html"===(null===(n=a.content)||void 0===n?void 0:n.kind)?a.content.css:"",a.type),u.appendChild(m),this.iframes.set(a.id,m),l.includes("requestPushPermission")&&(null===(o=null===(r=this.bridge)||void 0===r?void 0:r.preparePushPermission)||void 0===o||o.call(r)),!1!==this.displayOptions.closeButton){const t=document.createElement("button");t.className="joryio-inapp-close",t.innerHTML="&times;",t.setAttribute("aria-label","Close"),t.onclick=async()=>{g||(g=!0,await this.dismiss(a.id,"close_button").catch(()=>{}))},u.appendChild(t)}}let w=null;if("modal"===a.type||"fullscreen"===a.type){w=document.createElement("div"),w.className="joryio-inapp-backdrop",w.id="joryio-backdrop-"+a.id;const t="native"!==(null===(h=a.content)||void 0===h?void 0:h.kind)||!1!==a.content.backdropDismissible;!1!==this.displayOptions.backdropClose&&t&&(w.onclick=async()=>{g||(g=!0,await this.dismiss(a.id,"backdrop").catch(()=>{}))})}const k=this.displayOptions.container||document.documentElement;if(w&&k.appendChild(w),k.appendChild(f),"string"==typeof b&&b.trim()){const t=this.scopeCss(b,"#joryio-inapp-"+a.id);if(t){const i=document.createElement("style");i.id="joryio-css-"+a.id,i.textContent=t,k.appendChild(i)}}k.appendChild(u),this.logger.info(`Displayed campaign: ${a.name} (${a.id})`)}hostViewportWidth(){const t="undefined"!=typeof document?document.documentElement:null,i=t&&"number"==typeof t.clientWidth?t.clientWidth:0;return i>0?i:"undefined"!=typeof window&&"number"==typeof window.innerWidth?window.innerWidth:0}sizeContentFrame(t){const i=this.iframes.get(t),e=this.frameMaxWidths.get(t);i&&void 0!==e&&(i.style.width=Rt(e,this.hostViewportWidth())+"px")}watchViewport(){this.viewportListener||"undefined"==typeof window||"function"!=typeof window.addEventListener||(this.viewportListener=()=>{this.viewportTimer&&clearTimeout(this.viewportTimer),this.viewportTimer=setTimeout(()=>{this.viewportTimer=void 0;for(const t of this.frameMaxWidths.keys())this.sizeContentFrame(t)},100)},window.addEventListener("resize",this.viewportListener))}unwatchViewportIfIdle(){0>=this.frameMaxWidths.size&&this.viewportListener&&("undefined"!=typeof window&&"function"==typeof window.removeEventListener&&window.removeEventListener("resize",this.viewportListener),this.viewportListener=void 0,this.viewportTimer&&(clearTimeout(this.viewportTimer),this.viewportTimer=void 0))}buildSrcdoc(t,i,e,s){return ti(t,i,e,s)}scopeCss(t,i){let e=null;try{e=document.createElement("style"),e.media="not all",e.textContent=t,document.head.appendChild(e);const s=e.sheet;if(!s)return this.logger.warn("Custom CSS could not be parsed; ignoring it"),"";const n=Wt(s.cssRules,i);return n||this.logger.warn("Custom CSS contained no rules that can be scoped; ignoring it"),n}catch(t){return this.logger.warn("Custom CSS could not be parsed; ignoring it",t),""}finally{null==e||e.remove()}}async dismiss(t,i="dismiss"){const e=this.pendingDelays.get(t);e&&(clearTimeout(e),this.pendingDelays.delete(t));let s=!0;const n=this.awaitingDwell.get(t);n&&(Vt.has(i)&&n.generation===this.generation?this.confirmDisplay(t).catch(()=>{}):(this.dropDwell(t),s=!1));const r=document.getElementById("joryio-inapp-"+t),o=document.getElementById("joryio-backdrop-"+t),h=document.getElementById("joryio-style-"+t),a=document.getElementById("joryio-css-"+t);r&&r.remove(),this.iframes.delete(t),this.frameMaxWidths.delete(t),this.unwatchViewportIfIdle(),o&&o.remove(),h&&h.remove(),a&&a.remove();const l=this.displayedMessages.get(t);l&&(s&&await this.trackImpression(t,"dismissed").catch(()=>{}),this.callHost("onMessageDismiss",()=>{var t,e;return null===(e=(t=this.displayOptions).onDismiss)||void 0===e?void 0:e.call(t,l,i)}),this.displayedMessages.delete(t)),this.logger.info("Dismissed campaign: "+t)}async trackConversion(t,i){await this.trackImpression(t,"converted",{conversionEvent:i});const e=this.displayedMessages.get(t);e&&this.callHost("onConversion",()=>{var t,s;return null===(s=(t=this.displayOptions).onConversion)||void 0===s?void 0:s.call(t,e,i)})}async submitForm(t,i){var e,s,n;const r=this.displayedMessages.get(t);if(!this.runtime.canSend())return{ok:!1,message:"This form cannot be sent right now."};const h=new AbortController,a=setTimeout(()=>h.abort(),this.runtime.requestTimeoutMs),l=this.identity.getUserId();try{const a=()=>{var e,s,n;return fetch(this.apiEndpoint+"/v1/in-app/form-submit",{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(e=this.auth)||void 0===e?void 0:e.getSdkAuthHeaders(l,l?null:this.identity.getAnonymousId()))||{}),body:JSON.stringify(Object.assign(Object.assign({campaignId:t,variantId:null===(s=null==r?void 0:r.campaign)||void 0===s?void 0:s.variantId,userId:this.identity.getUserId()||void 0,anonymousId:this.identity.getAnonymousId()},(null===(n=null==r?void 0:r.campaign)||void 0===n?void 0:n.formToken)?{formToken:r.campaign.formToken}:{}),{values:i})),signal:h.signal})};let u=await a();if(401===u.status&&(null===(e=this.auth)||void 0===e?void 0:e.isStorefrontIdentityError)){const t=await u.clone().json().catch(()=>null);this.auth.isStorefrontIdentityError(401,t)&&await(null===(n=(s=this.auth).handleStorefrontIdentityError)||void 0===n?void 0:n.call(s,t).catch(()=>!1))&&(u=await a())}await this.maybeHandleSdkAuthError(u,this.apiEndpoint+"/v1/in-app/form-submit",l);const c=await u.json().catch(()=>null);return c&&"object"==typeof c?c:{ok:!1,message:"Something went wrong. Please try again."}}catch(t){return{ok:!1,message:"Something went wrong. Please try again."}}finally{clearTimeout(a)}}async trackImpression(t,i,e){var s,n,r,h,a;const l=this.campaigns.get(t)||(null===(s=this.displayedMessages.get(t))||void 0===s?void 0:s.campaign);if(!l)return;if(!this.runtime.canSend())return;const u="displayed"!==i?this.awaitingDwell.get(t):void 0;if(u){if(u.generation!==this.generation)return;this.confirmDisplay(t).catch(()=>{})}const c=this.session.getSessionId(),d=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({campaignId:t,variantId:l.variantId},this.subject()),{sessionId:c,deviceType:"web",locale:navigator.language,userAgent:navigator.userAgent}),l.pendingId?{pendingId:l.pendingId}:{}),l.deliveryToken?{deliveryToken:l.deliveryToken}:{}),e);"displayed"===i?d.displayedAt=(new Date).toISOString():"clicked"===i?(d.clicked=!0,d.clickedAt=(new Date).toISOString(),d.action="clicked"):"dismissed"===i?(d.dismissedAt=(new Date).toISOString(),d.action="dismissed"):"converted"===i&&(d.converted=!0,d.convertedAt=(new Date).toISOString());const f=new AbortController,p=setTimeout(()=>f.abort(),this.runtime.requestTimeoutMs),y="string"==typeof d.userId&&d.userId?d.userId:null;try{const e=await fetch(this.apiEndpoint+"/v1/in-app/track",{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(n=this.auth)||void 0===n?void 0:n.getSdkAuthHeaders(y,y?null:null!==(r=d.anonymousId)&&void 0!==r?r:null))||{}),body:JSON.stringify(d),signal:f.signal});e.ok||null===(a=(h=this.runtime).noteStatus)||void 0===a||a.call(h,e.status,null),await this.maybeHandleSdkAuthError(e,this.apiEndpoint+"/v1/in-app/track",y),this.logger.debug(`Tracked ${i} for campaign ${t}`)}catch(e){"AbortError"===(null==e?void 0:e.name)?this.logger.error(`Impression tracking timed out after ${this.runtime.requestTimeoutMs}ms for campaign ${t}`):this.logger.error(`Failed to track ${i}:`,e)}finally{clearTimeout(p)}}checkFrequencyCap(t){if(!t.frequencyCap)return!0;const{maxImpressions:i,timeWindow:e,minDelayBetweenImpressions:s}=t.frequencyCap;if(!i||!e)return!0;const n=this.impressionTimestamps.get(t.id)||[],r=Date.now();let o=0;if("once"===e||"lifetime"===e)return 0===n.length;if("session"===e)o=this.session.getSessionInfo().sessionStart;else{const t=[["min",6e4],["mo",2592e6],["h",36e5],["d",864e5],["w",6048e5],["m",2592e6]];let i=864e5;for(const[s,n]of t){if(!e.endsWith(s))continue;const t=parseInt(e.slice(0,-s.length),10);!Number.isNaN(t)&&t>0&&(i=t*n);break}o=r-i}return n.filter(t=>t>=o).length<i&&!(s&&n.length>0&&1e3*s>r-n[n.length-1])}startAttributeWatching(){if(this.syncInterval&&(clearInterval(this.syncInterval),this.syncInterval=void 0),0===this.watchedAttributes.size)return;this.logger.debug(`Watching ${this.watchedAttributes.size} attributes for changes`);const t={};this.watchedAttributes.forEach(i=>{t[i]=this.identity.getAttribute(i)}),this.syncInterval=window.setInterval(()=>{if("undefined"!=typeof document&&document.hidden)return;const i={};let e=!1;if(this.watchedAttributes.forEach(s=>{const n=this.identity.getAttribute(s);n!==t[s]&&(i[s]=n,t[s]=n,e=!0)}),e){if(this.checkAttributeThresholds(Object.keys(i)),"session-start-only"===this.runtime.evaluationMode||!this.runtime.canSend())return;this.logger.info("Attribute changes detected, re-syncing campaigns"),this.sync(i).catch(t=>{this.logger.error("Failed to re-sync on attribute change:",t)})}},5e3)}checkAttributeThresholds(t){if(!t.length)return;const i=this.identity.getAttributes()||{};for(const e of this.campaigns.values())if((e.triggers||[]).some(e=>"attribute_threshold"===e.type&&!!e.attribute&&t.includes(e.attribute)&&this.triggerFilterMatches(e,i)))return void this.displayCampaign(e).catch(t=>this.logger.error("In-app display failed:",t))}getCampaigns(){return Array.from(this.campaigns.values())}getCampaign(t){return this.campaigns.get(t)}clearAll(){this.logger.info("Clearing in-app messaging state"),this.invalidate(),this.stop();for(const t of this.displayedMessages.keys())this.dismiss(t,"clear").catch(t=>this.logger.error("In-app dismiss failed:",t));this.campaigns.clear(),this.displayedMessages.clear(),this.awaitingDwell.forEach((t,i)=>this.dropDwell(i)),this.watchedAttributes.clear(),this.iframes.clear(),this.frameMaxWidths.clear(),this.unwatchViewportIfIdle(),this.logger.info("In-app messaging state cleared")}forgetImpressions(){var t;this.impressionTimestamps.clear();try{null===(t=this.storage)||void 0===t||t.remove(Ht)}catch(t){}}boundedMapSet(t,i,e,s){if(t.set(i,e),t.size>s){const i=t.keys().next().value;void 0!==i&&t.delete(i)}}boundedSetAdd(t,i,e){if(t.add(i),t.size>e){const i=t.values().next().value;void 0!==i&&t.delete(i)}}destroy(){var t;null===(t=this.pageUnsubscribe)||void 0===t||t.call(this),this.pageUnsubscribe=null,this.logger.info("Destroying in-app messaging"),this.stop();for(const t of this.displayedMessages.keys())this.dismiss(t,"destroy").catch(t=>this.logger.error("In-app dismiss failed:",t));this.campaigns.clear(),this.displayedMessages.clear(),this.awaitingDwell.forEach((t,i)=>this.dropDwell(i)),this.removePageLifecycle(),this.impressionTimestamps.clear(),this.watchedAttributes.clear(),this.iframes.clear(),this.frameMaxWidths.clear(),this.unwatchViewportIfIdle(),"undefined"!=typeof window&&delete window[Lt]}}function ti(t,i,e,s,n=Lt){const r="modal"===s||"slideup"===s||"placement"===s,o=r?"body{display:flow-root;}":"",h=`(function(){\n var CID=${JSON.stringify(t)},KEY=${JSON.stringify(n)},SIZED=${r?"true":"false"};\n // Per-device visibility: tag the root with the REAL device class from the\n // HOST page viewport (the iframe is message-sized, so its own innerWidth is\n // useless here). The jr-vp-* → jr-hide-* rules in <style> then hide elements\n // the dashboard marked "Mobile only" / "Desktop only". <=480 = mobile.\n try{var __vp=0;try{__vp=window.parent.innerWidth||0;}catch(e){}if(!__vp)__vp=window.innerWidth||0;document.documentElement.className+=(__vp<=480?' jr-vp-mobile':' jr-vp-desktop');}catch(e){}\n function host(){try{return window.parent[KEY]||null;}catch(e){return null;}}\n function call(m,args){var b=host();if(b&&typeof b[m]==='function'){try{return b[m].apply(b,[CID].concat(args||[]));}catch(e){}}}\n window.joryioBridge={\n logCustomEvent:function(name,props){call('logCustomEvent',[name,props]);},\n setCustomUserAttribute:function(k,v){call('setCustomUserAttribute',[k,v]);},\n changeUser:function(uid){call('changeUser',[uid]);},\n requestPushPermission:function(){call('requestPushPermission',[]);},\n logConversion:function(ev){call('logConversion',[ev||'in_app_conversion']);},\n submitForm:function(values){return call('submitForm',[values]);},\n logClick:function(action){call('logClick',[action]);},\n navigate:function(url,target){call('navigate',[url,target]);},\n closeMessage:function(){call('closeMessage',[]);}\n };\n document.addEventListener('click',function(e){\n var el=e.target;\n while(el&&el!==document.body&&el!==document.documentElement){\n var action=el.getAttribute&&el.getAttribute('data-joryio-action');\n if(action&&typeof window.joryioBridge[action]==='function'){e.preventDefault();window.joryioBridge[action](el.getAttribute('data-joryio-event')||undefined);return;}\n var tag=el.tagName;\n if(tag==='A'||tag==='BUTTON'){\n var da=el.getAttribute('data-action');\n var href=tag==='A'?el.getAttribute('href'):null;\n window.joryioBridge.logClick(da||(href?'link_click':'cta_click'));\n // Route only http(s)/root-relative links through the host (top-nav,\n // since the sandbox can't navigate the top page itself). Leave\n // #anchors, mailto:, tel:, sms: to the browser. Any other link\n // would navigate THIS frame away from the message: cancelled (rule 57).\n if(href&&/^(https?:\\/\\/|\\/(?!\\/))/i.test(href)){e.preventDefault();window.joryioBridge.navigate(href,el.getAttribute('target'));}\n else if(href&&!/^(#|mailto:|tel:|sms:)/i.test(href)){e.preventDefault();}\n return;\n }\n el=el.parentNode;\n }\n },true);\n // Forms (data-jry-form): serialize, hand the values to the host, show the\n // answer in place. A redirect goes through navigate (the sandbox cannot).\n document.addEventListener('submit',function(ev){var f=ev.target;if(!(f&&f.tagName==='FORM'&&f.hasAttribute('data-jry-form')))return;ev.preventDefault();if(f.getAttribute('data-jry-busy'))return;\n var d={},els=f.querySelectorAll('input,select,textarea');for(var i=0;i<els.length;i++){var el=els[i],n=el.name;if(!n||el.disabled)continue;if(el.type==='checkbox'){if(!el.checked)continue;if(d[n]===undefined)d[n]=[];d[n].push(el.value||'on')}else if(el.type==='radio'){if(el.checked)d[n]=el.value}else d[n]=el.value}\n function msg(text,ok){var b=f.querySelector('[data-jry-message]');if(!b){b=document.createElement('div');b.setAttribute('data-jry-message','');b.setAttribute('role','status');f.appendChild(b)}b.textContent=text;b.className=ok?'jry-form-success':'jry-form-error';reportSize()}\n f.setAttribute('data-jry-busy','1');var btn=f.querySelector('button[type="submit"],input[type="submit"]');if(btn)btn.disabled=true;\n var p=window.joryioBridge.submitForm(d);if(!p||typeof p.then!=='function'){msg('This form cannot be sent here.',false);f.removeAttribute('data-jry-busy');if(btn)btn.disabled=false;return}\n p.then(function(r){if(r&&r.ok){if(r.redirect){window.joryioBridge.navigate(r.redirect,'_top');return}var els2=f.querySelectorAll('input,select,textarea,button');for(var j=0;j<els2.length;j++){els2[j].disabled=true}msg(r.message||'Thank you.',true)}else{msg((r&&(r.message||(r.errors&&r.errors[0])))||'Something went wrong. Please try again.',false);f.removeAttribute('data-jry-busy');if(btn)btn.disabled=false}}).catch(function(){msg('Something went wrong. Please try again.',false);f.removeAttribute('data-jry-busy');if(btn)btn.disabled=false});\n },true);\n function reportSize(){try{var b=document.body,de=document.documentElement;var w=Math.max(b?b.scrollWidth:0,de.scrollWidth);var h=SIZED&&b?Math.ceil(Math.max(b.scrollHeight,b.getBoundingClientRect?b.getBoundingClientRect().height:0)):Math.max(b?b.scrollHeight:0,de.scrollHeight);call('setSize',[w,h]);}catch(e){}}\n if(document.readyState!=='loading')reportSize();else document.addEventListener('DOMContentLoaded',reportSize);\n window.addEventListener('load',reportSize);\n try{if(window.ResizeObserver&&document.body){new ResizeObserver(reportSize).observe(document.body);}}catch(e){}\n })();`,a=function(){const t=new Uint8Array(16),i=globalThis.crypto;if(i&&"function"==typeof i.getRandomValues)i.getRandomValues(t);else for(let i=0;i<t.length;i++)t[i]=Math.floor(256*Math.random());return Array.from(t,t=>t.toString(16).padStart(2,"0")).join("")}();return`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${["default-src 'none'",`script-src 'nonce-${a}'`,"style-src 'unsafe-inline'; img-src https: data:; media-src https: data:; font-src https: data:; connect-src 'none'; form-action 'none'; base-uri 'none'; upgrade-insecure-requests"].join("; ")}"><meta name="viewport" content="width=device-width, initial-scale=1"><style>html,body{margin:0;padding:0;}img,video{max-width:100%;height:auto;}${o}.jr-vp-mobile .jr-hide-mobile{display:none!important}.jr-vp-desktop .jr-hide-desktop{display:none!important}${e=function(t){return"string"==typeof t?t.replace(/<\//g,"<\\/"):""}(e)}</style></head><body>${i}<script nonce="${a}">${h}<\/script></body></html>`}function ii(t,i){if(!t.attribute)return!0;const e=null==i?void 0:i[t.attribute],s=t.value;switch(t.operator){case void 0:case"equals":case"eq":return e===s;case"not_equals":case"neq":return e!==s;case"greater_than":case"gt":return+e>+s;case"less_than":case"lt":return+s>+e;case"contains":return((null!=e?e:"")+"").includes(s+"");case"exists":return null!=e;default:return!1}}function ei(t){let i=!1;const e=()=>{i||(i=!0,t())},s=()=>e();return s.cancel=e,s}const si="product:";function ni(t){return`${si}${t}`.slice(0,128)}const ri=t=>"joryio_placements_v1_"+e(t).toString(36),oi="__joryioPlacement",hi=/^[a-z0-9][a-z0-9_]{0,63}$/,ai=()=>Date.now();function li(t){return"string"==typeof t&&hi.test(t)}function ui(){try{const t=null===navigator||void 0===navigator?void 0:navigator.userActivation;return!t||!0===t.isActive}catch(t){return!0}}function ci(t){return"string"==typeof t&&/^https?:\/\//i.test(t)?t:null}const di=["javascript","data","file","vbscript","blob","about","content","intent"];function fi(t){if("string"!=typeof t)return!1;const i=/^([a-z][a-z0-9+.-]*):\/\/./i.exec(t.trim());if(!i)return!1;const e=i[1].toLowerCase();return"http"!==e&&"https"!==e&&!di.includes(e)}function pi(){return"undefined"==typeof document||"hidden"!==document.visibilityState}function yi(t,i){let e=!1;const s={observer:null,timer:null,inView:!1,resume:()=>{!e&&!s.timer&&s.inView&&pi()&&(s.timer=setTimeout(()=>{var t;s.timer=null,!e&&s.inView&&pi()&&(e=!0,null===(t=s.observer)||void 0===t||t.disconnect(),i())},Bt))},pause:()=>{s.timer&&clearTimeout(s.timer),s.timer=null},cancel:()=>{var t;e=!0,null===(t=s.observer)||void 0===t||t.disconnect(),s.pause()}};return"undefined"==typeof IntersectionObserver?(s.inView=!0,s.resume(),s):(s.observer=new IntersectionObserver(t=>{for(const i of t)s.inView=i.isIntersecting&&i.intersectionRatio>=.5,s.inView?s.resume():s.pause()},{threshold:[0,.5,1]}),s.observer.observe(t),s)}class vi{constructor(t,i,e,s,n,r,o){this.apiEndpoint=t,this.sdkKey=i,this.identity=e,this.session=s,this.logger=n,this.runtime=r,this.auth=o,this.links=null,this.cache=new Map,this.lastNetworkAt=new Map,this.inflight=new Map,this.batchKeys=new Set,this.batchTimer=null,this.batchWaiters=[],this.deferredKeys=new Set,this.deferredTimer=null,this.listeners=new Set,this.mounts=new Set,this.reported=new Set,this.triggeredAt=new Map,this.dismissedLocally=new Set,this.generation=0,this.mutationObserver=null,this.frames=new Map,this.frameSeq=0,this.pageListener=null,this.destroyed=!1,this.page=null,this.pageUnsubscribe=null,this.pageScopedKeys=new Set,this.loadCache(),this.installBridge(),this.installPageVisibility()}insertPlacement(t,i,e={}){if(!li(t))return this.logger.warn(`insertPlacement: "${t}" is not a placement key (a-z, 0-9 and _, up to 64)`),null;if(!i||"function"!=typeof i.appendChild)return this.logger.warn("insertPlacement: an element is required"),null;for(const t of this.mounts)t.element===i&&this.unmount(t);const s={key:t,element:i,options:e,wrapper:null,shown:[],pendingUpdate:!1,hostInView:!1,hostObserver:null,trackers:[],frameIds:[]};return this.mounts.add(s),this.observeHost(s),this.freshEntry(t)&&this.render(s),this.ensure([t]).then(()=>{this.mounts.has(s)&&!s.wrapper&&this.render(s)}).catch(t=>this.logger.debug("Placement fetch failed:",t)),{placementKey:t,element:i,remove:()=>this.unmount(s)}}async getPlacements(t){const i=this.cleanKeys(t);await this.ensure(i);const e={};for(const t of i)e[t]=this.toPlacement(t);return e}async refreshPlacements(t){const i=t?this.cleanKeys(t):this.knownKeys();i.length&&await this.fetchKeys(i,!0)}onPlacementsUpdated(t){if("function"!=typeof t)return ei(()=>{});const i=i=>t(i);return this.listeners.add(i),ei(()=>{this.listeners.delete(i)})}autoMount(){"undefined"!=typeof document&&"function"==typeof document.querySelectorAll&&("loading"!==document.readyState||"function"!=typeof document.addEventListener?(this.scanDocument(),!this.mutationObserver&&"undefined"!=typeof MutationObserver&&document.body&&(this.mutationObserver=new MutationObserver(()=>this.scanDocument()),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}))):document.addEventListener("DOMContentLoaded",()=>!this.destroyed&&this.autoMount(),{once:!0}))}onEventTracked(t,i){if(!t)return;const e=new Set;for(const[s,n]of this.cache)for(const r of n.placement.items||[])(r.triggers||[]).some(e=>"event"===e.type&&e.event===t&&ii(e,i))&&(this.triggeredAt.set(this.handle(s,r),ai()),e.add(s));e.size&&this.applyChanged(Array.from(e))}invalidate(){this.generation++,this.cache.clear(),this.lastNetworkAt.clear(),this.triggeredAt.clear(),this.dismissedLocally.clear(),this.reported.clear(),this.persistCache();const t=this.mountedKeys();for(const t of this.mounts)this.render(t);t.length&&this.fetchKeys(t,!0).catch(()=>{})}destroy(){var t,i,e;this.destroyed=!0,null===(t=this.pageUnsubscribe)||void 0===t||t.call(this),this.pageUnsubscribe=null;for(const t of Array.from(this.mounts))this.unmount(t);null===(i=this.mutationObserver)||void 0===i||i.disconnect(),this.mutationObserver=null,this.batchTimer&&clearTimeout(this.batchTimer),this.deferredTimer&&clearTimeout(this.deferredTimer),this.batchTimer=null,this.deferredTimer=null,this.batchWaiters.forEach(t=>t.resolve()),this.batchWaiters=[],this.listeners.clear(),this.pageListener&&"undefined"!=typeof document&&"function"==typeof document.removeEventListener&&document.removeEventListener("visibilitychange",this.pageListener);try{"undefined"!=typeof window&&(null===(e=window[oi])||void 0===e?void 0:e.__owner)===this&&delete window[oi]}catch(t){}}cleanKeys(t){const i=[];for(const e of Array.isArray(t)?t:[])li(e)&&!i.includes(e)?i.push(e):li(e)||this.logger.warn(`Ignoring "${e}": not a placement key`);return i}knownKeys(){return Array.from(new Set([...this.mountedKeys(),...this.cache.keys()]))}mountedKeys(){return Array.from(new Set(Array.from(this.mounts).map(t=>t.key)))}setPageContext(t){var i;null===(i=this.pageUnsubscribe)||void 0===i||i.call(this),this.pageUnsubscribe=null,this.page=t,t&&(this.pageUnsubscribe=t.onSignal(t=>{if("page_change"!==t.type||this.destroyed)return;const i=[];if(this.cache.forEach((e,s)=>{e.placement.pageScoped&&e.url!==t.url&&i.push(s)}),!i.length)return;i.forEach(t=>this.cache.delete(t)),this.persistCache();for(const t of this.mounts)i.includes(t.key)&&this.render(t);const e=i.filter(t=>this.mountedKeys().includes(t));e.length&&this.fetchKeys(e,!1).then(()=>{for(const t of this.mounts)e.includes(t.key)&&!t.wrapper&&this.render(t)}).catch(()=>{})}))}currentUrl(){return this.page?this.page.current().url:m()}rateKey(t){var i,e;return(null===(i=this.cache.get(t))||void 0===i?void 0:i.placement.pageScoped)||this.pageScopedKeys.has(t)?`${t}\0${null!==(e=this.currentUrl())&&void 0!==e?e:""}`:t}freshEntry(t){const i=this.cache.get(t);if(!i)return null;if(i.placement.pageScoped&&i.url!==this.currentUrl())return null;const e=1e3*(i.placement.ttlSeconds||300);return ai()-i.fetchedAt<e?i:null}async ensure(t){const i=t.filter(t=>!this.freshEntry(t));i.length&&await this.fetchKeys(i,!1)}fetchKeys(t,i){const e=ai(),s=[],n=[];for(const r of t){const t=this.inflight.get(r);if(t){s.push(t),i&&this.defer(r);continue}const o=this.lastNetworkAt.get(this.rateKey(r));void 0!==o&&3e4>e-o?i&&this.defer(r):n.push(r)}if(n.length){n.forEach(t=>this.batchKeys.add(t));const t=new Promise(t=>this.batchWaiters.push({keys:n,resolve:t}));n.forEach(i=>this.inflight.set(i,t)),this.batchTimer||(this.batchTimer=setTimeout(()=>{this.flushBatch()},50)),s.push(t)}return Promise.all(s).then(()=>{})}defer(t){if(this.deferredKeys.add(t),this.deferredTimer)return;const i=Math.min(...Array.from(this.deferredKeys).map(t=>{var i;return null!==(i=this.lastNetworkAt.get(this.rateKey(t)))&&void 0!==i?i:0})),e=Math.max(0,i+3e4-ai());this.deferredTimer=setTimeout(()=>{this.deferredTimer=null;const t=Array.from(this.deferredKeys);this.deferredKeys.clear(),t.length&&!this.destroyed&&this.fetchKeys(t,!1).catch(()=>{})},e+10)}async flushBatch(){this.batchTimer=null;const t=Array.from(this.batchKeys);this.batchKeys.clear();const i=this.batchWaiters;this.batchWaiters=[];const e=[];for(let i=0;i<t.length;i+=10)e.push(t.slice(i,i+10));try{await Promise.all(e.map(t=>this.request(t)))}finally{t.forEach(t=>this.inflight.delete(t)),i.forEach(t=>t.resolve())}}async request(t){var i,e,s,n;const r=this.runtime.consent();if(null===r||this.destroyed)return;const h=this.generation,a="granted"===r,l=ai();t.forEach(t=>this.lastNetworkAt.set(this.rateKey(t),l));const u=this.currentUrl(),c={};for(const i of this.mounts)t.includes(i.key)&&i.shown.length&&(c[i.key]=i.shown.slice());const d=a?this.identity.getUserId():null,f=a?this.identity.getAnonymousId():null,p=Object.assign(Object.assign(Object.assign(Object.assign({},d?{userId:d}:{}),f?{anonymousId:f}:{}),a?{sessionId:this.session.getSessionId()}:{}),{deviceType:"web",locale:"undefined"!=typeof navigator?navigator.language:void 0,capabilities:this.capabilities(),trackingConsent:r,placements:t,shown:c,context:this.page?Object.assign(Object.assign({},this.page.current()),{screen:null}):{url:m(),screen:null}}),y="undefined"!=typeof AbortController?new AbortController:null,v=setTimeout(()=>null==y?void 0:y.abort(),null!==(i=this.runtime.requestTimeoutMs)&&void 0!==i?i:1e4),b=this.apiEndpoint+"/v1/in-app/placements";try{const i=await fetch(b,Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),a&&(null===(e=this.auth)||void 0===e?void 0:e.getSdkAuthHeaders(d,d?null:f))||{}),body:JSON.stringify(p)},y?{signal:y.signal}:{}));if(!i.ok)return null===(n=(s=this.runtime).noteStatus)||void 0===n||n.call(s,i.status,null),void this.logger.debug(`Placements request answered ${i.status}; keeping the cached placements`);const r=await i.json();if(h!==this.generation)return void this.logger.debug("Discarding a placements answer that predates an identity or consent change");if(!r||!1===r.success||!r.placements||"object"!=typeof r.placements)return;const l=ai(),c=[];for(const i of t){const t=r.placements[i]||{placementKey:i,items:[]},e=this.normalize(i,t),s=this.cache.get(i);this.cache.set(i,{placement:e,fetchedAt:l,url:u}),e.pageScoped?this.pageScopedKeys.add(i):this.pageScopedKeys.delete(i);for(const t of Array.from(this.dismissedLocally))t.startsWith(i+"\0")&&this.dismissedLocally.delete(t);s&&JSON.stringify(s.placement)===JSON.stringify(e)||c.push(i)}this.persistCache(),c.length&&this.applyChanged(c)}catch(t){const i="AbortError"===(null==t?void 0:t.name);this.logger.debug(i?"Placements request timed out":"Placements request failed",t)}finally{clearTimeout(v)}}capabilities(){const t=["placements","content.native","content.data"];return this.page&&t.push(c),this.runtime.allowHtml()&&t.push("content.html"),t}normalize(t,i){const e=Array.isArray(i.items)?i.items.filter(t=>t&&"string"==typeof t.id):[];return Object.assign({placementKey:t,emptyBehavior:"keep_space"===i.emptyBehavior?"keep_space":"collapse",maxItems:"number"==typeof i.maxItems&&i.maxItems>0?i.maxItems:1,ttlSeconds:"number"==typeof i.ttlSeconds&&i.ttlSeconds>0?i.ttlSeconds:300,isControl:!0===i.isControl,controlToken:i.controlToken||null,items:e},!0===i.pageScoped?{pageScoped:!0}:{})}applyChanged(t){for(const i of this.mounts)t.includes(i.key)&&(i.hostInView&&i.shown.length?i.pendingUpdate=!0:this.render(i));if(!this.listeners.size)return;const i={};t.forEach(t=>i[t]=this.toPlacement(t));for(const t of Array.from(this.listeners))try{t(i)}catch(t){this.logger.error("The onPlacementsUpdated callback threw; ignored:",t)}}handle(t,i){return`${t}\0${i.deliveryToken||i.id}`}visibleItems(t){const i=this.cache.get(t);if(!i)return[];const e=ai(),s=i.placement.maxItems||1;return(i.placement.items||[]).filter(i=>{if(i.expiresAt&&Date.parse(i.expiresAt)<=e)return!1;if(this.dismissedLocally.has(this.handle(t,i)))return!1;if((i.triggers||[]).filter(t=>"event"===t.type).length){const s=this.triggeredAt.get(this.handle(t,i)),n=i.placementTriggerWindowSeconds||1800;if(void 0===s||e-s>1e3*n)return!1}return!0}).slice(0,s)}toPlacement(t){const i=this.cache.get(t),e=(null==i?void 0:i.placement)||this.normalize(t,{placementKey:t,items:[]}),s=this.generation;return{placementKey:t,items:this.visibleItems(t).map(i=>this.toItem(t,i,s)),isControl:!0===e.isControl,emptyBehavior:e.emptyBehavior||"collapse",maxItems:e.maxItems||1,ttlSeconds:e.ttlSeconds||300,markDisplayed:()=>this.current(s)&&this.reportControl(t)}}current(t){return t===this.generation}toItem(t,i,e){var s,n,r;return{id:i.id,variantId:null!==(s=i.variantId)&&void 0!==s?s:null,kind:i.kind,data:Object.assign({},i.data||{}),content:null!==(n=i.content)&&void 0!==n?n:null,products:mi(i.products),priority:i.priority,expiresAt:null!==(r=i.expiresAt)&&void 0!==r?r:null,markDisplayed:()=>this.current(e)&&this.report(t,i,"displayed"),markClicked:s=>this.current(e)&&this.report(t,i,"clicked",s),markDismissed:()=>this.current(e)&&this.dismissItem(t,i)}}dismissItem(t,i){this.report(t,i,"dismissed"),this.dismissedLocally.add(this.handle(t,i));for(const i of this.mounts)i.key===t&&this.render(i)}report(t,i,e,s){if("granted"!==this.runtime.consent())return;const n=`${e}:${this.handle(t,i)}`;if("clicked"!==e){if(this.reported.has(n))return;this.reported.add(n)}"displayed"!==e&&this.report(t,i,"displayed");const r=(new Date).toISOString(),o=Gt(s),h=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({campaignId:i.id},i.variantId?{variantId:i.variantId}:{}),i.deliveryToken?{deliveryToken:i.deliveryToken}:{}),{placementKey:t}),this.subject()),{sessionId:this.session.getSessionId(),deviceType:"web"}),"displayed"===e?{action:"displayed",displayedAt:r}:{}),"clicked"===e?Object.assign({action:"clicked",clicked:!0,clickedAt:r},o?{elementId:o}:{}):{}),"dismissed"===e?{action:"dismissed",dismissedAt:r}:{});this.post("/v1/in-app/track",h)}reportControl(t){const i=this.cache.get(t);if(!(null==i?void 0:i.placement.isControl)||!i.placement.controlToken)return;if("granted"!==this.runtime.consent())return;const e="control:"+i.placement.controlToken;this.reported.has(e)||(this.reported.add(e),this.post("/v1/in-app/track",Object.assign(Object.assign({action:"control_viewed",controlToken:i.placement.controlToken,placementKey:t},this.subject()),{sessionId:this.session.getSessionId(),deviceType:"web",viewedAt:(new Date).toISOString()})))}subject(){const t=this.identity.getUserId();return Object.assign(Object.assign({},t?{userId:t}:{}),{anonymousId:this.identity.getAnonymousId()})}post(t,i){var e,s;const n="string"==typeof i.userId?i.userId:null;fetch(`${this.apiEndpoint}${t}`,{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(e=this.auth)||void 0===e?void 0:e.getSdkAuthHeaders(n,n?null:null!==(s=i.anonymousId)&&void 0!==s?s:null))||{}),body:JSON.stringify(i),keepalive:!0}).then(t=>{var i,e;t.ok||null===(e=(i=this.runtime).noteStatus)||void 0===e||e.call(i,t.status,null)}).catch(i=>this.logger.debug(`Placement report to ${t} failed`,i))}scanDocument(){if("undefined"==typeof document||"function"!=typeof document.querySelectorAll)return;for(const t of Array.from(this.mounts))!1===t.element.isConnected&&this.unmount(t);const t=new Set(Array.from(this.mounts).map(t=>t.element));document.querySelectorAll("[data-joryio-placement]").forEach(i=>{if(t.has(i))return;const e=i.getAttribute("data-joryio-placement");e&&this.insertPlacement(e,i)})}unmount(t){var i,e,s;this.mounts.delete(t),null===(i=t.hostObserver)||void 0===i||i.disconnect(),this.clearTrackers(t),this.clearDrawn(t),null===(s=(e=t.element).removeAttribute)||void 0===s||s.call(e,"data-joryio-placement-state")}clearTrackers(t){for(const i of t.trackers)i.cancel();t.trackers=[]}clearDrawn(t){var i;t.frameIds.forEach(t=>this.frames.delete(t)),t.frameIds=[],null===(i=t.wrapper)||void 0===i||i.remove(),t.wrapper=null,t.shown=[]}render(t){if(!this.mounts.has(t))return;t.pendingUpdate=!1,this.clearTrackers(t),this.clearDrawn(t);const i=this.toPlacement(t.key),e=this.cache.get(t.key),s=document.createElement("div");s.className="joryio-placement",s.setAttribute("data-joryio-placement-key",t.key);const n=[];for(const i of this.visibleItems(t.key)){const e=this.drawItem(t,i);e&&(s.appendChild(e),n.push(i),this.trackViewability(t,e,()=>this.report(t.key,i,"displayed")))}t.shown=n.map(t=>t.deliveryId||t.id),t.element.appendChild(s),t.wrapper=s;const r=n.length?"filled":i.isControl?"control":"empty";if(t.element.setAttribute("data-joryio-placement-state",r),n.length||(s.style.display="keep_space"===i.emptyBehavior?"":"none",i.isControl&&(null==e?void 0:e.placement.controlToken)&&this.trackViewability(t,t.element,()=>this.reportControl(t.key))),t.options.onRender)try{t.options.onRender(i,t.element)}catch(t){this.logger.error("The insertPlacement onRender callback threw; ignored:",t)}}drawItem(t,i){const e=i.content;let s=null;if("html"===(null==e?void 0:e.kind)){if(!this.runtime.allowHtml())return this.logger.warn(`Placement ${t.key}: HTML item skipped (allowHtmlJsInAppMessages is off)`),null;s=this.drawHtml(t,i,e)}else if("native"===(null==e?void 0:e.kind))s=this.drawNative(t,i,e);else if(e)return null;const n=!1===t.options.showProducts?[]:mi(i.products);if(!n.length)return s;const r=this.drawProducts(t,i,n);if(!s)return r;const o=document.createElement("div");return o.className="joryio-placement-item",o.setAttribute("data-joryio-item",i.id),o.appendChild(s),o.appendChild(r),o}drawProducts(t,i,e){const s=document.createElement("div");s.className="joryio-placement-products",s.setAttribute("data-joryio-item",i.id),s.style.cssText="display:flex;gap:8px;overflow-x:auto;box-sizing:border-box;";const n=+t.options.productCardWidth,r=Number.isFinite(n)&&n>0?n:160;for(const n of e){const e=document.createElement("div");e.className="joryio-placement-product",e.setAttribute("data-joryio-product",n.id),e.style.cssText=`flex:0 0 ${r}px;width:${r}px;box-sizing:border-box;`;const o=n.url?()=>this.buttonAction(t,i,{id:ni(n.id),action:"deep_link",url:n.url}):null,h=ci(n.imageUrl);if(h){const t=document.createElement("img");t.className="joryio-placement-product-image",t.src=h,t.alt=n.title||"",t.style.cssText="display:block;width:100%;aspect-ratio:1/1;object-fit:cover;",e.appendChild(t)}if(n.title){const t=document.createElement("div");t.className="joryio-placement-product-title",t.textContent=n.title,e.appendChild(t)}if(n.price){const t=document.createElement("div");if(t.className="joryio-placement-product-price",t.textContent=n.price,n.compareAtPrice){const i=document.createElement("s");i.className="joryio-placement-product-compare",i.textContent=n.compareAtPrice,i.style.cssText="margin-inline-start:6px;opacity:0.6;",t.appendChild(i)}e.appendChild(t)}if(o&&t.options.productButtonText){const i=document.createElement("button");i.type="button",i.className="joryio-placement-product-button",i.textContent=t.options.productButtonText,i.addEventListener("click",t=>{var i;null===(i=null==t?void 0:t.stopPropagation)||void 0===i||i.call(t),o()}),e.appendChild(i)}o&&(e.setAttribute("role","link"),e.tabIndex=0,e.style.cursor="pointer",e.addEventListener("click",o),e.addEventListener("keydown",t=>{"Enter"===(null==t?void 0:t.key)&&o()})),s.appendChild(e)}return s}drawNative(t,i,e){var s;const n=document.createElement("div");n.className="joryio-placement-card",n.setAttribute("data-joryio-item",i.id),n.style.cssText="position:relative;box-sizing:border-box;";const r=ci(e.imageUrl);if(r){const t=document.createElement("img");t.src=r,t.alt="",t.style.cssText="display:block;max-width:100%;height:auto;",n.appendChild(t)}if(e.title){const t=document.createElement("div");t.className="joryio-placement-title",t.textContent=e.title,n.appendChild(t)}if(e.body){const t=document.createElement("div");t.className="joryio-placement-body",t.textContent=e.body,n.appendChild(t)}if(null===(s=e.buttons)||void 0===s?void 0:s.length){const s=document.createElement("div");s.className="joryio-placement-buttons",e.buttons.forEach((e,n)=>{const r=document.createElement("button");r.type="button",r.className=0===n?"primary":"secondary",r.textContent=e.text,r.addEventListener("click",()=>this.buttonAction(t,i,e)),s.appendChild(r)}),n.appendChild(s)}if(!0===e.closeButton){const e=document.createElement("button");e.type="button",e.className="joryio-placement-close",e.setAttribute("aria-label","Close"),e.textContent="×",e.addEventListener("click",()=>this.dismissItem(t.key,i)),n.appendChild(e)}return n}buttonAction(t,i,e){var s,n;const r=t.key;if("request_push_permission"===e.action&&(null===(s=this.runtime.bridge)||void 0===s||s.requestPushPermission()),this.report(r,i,"clicked",e.id),"url"===e.action||"deep_link"===e.action){const s=ci(e.url),o={placementKey:r,itemId:i.id};if(s)this.openLink(s,o,()=>window.open(s,"_blank","noopener"));else if("deep_link"===e.action&&fi(e.url)&&(t.options.onDeepLink||(null===(n=this.links)||void 0===n?void 0:n.hasHandler))){const s=e.url.trim();this.openLink(s,o,()=>{if(t.options.onDeepLink)try{t.options.onDeepLink(s,this.toItem(r,i,this.generation))}catch(t){this.logger.error("The insertPlacement onDeepLink callback threw; ignored:",t)}})}return}"dismiss"!==e.action&&"close"!==e.action||this.dismissItem(r,i)}openLink(t,i,e){this.links?this.links.route(t,"placement",i,e):e()}drawHtml(t,i,e){const s="p"+ ++this.frameSeq,n=document.createElement("iframe");return n.className="joryio-placement-frame",n.setAttribute("data-joryio-item",i.id),n.setAttribute("sandbox","allow-scripts allow-same-origin allow-popups"),n.setAttribute("title","Placement"),n.style.cssText="display:block;width:100%;height:0;border:0;",n.srcdoc=ti(s,e.html||"",e.css||"","placement",oi),this.frames.set(s,{iframe:n,key:t.key,item:i}),t.frameIds.push(s),n}installBridge(){if("undefined"==typeof window)return;const t=t=>this.frames.get(t);window[oi]={__owner:this,setSize:(i,e,s)=>{const n=t(i);n&&Number.isFinite(s)&&s>0&&(n.iframe.style.height=Math.ceil(s)+"px")},logClick:(i,e)=>{const s=t(i);s&&ui()&&this.report(s.key,s.item,"clicked",e)},navigate:(i,e)=>{if(!t(i)||!ui())return;const s=ci(e),n=t(i);s&&n&&this.openLink(s,{placementKey:n.key,itemId:n.item.id},()=>window.open(s,"_blank","noopener"))},closeMessage:i=>{const e=t(i);e&&this.dismissItem(e.key,e.item)},logConversion:()=>{},logCustomEvent:(i,e,s)=>{var n;t(i)&&e&&(null===(n=this.runtime.bridge)||void 0===n||n.logCustomEvent(e,s))},setCustomUserAttribute:(i,e,s)=>{var n;t(i)&&e&&(null===(n=this.runtime.bridge)||void 0===n||n.setCustomUserAttribute(e,s))},changeUser:(i,e)=>{var s;t(i)&&e&&(null===(s=this.runtime.bridge)||void 0===s||s.changeUser(e))},requestPushPermission:i=>{var e;t(i)&&(null===(e=this.runtime.bridge)||void 0===e||e.requestPushPermission())},submitForm:()=>Promise.resolve({ok:!1,message:"Forms are not available in this spot."})}}pageVisible(){return"undefined"==typeof document||"hidden"!==document.visibilityState}observeHost(t){if("undefined"==typeof IntersectionObserver)return;const i=new IntersectionObserver(i=>{for(const e of i)t.hostInView=e.isIntersecting,!e.isIntersecting&&t.pendingUpdate&&this.render(t)});i.observe(t.element),t.hostObserver=i}trackViewability(t,i,e){let s=null;s=yi(i,()=>{s&&t.trackers.includes(s)&&e()}),t.trackers.push(s)}installPageVisibility(){"undefined"!=typeof document&&"function"==typeof document.addEventListener&&(this.pageListener=()=>{for(const t of this.mounts)for(const i of t.trackers)this.pageVisible()?i.resume():i.pause()},document.addEventListener("visibilitychange",this.pageListener))}subjectKey(){return`${this.identity.getUserId()||""}|${this.identity.getAnonymousId()}`}loadCache(){var t;try{if("undefined"==typeof sessionStorage)return;null===(t=sessionStorage.removeItem)||void 0===t||t.call(sessionStorage,"joryio_placements_v1");const i=sessionStorage.getItem(ri(this.sdkKey));if(!i)return;const e=JSON.parse(i);if(!e||e.subject!==this.subjectKey()||"object"!=typeof e.entries)return;for(const[t,i]of Object.entries(e.entries))li(t)&&i&&i.placement&&"number"==typeof i.fetchedAt&&this.cache.set(t,{placement:this.normalize(t,i.placement),fetchedAt:i.fetchedAt,url:"string"==typeof i.url?i.url:null})}catch(t){}}persistCache(){try{if("undefined"==typeof sessionStorage)return;const t={};this.cache.forEach((i,e)=>{t[e]=i}),sessionStorage.setItem(ri(this.sdkKey),JSON.stringify({subject:this.subjectKey(),entries:t}))}catch(t){}}}function mi(t){if(!Array.isArray(t))return[];const i=t=>"string"==typeof t?t:null;return t.filter(t=>!!t&&"object"==typeof t&&("string"==typeof t.id||"number"==typeof t.id)).map(t=>({id:t.id+"",title:i(t.title),price:i(t.price),compareAtPrice:i(t.compareAtPrice),discountPercent:"number"==typeof t.discountPercent?t.discountPercent:null,imageUrl:i(t.imageUrl),url:i(t.url)}))}const bi="joryio-cards-ui.min.js",gi=300,wi="viewed",ki="read",Si="clicked",ji="dismissed",Oi=t=>"joryio_cards_v1_"+e(t).toString(36),Ai=t=>"joryio_cards_device_v1_"+e(t).toString(36);function Ii(){const t="undefined"!=typeof window?window.__joryioCardsUi:null;return t&&1===t.version&&"function"==typeof t.mount?t:null}const _i=()=>Date.now(),Ti=t=>"string"==typeof t?t:null;function $i(t){if(!t||"object"!=typeof t)return null;const i=Ti(t.id),e=Ti(t.deliveryToken);return i&&e?{id:i,campaignId:Ti(t.campaignId)||"",variantId:Ti(t.variantId),title:Ti(t.title),body:Ti(t.body),imageUrl:Ti(t.imageUrl),buttonText:Ti(t.buttonText),url:Ti(t.url),pinned:!0===t.pinned,createdAt:Ti(t.createdAt)||"",expiresAt:Ti(t.expiresAt),read:!0===t.read,clicked:!0===t.clicked,deliveryToken:e}:null}function Di(t){return Array.isArray(t)?t.map($i).filter(Boolean):[]}function Ci(t,i,e){return{id:t.id,campaignId:t.campaignId,variantId:t.variantId,title:t.title,body:t.body,imageUrl:t.imageUrl,buttonText:t.buttonText,url:t.url,pinned:t.pinned,createdAt:t.createdAt,expiresAt:t.expiresAt,read:i,clicked:e}}class Pi{constructor(t,i,e,s,n,r,o){this.apiEndpoint=t,this.sdkKey=i,this.identity=e,this.session=s,this.logger=n,this.runtime=r,this.auth=o,this.links=null,this.wireCards=[],this.serverUnread=0,this.nextCursor=null,this.stateScope="server",this.etag=null,this.ttlSeconds=gi,this.fetchedAt=null,this.lastNetworkAt=null,this.inflight=null,this.deferredTimer=null,this.listeners=new Set,this.mounts=new Set,this.reported=new Set,this.overlayRead=new Set,this.overlayClicked=new Set,this.overlayDismissed=new Set,this.deviceRead=new Set,this.deviceDismissed=new Set,this.generation=0,this.destroyed=!1,this.cardsUi=null,this.cardsUiLoading=null,this.removeLegacyStorage(),this.loadFeedCache(),this.loadDeviceState()}async getCards(t={}){const i=t&&"string"==typeof t.cursor&&t.cursor?t.cursor:null;return i?this.loadPage(i):(this.fresh()||await this.fetch(!1),this.view())}getUnreadCardCount(){return this.view().unreadCount}async refreshCards(){await this.fetch(!0)}onCardsUpdated(t){if("function"!=typeof t)return ei(()=>{});const i=i=>t(i);return this.listeners.add(i),ei(()=>{this.listeners.delete(i)})}markCardViewed(t){this.report(t,wi)}markCardRead(t){this.report(t,ki)}markCardClicked(t){this.report(t,Si)}dismissCard(t){this.report(t,ji)}mountCardFeed(t,i={}){if(!t||"function"!=typeof t.appendChild)return this.logger.warn("mountCardFeed: an element is required"),null;if("undefined"==typeof document)return null;for(const i of this.mounts)i.element===t&&this.unmount(i);const e={element:t,options:i||{},view:null};return this.mounts.add(e),this.fresh()||this.fetch(!1).catch(()=>{}),this.cardsUi=this.cardsUi||Ii(),this.cardsUi?this.attach(e,this.cardsUi):this.loadCardsUi().then(i=>{this.mounts.has(e)&&(i?this.attach(e,i):t.setAttribute("data-joryio-card-feed-state","unavailable"))}),{element:t,remove:()=>this.unmount(e)}}invalidate(t){if(this.generation++,this.wireCards=[],this.serverUnread=0,this.nextCursor=null,this.stateScope="server",this.etag=null,this.ttlSeconds=gi,this.fetchedAt=null,this.lastNetworkAt=null,this.inflight=null,this.deferredTimer&&clearTimeout(this.deferredTimer),this.deferredTimer=null,this.reported.clear(),this.overlayRead.clear(),this.overlayClicked.clear(),this.overlayDismissed.clear(),t){this.deviceRead.clear(),this.deviceDismissed.clear();try{"undefined"!=typeof localStorage&&localStorage.removeItem(Ai(this.sdkKey))}catch(t){}}try{"undefined"!=typeof sessionStorage&&sessionStorage.removeItem(Oi(this.sdkKey))}catch(t){}const i=this.listeners.size>0||this.mounts.size>0;this.notify(),i&&!this.destroyed&&this.fetch(!0).catch(()=>{})}destroy(){this.destroyed=!0;for(const t of Array.from(this.mounts))this.unmount(t);this.deferredTimer&&clearTimeout(this.deferredTimer),this.deferredTimer=null,this.listeners.clear()}fresh(){return null!==this.fetchedAt&&_i()-this.fetchedAt<1e3*this.ttlSeconds}fetch(t){if(this.destroyed)return Promise.resolve();if(this.inflight)return t&&this.defer(),this.inflight;if(null!==this.lastNetworkAt&&3e4>_i()-this.lastNetworkAt)return t&&this.defer(),Promise.resolve();const i=this.requestFirstPage().finally(()=>{this.inflight===i&&(this.inflight=null)});return this.inflight=i,i}defer(){var t;if(this.deferredTimer)return;const i=Math.max(0,(null!==(t=this.lastNetworkAt)&&void 0!==t?t:0)+3e4-_i());this.deferredTimer=setTimeout(()=>{this.deferredTimer=null,this.destroyed||this.fetch(!1).catch(()=>{})},i+10)}async post(t){var i,e,s,n;const r=this.runtime.consent();if("granted"!==r||this.destroyed)return null;const h=this.generation;t||(this.lastNetworkAt=_i());const a=this.identity.getUserId(),l=this.identity.getAnonymousId(),u=Object.assign(Object.assign(Object.assign(Object.assign({},a?{userId:a}:{}),{anonymousId:l,sessionId:this.session.getSessionId(),deviceType:"web",locale:"undefined"!=typeof navigator?navigator.language:void 0,capabilities:["cards","content.native"],trackingConsent:r,limit:20}),t?{cursor:t}:{}),!t&&this.etag?{etag:this.etag}:{}),c="undefined"!=typeof AbortController?new AbortController:null,d=setTimeout(()=>null==c?void 0:c.abort(),null!==(i=this.runtime.requestTimeoutMs)&&void 0!==i?i:1e4);try{const t=await fetch(this.apiEndpoint+"/v1/in-app/cards",Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(e=this.auth)||void 0===e?void 0:e.getSdkAuthHeaders(a,a?null:l))||{}),body:JSON.stringify(u)},c?{signal:c.signal}:{}));if(!t.ok)return null===(n=(s=this.runtime).noteStatus)||void 0===n||n.call(s,t.status,null),this.logger.debug(`Card feed request answered ${t.status}; keeping the cached feed`),null;const i=await t.json();return h!==this.generation?(this.logger.debug("Discarding a card feed answer that predates an identity or consent change"),null):i&&"object"==typeof i&&!1!==i.success?{data:i,generation:h}:(this.logger.debug("Card feed answered success: false; keeping the cached feed"),null)}catch(t){const i="AbortError"===(null==t?void 0:t.name);return this.logger.debug(i?"Card feed request timed out":"Card feed request failed",t),null}finally{clearTimeout(d)}}async requestFirstPage(){const t=await this.post(null);if(!t||t.generation!==this.generation)return;const{data:i}=t,e=_i();this.ttlSeconds="number"==typeof i.ttlSeconds&&i.ttlSeconds>0?i.ttlSeconds:gi;let s=!1;if(!0===i.notModified&&null!==this.fetchedAt)this.fetchedAt=e;else{if(!0===i.notModified)return this.etag=null,this.lastNetworkAt=null,this.requestFirstPage();{const t=JSON.stringify(this.view());this.wireCards=Di(i.cards),this.serverUnread="number"==typeof i.unreadCount?Math.max(0,i.unreadCount):0,this.nextCursor=Ti(i.nextCursor),this.stateScope="device"===i.stateScope?"device":"server",this.etag=Ti(i.etag),this.fetchedAt=e,s=t!==JSON.stringify(this.view())}}this.persistFeed(),s&&this.notify()}async loadPage(t){const i=await this.post(t);if(!i||i.generation!==this.generation)return Object.assign(Object.assign({},this.view()),{cards:[]});const{data:e}=i,s=Di(e.cards),n=new Set(this.wireCards.map(t=>t.id));this.wireCards=this.wireCards.concat(s.filter(t=>!n.has(t.id))),this.nextCursor=Ti(e.nextCursor),"number"==typeof e.unreadCount&&(this.serverUnread=Math.max(0,e.unreadCount)),this.persistFeed();const r=this.view(),o=new Set(s.map(t=>t.id));return this.notify(),Object.assign(Object.assign({},r),{cards:r.cards.filter(t=>o.has(t.id))})}notify(){for(const t of this.mounts)this.render(t);if(!this.listeners.size)return;const t=this.view();for(const i of Array.from(this.listeners))try{i(t)}catch(t){this.logger.error("The onCardsUpdated callback threw; ignored:",t)}}key(t){return`${t.id}\0${t.createdAt}`}view(){const t=_i();let i=this.serverUnread;const e=[];for(const s of this.wireCards){const n=this.key(s),r=this.overlayDismissed.has(n)||this.deviceDismissed.has(s.id),o=s.expiresAt?Date.parse(s.expiresAt):NaN,h=Number.isFinite(o)&&t>=o,a=s.clicked||this.overlayClicked.has(n),l=s.read||a||this.overlayRead.has(n)||this.deviceRead.has(s.id);!s.read&&(l||r||h)&&i--,r||h||e.push(Ci(s,l,a))}return{cards:e,unreadCount:Math.max(0,i),nextCursor:this.nextCursor,stateScope:this.stateScope}}report(t,i){const e="string"==typeof t?t:null==t?void 0:t.id,s="string"==typeof t?null:null==t?void 0:t.createdAt,n=this.wireCards.find(t=>t.id===e&&(null==s||t.createdAt===s));if(!n)return void this.logger.debug(`Card report ignored: ${e+""} is not in the current feed`);const r=this.key(n),o=n.read||n.clicked||this.overlayRead.has(r)||this.overlayClicked.has(r)||this.deviceRead.has(n.id);if(i===ki&&o)return void this.reported.add(`${ki}:${n.id}`);const h=`${i}:${n.id}`;if(this.reported.has(h))return;this.reported.add(h);const a=[];i===wi||this.reported.has(`${wi}:${n.id}`)||(this.reported.add(`${wi}:${n.id}`),a.push(wi)),a.push(i);const l="device"===this.stateScope;if(i!==ki&&i!==Si||(this.overlayRead.add(r),l&&this.deviceRead.add(n.id)),i===Si&&(this.overlayClicked.add(r),this.reported.add(`${ki}:${n.id}`)),i===ji&&(this.overlayDismissed.add(r),l&&this.deviceDismissed.add(n.id)),l&&i!==wi&&this.persistDeviceState(),i!==wi&&this.notify(),"granted"!==this.runtime.consent())return;const u=this.session.getSessionId();for(const t of a)this.send({deliveryToken:n.deliveryToken,action:t,sessionId:u})}send(t){var i;const e=this.identity.getUserId();fetch(this.apiEndpoint+"/v1/in-app/track",{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(i=this.auth)||void 0===i?void 0:i.getSdkAuthHeaders(e,e?null:this.identity.getAnonymousId()))||{}),body:JSON.stringify(t),keepalive:!0}).then(t=>{var i,e;t.ok||null===(e=(i=this.runtime).noteStatus)||void 0===e||e.call(i,t.status,null)}).catch(t=>this.logger.debug("Card report failed",t))}loadCardsUi(){if(this.cardsUiLoading)return this.cardsUiLoading;const t=(async()=>{var t;let i=Ii();const e=null!==(t=this.runtime.loadScript)&&void 0!==t?t:t=>H(t,"data-joryio-cards-ui");for(const t of i?[]:L(bi,this.runtime.cardsUiScriptUrl))try{if(await e(t),i=Ii(),i)break}catch(t){this.logger.debug("Joryio card feed file failed to load",t)}return i||this.logger.warn(`mountCardFeed: ${bi} could not be loaded (Content-Security-Policy script-src?)`),this.cardsUi=i,i})().catch(()=>null);return this.cardsUiLoading=t,t.then(t=>{t||(this.cardsUiLoading=null)}),t}attach(t,i){try{t.view=i.mount(t.element,t.options,this.feedHost(t)),t.view.render()}catch(t){this.logger.error("The card feed could not be drawn:",t)}}feedHost(t){return{view:()=>this.view(),generation:()=>this.generation,markCardViewed:t=>this.markCardViewed(t),markCardRead:t=>this.markCardRead(t),markCardClicked:t=>this.markCardClicked(t),dismissCard:t=>this.dismissCard(t),routeLink:(i,e,s)=>{this.mounts.has(t)&&(this.links?this.links.route(i,"card",e,s):s())},loadMore:async()=>{const i=this.nextCursor;i&&this.mounts.has(t)&&this.wireCards.length&&await this.loadPage(i)},trackViewable:yi,logger:this.logger}}unmount(t){this.mounts.delete(t);const i=t.view;t.view=null;try{null==i||i.remove()}catch(t){this.logger.debug("Card feed remove failed",t)}}render(t){var i;try{null===(i=t.view)||void 0===i||i.render()}catch(t){this.logger.error("The card feed could not be drawn:",t)}}subjectKey(){return`${this.identity.getUserId()||""}|${this.identity.getAnonymousId()}`}removeLegacyStorage(){var t,i;try{"undefined"!=typeof sessionStorage&&(null===(t=sessionStorage.removeItem)||void 0===t||t.call(sessionStorage,"joryio_cards_v1"))}catch(t){}try{"undefined"!=typeof localStorage&&(null===(i=localStorage.removeItem)||void 0===i||i.call(localStorage,"joryio_cards_device_v1"))}catch(t){}}persistFeed(){try{if("undefined"==typeof sessionStorage)return;sessionStorage.setItem(Oi(this.sdkKey),JSON.stringify({subject:this.subjectKey(),fetchedAt:this.fetchedAt,etag:this.etag,ttlSeconds:this.ttlSeconds,unreadCount:this.serverUnread,nextCursor:this.nextCursor,stateScope:this.stateScope,cards:this.wireCards}))}catch(t){}}loadFeedCache(){try{if("undefined"==typeof sessionStorage)return;const t=sessionStorage.getItem(Oi(this.sdkKey));if(!t)return;const i=JSON.parse(t);if(!i||i.subject!==this.subjectKey())return;this.wireCards=Di(i.cards),this.serverUnread="number"==typeof i.unreadCount?Math.max(0,i.unreadCount):0,this.nextCursor=Ti(i.nextCursor),this.stateScope="device"===i.stateScope?"device":"server",this.etag=Ti(i.etag),this.ttlSeconds="number"==typeof i.ttlSeconds&&i.ttlSeconds>0?i.ttlSeconds:gi,this.fetchedAt="number"==typeof i.fetchedAt?i.fetchedAt:null}catch(t){this.wireCards=[]}}persistDeviceState(){const t=t=>{for(;t.size>500;)t.delete(t.values().next().value)};t(this.deviceRead),t(this.deviceDismissed);try{if("undefined"==typeof localStorage)return;localStorage.setItem(Ai(this.sdkKey),JSON.stringify({anonymousId:this.identity.getAnonymousId(),read:Array.from(this.deviceRead),dismissed:Array.from(this.deviceDismissed)}))}catch(t){}}loadDeviceState(){try{if("undefined"==typeof localStorage)return;const t=localStorage.getItem(Ai(this.sdkKey));if(!t)return;const i=JSON.parse(t);if(!i||i.anonymousId!==this.identity.getAnonymousId())return;for(const t of Array.isArray(i.read)?i.read:[])"string"==typeof t&&this.deviceRead.add(t);for(const t of Array.isArray(i.dismissed)?i.dismissed:[])"string"==typeof t&&this.deviceDismissed.add(t)}catch(t){this.deviceRead.clear(),this.deviceDismissed.clear()}}}class Mi{constructor(t=()=>{}){this.onHandlerError=t,this.handler=null}setHandler(t){this.handler="function"==typeof t?t:null}get hasHandler(){return null!==this.handler}route(t,i,e,s){if("string"!=typeof t)return!1;const n=t.trim(),r=fi(n);if(!ci(n)&&!r)return!1;let o=!1;const h=()=>{o||(o=!0,s())},a=Object.assign(Object.assign({url:n,source:i},function(t){const i={};for(const e of["campaignId","placementKey","itemId","cardId"]){const s=t[e];"string"==typeof s&&s&&(i[e]=s)}return i}(e)),{isAppDeepLink:r,openDefault:h}),l=this.handler;if(l){let t=!1;try{t=!0===l(a)}catch(t){this.onHandlerError(t)}if(t)return!0}return h(),!0}}const xi=t=>"jry_flags_"+e(t).toString(36),Ki=()=>Date.now();class Ni{constructor(t,i,e,s,n,r,o){this.apiEndpoint=t,this.sdkKey=i,this.identity=e,this.session=s,this.logger=n,this.runtime=r,this.auth=o,this.flags={},this.etag="",this.fetchedAt=0,this.generation=0,this.inflight=null,this.inflightGeneration=0,this.listeners=new Set,this.exposed=new Set,this.pending=null,this.flushTimer=null,this.used=!1,this.onVisible=()=>{"undefined"!=typeof document&&"visible"===document.visibilityState&&this.refresh(!1)},this.load()}start(){"undefined"!=typeof document&&document.addEventListener("visibilitychange",this.onVisible),this.used&&this.refresh(!0)}use(){this.used||(this.used=!0,this.refresh(!0))}destroy(){"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.onVisible),this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null,this.listeners.clear()}onIdentityChanged(){this.generation++,this.flush();const t=Object.keys(this.flags);this.flags={},this.etag="",this.fetchedAt=0,this.save(),t.length&&this.emit(t),this.used&&this.refresh(!0)}getFlag(t,i){const e=this.read(t);return e?e.value:i}getBoolFlag(t,i){const e=this.read(t,"boolean");return e&&"boolean"==typeof e.value?e.value:i}getStringFlag(t,i){const e=this.read(t,"string");return e&&"string"==typeof e.value?e.value:i}getNumberFlag(t,i){const e=this.read(t,"number");return e&&"number"==typeof e.value?e.value:i}getJsonFlag(t,i){const e=this.read(t,"json");return e?e.value:i}getAllFlags(){if(!this.runtime.canSend())return{};this.use();const t={};for(const[i,e]of Object.entries(this.flags))t[i]=e.value;return t}async refreshFlags(){this.used=!0,await this.refresh(!0)}onFlagsUpdated(t){if("function"!=typeof t)return ei(()=>{});const i=i=>t(i);return this.listeners.add(i),this.use(),ei(()=>{this.listeners.delete(i)})}read(t,i){if(!this.runtime.canSend())return null;this.use();const e=this.flags[t];return!e||i&&e.valueType!==i?null:(this.noteExposure(t,e),e)}noteExposure(t,i){if(!i.logExposure)return;const e=`${this.session.getSessionId()}|${this.subjectKey()}|${t}|${i.variant}`;this.exposed.has(e)||(this.exposed.add(e),this.pending&&this.pending.generation===this.generation||(this.pending&&this.flush(),this.pending={body:this.requestBody(),generation:this.generation,exposures:[]}),this.pending.exposures.push({key:t,variant:i.variant}),this.flushTimer||(this.flushTimer=setTimeout(()=>this.flush(),1e3)))}flush(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null;const t=this.pending;if(this.pending=null,!t||!t.exposures.length||!this.runtime.canSend())return;const i=Object.assign(Object.assign({},t.body),{exposures:t.exposures.slice(0,100)});this.post("/v1/flags/exposures",i,!0).catch(t=>this.logger.debug("Flag exposures failed",t))}subjectKey(){return`${this.identity.getUserId()||""}|${this.identity.getAnonymousId()}`}requestBody(){var t,i,e;const s=this.identity.getUserId();return Object.assign(Object.assign({},s?{userId:s}:{}),{anonymousId:this.identity.getAnonymousId(),sessionId:this.session.getSessionId(),attributes:null!==(e=null===(i=(t=this.runtime).attributes)||void 0===i?void 0:i.call(t))&&void 0!==e?e:{},context:{platform:"web",locale:"undefined"!=typeof navigator?navigator.language:void 0,url:"undefined"!=typeof location?location.href.split("?")[0]:void 0}})}async refresh(t){if(!this.runtime.canSend()||!this.used)return;if(this.inflight){const t=this.inflightGeneration!==this.generation;return await this.inflight,void(t&&await this.refresh(!0))}if(!t&&6e4>Ki()-this.fetchedAt)return;const i=this.generation;return this.inflightGeneration=i,this.inflight=(async()=>{try{const t=await this.post("/v1/flags/evaluate",Object.assign(Object.assign({},this.requestBody()),this.etag?{etag:this.etag}:{}),!1);if(!t)return;if(i!==this.generation)return;if(this.fetchedAt=Ki(),t.notModified)return void this.save();if(!t.flags||"object"!=typeof t.flags)return;const e=t.flags,s=Object.keys(Object.assign(Object.assign({},this.flags),e)).filter(t=>{var i,s,n,r;return JSON.stringify(null===(i=this.flags[t])||void 0===i?void 0:i.value)!==JSON.stringify(null===(s=e[t])||void 0===s?void 0:s.value)||(null===(n=this.flags[t])||void 0===n?void 0:n.variant)!==(null===(r=e[t])||void 0===r?void 0:r.variant)});this.flags=e,this.etag="string"==typeof t.etag?t.etag:"",this.save(),s.length&&this.emit(s)}catch(t){this.logger.debug("Flags refresh failed; keeping the held flags",t)}finally{this.inflight=null}})(),this.inflight}async post(t,i,e){var s,n,r,h,a;const l="undefined"!=typeof AbortController?new AbortController:null,u=setTimeout(()=>null==l?void 0:l.abort(),null!==(s=this.runtime.requestTimeoutMs)&&void 0!==s?s:1e4),c="string"==typeof i.userId?i.userId:null;try{const s=await fetch(`${this.apiEndpoint}${t}`,Object.assign(Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json","X-SDK-Key":this.sdkKey},o()),(null===(n=this.auth)||void 0===n?void 0:n.getSdkAuthHeaders(c,c?null:null!==(r=i.anonymousId)&&void 0!==r?r:null))||{}),body:JSON.stringify(i)},e?{keepalive:!0}:{}),l?{signal:l.signal}:{}));return s.ok?await s.json():(null===(a=(h=this.runtime).noteStatus)||void 0===a||a.call(h,s.status,null),null)}finally{clearTimeout(u)}}emit(t){for(const i of Array.from(this.listeners))try{i(t)}catch(t){this.logger.error("onFlagsUpdated callback failed",t)}}load(){try{if("undefined"==typeof localStorage)return;localStorage.removeItem("jry_flags");const t=localStorage.getItem(xi(this.sdkKey));if(!t)return;const i=JSON.parse(t);if(!i||i.subject!==this.subjectKey()||"object"!=typeof i.flags)return;this.flags=i.flags,this.etag=i.etag||"",this.used=!0,this.fetchedAt=0}catch(t){}}save(){try{if("undefined"==typeof localStorage)return;const t={subject:this.subjectKey(),etag:this.etag,fetchedAt:this.fetchedAt,flags:this.flags};localStorage.setItem(xi(this.sdkKey),JSON.stringify(t))}catch(t){}}}var Fi;t.SubscriptionStatus=void 0,(Fi=t.SubscriptionStatus||(t.SubscriptionStatus={})).OPTED_IN="optedIn",Fi.SUBSCRIBED="subscribed",Fi.UNSUBSCRIBED="unsubscribed";const Ei=["email","sms","whatsapp","push","viber"];class Ui{constructor(t,i,e,s,n){this.logger=t,this.network=i,this.identity=e,this.apiEndpoint=s,this.runWrite=n||((t,i)=>{this.sendOnce(i).then(i=>{i.ok||this.logger.error(`${t} failed (HTTP ${i.status||"no response"})`)},i=>this.logger.error(t+" failed:",i))})}sendOnce(t){return"subscription"===t.kind?this.network.sendSubscriptionUpdate(this.apiEndpoint,t.payload):"group"===t.kind?this.network.sendSubscriptionGroupUpdate(this.apiEndpoint,t.payload):Promise.resolve({ok:!1,status:0})}ids(){const t=this.identity.getUserId();return Object.assign(Object.assign({},t?{userId:t}:{}),{anonymousId:this.identity.getAnonymousId()})}setSubscription(i,e){if(!Ei.includes(i))return void this.logger.error(`Invalid channel: ${i}. Must be one of: ${Ei.join(", ")}`);const s=Object.values(t.SubscriptionStatus);if(!s.includes(e))return void this.logger.error(`Invalid status: ${e}. Must be one of: ${s.join(", ")}`);this.logger.debug(`Setting ${i} subscription status to ${e}`);const n=Object.assign({channel:i,status:e},this.ids());this.runWrite(`Update ${i} subscription`,{kind:"subscription",payload:n})}setSubscriptions(t){if(t&&"object"==typeof t)for(const[i,e]of Object.entries(t))void 0!==e&&this.setSubscription(i,e);else this.logger.error("setSubscriptions requires an object, e.g. { email: SubscriptionStatus.OPTED_IN }")}addToSubscriptionGroup(t,i="email"){this.updateGroup(t,i,"subscribe")}removeFromSubscriptionGroup(t,i="email"){this.updateGroup(t,i,"unsubscribe")}updateGroup(t,i,e){if("string"!=typeof t||!t)return void this.logger.error(`Cannot ${e} subscription group: groupId is required`);if(!Ei.includes(i))return void this.logger.error(`Invalid channel: ${i}. Must be one of: ${Ei.join(", ")}`);this.logger.debug(`${e} subscription group ${t} for channel ${i}`);const s=Object.assign({groupId:t,channel:i,action:e},this.ids());this.runWrite(`Subscription group ${t} ${e}`,{kind:"group",payload:s})}}const qi={error:0,warn:1,info:2,debug:3};class zi{constructor(t,i="error"){this.enabled=t,this.level=i}shouldLog(t){return this.enabled&&qi[t]<=qi[this.level]}error(...t){this.shouldLog("error")&&console.error("[Joryio SDK]",...t)}warn(...t){this.shouldLog("warn")&&console.warn("[Joryio SDK]",...t)}info(...t){this.shouldLog("info")&&console.info("[Joryio SDK]",...t)}debug(...t){this.shouldLog("debug")&&console.debug("[Joryio SDK]",...t)}setEnabled(t){this.enabled=t}setLevel(t){this.level=t}}const Ji=t=>t.includes("Edg/")?"Edge":t.includes("OPR/")?"Opera":t.includes("Chrome/")?"Chrome":t.includes("Safari/")&&!t.includes("Chrome/")?"Safari":t.includes("Firefox/")?"Firefox":t.includes("MSIE")||t.includes("Trident/")?"IE":"Unknown",Ri=t=>"string"==typeof t&&t.trim().length>0,Li=t=>"number"==typeof t&&Number.isFinite(t),Hi=t=>Li(t)?t:void 0;class Bi{constructor(t,i,e){this.sdk=t,this.config={currency:i&&"string"==typeof i.currency&&i.currency||"USD"},this.logger=e||new zi(!1)}guard(t,i,e){if(i)this.logger.warn(`ecommerce.${t}() not tracked: ${i}`);else try{e()}catch(i){this.logger.error(`ecommerce.${t}() failed:`,i)}}productProblem(t,i="product"){return t&&"object"==typeof t?Ri(t.productId)?Li(t.price)?null:i+".price must be a finite number":i+".productId is required":`a ${i} object is required`}itemsProblem(t){if(!Array.isArray(t))return"an items array is required";for(const i of t){if(null==i)continue;const t=this.productProblem(i,"item");if(t)return t}return null}cartProblem(t,i){var e;return null!==(e=this.itemsProblem(t))&&void 0!==e?e:Li(i)?null:"cartValue must be a finite number"}textProblem(t){for(const[i,e]of Object.entries(t))if(!Ri(e))return`a ${i} is required`;return null}amountsProblem(t){for(const[i,e]of Object.entries(t))if(null!=e&&!Li(e))return i+" must be a finite number";return null}validItems(t){return t.filter(t=>t&&"object"==typeof t)}itemCount(t){return t.reduce((t,i)=>t+(Li(i.quantity)?i.quantity:0),0)}viewProduct(t){this.guard("viewProduct",this.productProblem(t),()=>this.sdk.track("Product Viewed",{product_id:t.productId,name:t.name,price:t.price,category:t.category,brand:t.brand,variant:t.variant,variant_id:t.variantId,sku:t.sku,image_url:t.imageUrl,url:t.url,currency:this.config.currency}))}viewCategory(t,i,e){this.guard("viewCategory",this.textProblem({categoryId:t,categoryName:i}),()=>this.sdk.track("Product List Viewed",Object.assign({category_id:t,category_name:i},e&&"object"==typeof e?e:{})))}search(t,i,e){this.guard("search",this.textProblem({query:t}),()=>this.sdk.track("Products Searched",Object.assign({query:t,result_count:Hi(i)},e&&"object"==typeof e?e:{})))}addToCart(t,i){var e;const s=null!==(e=this.productProblem(t,"item"))&&void 0!==e?e:this.amountsProblem({cartValue:i});this.guard("addToCart",s,()=>this.sdk.track("Product Added",{product_id:t.productId,name:t.name,price:t.price,quantity:t.quantity,category:t.category,brand:t.brand,variant:t.variant,variant_id:t.variantId,sku:t.sku,image_url:t.imageUrl,url:t.url,item_total:Hi(t.price*t.quantity),cart_value:Hi(i),currency:this.config.currency}))}removeFromCart(t,i=1){this.guard("removeFromCart",this.productProblem(t,"item"),()=>this.sdk.track("Product Removed",{product_id:t.productId,name:t.name,price:t.price,quantity:Li(i)?i:1,variant_id:t.variantId,sku:t.sku,currency:this.config.currency}))}cartViewed(t,i){this.guard("cartViewed",this.cartProblem(t,i),()=>{const e=this.validItems(t);this.sdk.track("Cart Viewed",{items:e.map(t=>({product_id:t.productId,name:t.name,price:t.price,quantity:t.quantity,variant_id:t.variantId,sku:t.sku})),item_count:this.itemCount(e),cart_value:Hi(i),currency:this.config.currency})})}updateCart(t,i){this.guard("updateCart",this.cartProblem(t,i),()=>{const e=this.validItems(t);this.sdk.track("Cart Updated",{items:e.map(t=>({product_id:t.productId,name:t.name,price:t.price,quantity:t.quantity,variant_id:t.variantId,sku:t.sku})),item_count:this.itemCount(e),cart_value:Hi(i),currency:this.config.currency})})}startCheckout(t,i,e){this.guard("startCheckout",this.cartProblem(t,i),()=>{const s=this.validItems(t);this.sdk.track("Checkout Started",Object.assign({items:s.map(t=>({product_id:t.productId,name:t.name,price:t.price,quantity:t.quantity,variant_id:t.variantId,sku:t.sku})),item_count:this.itemCount(s),value:Hi(i),currency:this.config.currency},e&&"object"==typeof e?e:{}))})}addPaymentInfo(t,i){this.guard("addPaymentInfo",this.textProblem({paymentMethod:t}),()=>this.sdk.track("Payment Info Entered",Object.assign({payment_method:t},i&&"object"==typeof i?i:{})))}purchase(t){var i;const e=t&&"object"==typeof t?Ri(t.orderId)?Li(t.value)?null!==(i=this.itemsProblem(t.items))&&void 0!==i?i:this.amountsProblem({shipping:t.shipping,tax:t.tax,discount:t.discount}):"order.value must be a finite number":"order.orderId is required":"an order object is required";this.guard("purchase",e,()=>{const i=this.validItems(t.items);this.sdk.track("Order Completed",{orderId:t.orderId,items:i.map(t=>({product_id:t.productId,name:t.name,price:t.price,quantity:t.quantity,category:t.category,brand:t.brand,variant_id:t.variantId,sku:t.sku})),item_count:this.itemCount(i),total:t.value,currency:t.currency||this.config.currency,shipping:Hi(t.shipping),tax:Hi(t.tax),discount:Hi(t.discount),coupon:t.coupon})})}orderFulfilled(t,i,e){this.guard("orderFulfilled",Ri(t)?null:"an orderId is required",()=>this.sdk.track("Order Fulfilled",{order_id:t,tracking_number:i,carrier:e}))}orderDelivered(t){this.guard("orderDelivered",Ri(t)?null:"an orderId is required",()=>this.sdk.track("Order Delivered",{order_id:t}))}orderCancelled(t,i){this.guard("orderCancelled",Ri(t)?null:"an orderId is required",()=>this.sdk.track("Order Cancelled",{order_id:t,reason:i}))}orderRefunded(t,i,e){var s;const n=null!==(s=this.textProblem({orderId:t}))&&void 0!==s?s:this.amountsProblem({refundAmount:i});this.guard("orderRefunded",n,()=>this.sdk.track("Order Refunded",{order_id:t,refund_amount:Hi(i),reason:e}))}addToWishlist(t){this.guard("addToWishlist",this.productProblem(t),()=>this.sdk.track("Product Added to Wishlist",{product_id:t.productId,name:t.name,price:t.price,category:t.category,brand:t.brand,currency:this.config.currency}))}removeFromWishlist(t){this.guard("removeFromWishlist",this.productProblem(t),()=>this.sdk.track("Product Removed from Wishlist",{product_id:t.productId,name:t.name}))}shareProduct(t,i){var e;this.guard("shareProduct",null!==(e=this.productProblem(t))&&void 0!==e?e:this.textProblem({shareMethod:i}),()=>this.sdk.track("Product Shared",{product_id:t.productId,name:t.name,share_method:i}))}applyCoupon(t,i,e){var s;const n=null!==(s=this.textProblem({couponCode:t}))&&void 0!==s?s:this.amountsProblem({discountAmount:i});this.guard("applyCoupon",n,()=>this.sdk.track("Coupon Applied",{coupon_code:t,discount_amount:Hi(i),discount_type:e}))}removeCoupon(t){this.guard("removeCoupon",Ri(t)?null:"a couponCode is required",()=>this.sdk.track("Coupon Removed",{coupon_code:t}))}submitReview(t,i,e){const s=Ri(t)?Li(i)?null:"rating must be a finite number":"a productId is required";this.guard("submitReview",s,()=>this.sdk.track("Product Reviewed",{product_id:t,rating:i,review_text:e}))}}function Vi(t,i,e){return new Bi(t,i,e)}function Wi(t,i){var e={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&0>i.indexOf(s)&&(e[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(t);n<s.length;n++)0>i.indexOf(s[n])&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(e[s[n]]=t[s[n]])}return e}function Xi(t){switch(t.kind){case"subscription":return"unsubscribed"===t.payload.status;case"group":return"unsubscribe"===t.payload.action;case"marker":return!0===t.payload.value;default:return!1}}"function"==typeof SuppressedError&&SuppressedError;const Gi=[2e3,5e3,15e3,3e4,6e4,6e4,6e4,6e4,6e4],Qi=3e5;function Zi(t,i){const e=Gi[Math.min(Math.max(t,1),Gi.length)-1];return Math.min(Math.max(t>Gi.length?Math.min(e*Math.pow(2,t-Gi.length),Qi):e,null!=i?i:0),Qi)}function Yi(t,i){if(t.ok)return{action:"done"};if(t.softFailure)return{action:"retry",counts:!0};const e=t.status;return 0!==e&&408!==e&&429!==e&&500>e?404===e?{action:"retry",counts:!0,notFound:!0}:401===e?i.isSdkAuthError?i.ownerIsCurrentUser?{action:"retry",counts:!0}:{action:"drop",reason:"SDK authentication refused a write of a user who is no longer signed in (401)"}:{action:"hold",reason:"the SDK key was refused (401)"}:402===e?{action:"retry",counts:!1,retryAfterMs:t.retryAfterMs}:{action:"drop",reason:`refused by the server (HTTP ${e})`}:{action:"retry",counts:!1,retryAfterMs:t.retryAfterMs}}function te(t,i){return t>=10||i>=5}const ie="push_registration",ee="push_unregistered",se="push_in_use",ne="push_pending_unregister",re="joryio-sdk-state";class oe{constructor(t,i,e,s,n={}){this.logger=t,this.network=i,this.identity=e,this.apiEndpoint=s,this.vapidKeyCache=null,this.prepared=null,this.lastPrepareError=null,this.unregisterInFlight=!1,this.unregisterTimer=null,this.usedThisPage=!1,this.canSend=n.canSend||(()=>!0),this.canWithdraw=n.canWithdraw||(()=>!0),this.withdrawalUserId=n.withdrawalUserId||(()=>this.identity.getUserId()),this.storage=n.storage||null,this.getDeviceId=n.getDeviceId||(()=>{}),this.onSubscribeSettled=n.onSubscribeSettled||null,this.onPrepared=n.onPrepared||null}usedOnThisPage(){return this.usedThisPage}usedEarlier(){if(!this.storage)return!1;try{return!0===this.storage.get(se)||null!=this.storage.get(ie)||!0===this.storage.get(ee)}catch(t){return!1}}markUsed(){var t;this.usedThisPage=!0;try{null===(t=this.storage)||void 0===t||t.set(se,!0)}catch(t){}}isSupported(){return"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}getPermissionState(){if(!this.isSupported())return"unavailable";const t=Notification.permission;return"granted"===t||"denied"===t?t:"notDetermined"}async getExistingSubscription(t){if(!this.isSupported())return null;try{const i=await navigator.serviceWorker.getRegistration((null==t?void 0:t.scope)||"/");return i?await i.pushManager.getSubscription():null}catch(t){return this.logger.warn("Could not read the push subscription:",t),null}}async syncExistingSubscription(t=!1,i){var e,s;try{if(await this.sendPendingUnregister(),!this.canSend())return;if(!0===(null===(e=this.storage)||void 0===e?void 0:e.get(ee)))return;if(!this.isSupported()||"granted"!==Notification.permission)return;const n=await navigator.serviceWorker.getRegistration((null==i?void 0:i.scope)||"/");if(!n)return;let r=await n.pushManager.getSubscription();const o=null===(s=this.storage)||void 0===s?void 0:s.get(ie),h=this.identity.getUserId(),a=this.identity.getAnonymousId(),l=!o||Date.now()-(o.at||0)>864e5,u=!r||!o||o.endpoint!==r.endpoint||o.userId!==h||o.anonymousId!==a;if(!t&&!l&&!u)return;const c=await this.fetchVapidPublicKey();if(!c)return;r&&!this.subscriptionKeyMatches(r,c)&&(this.logger.info("VAPID key changed - re-subscribing this browser"),await r.unsubscribe().catch(()=>!1),r=null),r||(r=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:he(c)})),await this.registerWithBackend(r)}catch(t){this.logger.warn("Could not refresh the push subscription:",t)}}async setTrackingOptedOut(t){try{if("undefined"==typeof caches)return;if(t){const t=await caches.open(re);await t.put("/__joryio/tracking-opted-out",new Response("1"))}else await caches.delete(re)}catch(t){this.logger.debug("Could not record the opt-out for the service worker:",t)}}async prepare(t){var i;if(t=t||{},!this.isSupported())return this.lastPrepareError="unsupported",!1;if(this.prepared)return this.lastPrepareError=null,!0;const e=await this.fetchVapidPublicKey();if(!e)return this.lastPrepareError="no-key",this.logger.error("Web push is not enabled for this workspace"),!1;try{const s=await navigator.serviceWorker.register(t.swPath||"/joryio-sw.js",{scope:t.scope||"/"});await navigator.serviceWorker.ready,this.prepared={registration:s,publicKey:e},this.lastPrepareError=null,this.markUsed();try{null===(i=this.onPrepared)||void 0===i||i.call(this)}catch(t){this.logger.warn("Push permission report failed:",t)}return!0}catch(t){return this.lastPrepareError="sw-failed",this.logger.error("Service worker registration failed:",t),!1}}async subscribe(t){var i;try{return await this.subscribeOnce(t)}finally{this.markUsed();try{null===(i=this.onSubscribeSettled)||void 0===i||i.call(this)}catch(t){this.logger.warn("Push permission report failed:",t)}}}async subscribeOnce(t){var i;if(t=t||{},!this.isSupported())return console.warn("[Joryio SDK] Push not enabled: this browser/context does not support web push (needs HTTPS, a service worker, and PushManager - Safari < 16.4 and insecure origins are excluded)."),null;this.prepared||await this.prepare(t);const e=this.prepared;if(!e){this.logger.error("Web push is not enabled for this workspace");const i=t.swPath||"/joryio-sw.js";return"no-key"===this.lastPrepareError?console.warn("[Joryio SDK] Push not enabled: the server returned no VAPID key - web push is not configured for this app. Enable web push for THIS app (the one your SDK key belongs to) in the dashboard."):"sw-failed"===this.lastPrepareError?console.warn(`[Joryio SDK] Push not enabled: the service worker failed to register. The VAPID key was fetched OK, so the problem is ${i}: make sure it is hosted on your origin AND its importScripts() points at https://sdk.joryio.com/web/1/joryio-sw.js (a dead URL makes the worker's install throw and registration fail).`):console.warn("[Joryio SDK] Push not enabled: could not prepare web push."),null}null===(i=this.storage)||void 0===i||i.remove(ee);try{const t=await e.registration.pushManager.getSubscription();if(t&&this.subscriptionKeyMatches(t,e.publicKey))return await this.registerWithBackend(t).catch(t=>this.logRegisterFailure(t)),t;t&&(this.logger.info("VAPID key changed - re-subscribing this browser"),await t.unsubscribe().catch(()=>{}));const i=await e.registration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:he(e.publicKey)});return await this.sendPendingUnregister(),await this.registerWithBackend(i).catch(t=>this.logRegisterFailure(t)),this.logger.info("Web push subscribed"),i}catch(t){return"NotAllowedError"===(null==t?void 0:t.name)?(this.logger.info("User denied push permission"),console.warn("[Joryio SDK] Push not enabled: notification permission is denied. The browser will not re-prompt - the user must re-allow notifications for this site in browser settings.")):(this.logger.error("pushManager.subscribe failed:",t),console.warn("[Joryio SDK] Push not enabled: pushManager.subscribe failed:",t)),null}}async unsubscribe(t){var i,e;const s={userId:this.withdrawalUserId()||void 0,anonymousId:this.identity.getAnonymousId()};try{if(null===(i=this.storage)||void 0===i||i.set(ee,!0),null===(e=this.storage)||void 0===e||e.remove(ie),!this.isSupported())return!1;const n=await navigator.serviceWorker.getRegistration((null==t?void 0:t.scope)||"/");if(!n)return!1;const r=await n.pushManager.getSubscription();if(!r)return!0;const o=r.endpoint,h=await r.unsubscribe().catch(()=>!1),a=this.pendingUnregisters().filter(t=>t.endpoint!==o);return a.push(Object.assign({endpoint:o},s)),this.storePendingUnregisters(a),await this.sendPendingUnregister(),h}catch(t){return this.logger.warn("Push unsubscribe failed:",t),!1}}async forget(){await this.unsubscribe(),this.prepared=null}pendingUnregisterUsers(){return this.pendingUnregisters().map(t=>t.userId).filter(t=>"string"==typeof t&&!!t)}pendingUnregisters(){var t;const i=null===(t=this.storage)||void 0===t?void 0:t.get(ne);return(Array.isArray(i)?i:i?[i]:[]).filter(t=>t&&"string"==typeof t.endpoint&&t.endpoint&&"string"==typeof t.anonymousId)}storePendingUnregisters(t){var i,e;t.length?null===(i=this.storage)||void 0===i||i.set(ne,t.slice(-20)):null===(e=this.storage)||void 0===e||e.remove(ne)}retryPendingUnregister(){this.sendPendingUnregister().catch(()=>{})}async sendPendingUnregister(){if(!this.unregisterInFlight&&this.canWithdraw()&&("undefined"==typeof navigator||!1!==navigator.onLine)){null!==this.unregisterTimer&&(clearTimeout(this.unregisterTimer),this.unregisterTimer=null),this.unregisterInFlight=!0;try{for(;;){const[t]=this.pendingUnregisters();if(!t)return;const{attempts:i=0,notFoundAttempts:e=0,failures:s=0}=t,n=Wi(t,["attempts","notFoundAttempts","failures"]),r=await this.network.request({url:this.apiEndpoint+"/v1/push/unregister",method:"POST",body:Object.assign({platform:"web"},n),subjectUserId:n.userId||null}),o=Yi(r,{isSdkAuthError:this.network.isSdkAuthError(r.status,r.data),ownerIsCurrentUser:(n.userId||null)===this.withdrawalUserId()}),h=this.pendingUnregisters().filter(i=>i.endpoint!==t.endpoint);if("done"===o.action||"drop"===o.action){"drop"===o.action&&this.logger.error("Push unregister dropped: "+o.reason),this.storePendingUnregisters(h);continue}if("hold"===o.action)return;const a=Object.assign(Object.assign({},t),{failures:s+1,attempts:i+(o.counts&&!o.notFound?1:0),notFoundAttempts:e+(o.counts&&o.notFound?1:0)});if(!te(a.attempts,a.notFoundAttempts))return this.storePendingUnregisters([a,...h]),void(this.unregisterTimer=setTimeout(()=>{this.unregisterTimer=null,this.sendPendingUnregister().catch(()=>{})},Zi(a.failures,o.retryAfterMs)));this.logger.error("Push unregister failed too many times; dropping it"),this.storePendingUnregisters(h)}}catch(t){this.logger.warn("Failed to notify backend about unsubscribe:",t)}finally{this.unregisterInFlight=!1}}}destroy(){null!==this.unregisterTimer&&clearTimeout(this.unregisterTimer),this.unregisterTimer=null}logRegisterFailure(t){this.logger.warn("This browser is subscribed, but registering it with Joryio failed; it is retried on the next page load:",t)}subscriptionKeyMatches(t,i){var e;try{const s=null===(e=t.options)||void 0===e?void 0:e.applicationServerKey;if(!s)return!0;const n=new Uint8Array(s),r=he(i);if(n.byteLength!==r.byteLength)return!1;for(let t=0;t<n.byteLength;t++)if(n[t]!==r[t])return!1;return!0}catch(t){return!0}}async fetchVapidPublicKey(){var t,i;if(this.vapidKeyCache)return this.vapidKeyCache;try{const e=await this.network.request({url:this.apiEndpoint+"/v1/push/vapid-public-key",method:"GET"});return e.ok&&(null===(t=e.data)||void 0===t?void 0:t.enabled)&&(null===(i=e.data)||void 0===i?void 0:i.publicKey)?(this.vapidKeyCache=e.data.publicKey,this.vapidKeyCache):null}catch(t){return this.logger.error("Failed to fetch VAPID public key:",t),null}}async registerWithBackend(t){var i,e,s,n;if(!this.canSend())return void this.logger.debug("Push subscription not registered: tracking is off or consent is pending");const r=t.toJSON(),o=this.getDeviceId(),h=Object.assign({platform:"web",subscription:{endpoint:t.endpoint,keys:{p256dh:(null===(i=r.keys)||void 0===i?void 0:i.p256dh)||"",auth:(null===(e=r.keys)||void 0===e?void 0:e.auth)||""}},userId:this.identity.getUserId()||void 0,anonymousId:this.identity.getAnonymousId()},o?{deviceId:o}:{}),a=this.pendingUnregisters();a.some(i=>i.endpoint===t.endpoint)&&this.storePendingUnregisters(a.filter(i=>i.endpoint!==t.endpoint));const l=await this.network.request({url:this.apiEndpoint+"/v1/push/register",method:"POST",body:h,subjectUserId:h.userId||null});if(!l.ok)throw Error("Failed to register subscription: "+(l.error||l.status));null===(s=this.storage)||void 0===s||s.set(ie,{endpoint:t.endpoint,userId:null!==(n=h.userId)&&void 0!==n?n:null,anonymousId:h.anonymousId,at:Date.now()})}}function he(t){const i=(t+"=".repeat((4-t.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),e=atob(i),s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s}const ae="write_outbox",le="deferred_writes",ue="write_outbox_removed";function ce(t){const i=t.payload;return Object.assign({anonymousId:i.anonymousId},i.userId?{userId:i.userId}:{})}function de(t){switch(t.kind){case"subscription":return"subscription:"+t.payload.channel;case"group":return`group:${t.payload.groupId}:${t.payload.channel}`;case"marker":return"marker";default:return null}}function fe(t){switch(t.kind){case"alias":return"addAlias";case"subscription":return`Update ${t.payload.channel} subscription`;case"group":return`Subscription group ${t.payload.groupId} ${t.payload.action}`;case"marker":return"The tracking_opted_out marker"}}function pe(){return"undefined"!=typeof navigator&&!1===navigator.onLine}function ye(t){return!(!t||"object"!=typeof t||"alias"!==t.kind&&"subscription"!==t.kind&&"group"!==t.kind&&"marker"!==t.kind||!t.payload||"object"!=typeof t.payload||"string"!=typeof t.payload.anonymousId)}function ve(t){if(!t||!ye(t.record))return null;const i=t=>Number.isInteger(t)&&t>=0?t:0;return{id:"string"==typeof t.id?t.id:Q(),record:t.record,withdrawal:Xi(t.record),attempts:i(t.attempts),notFoundAttempts:i(t.notFoundAttempts),failures:i(t.failures),notBefore:0,createdAt:"number"==typeof t.createdAt&&Number.isFinite(t.createdAt)?t.createdAt:0}}class me{constructor(t){this.deps=t,this.entries=[],this.inFlight=null,this.timer=null,this.stopped=!1,this.handedOffAt=new Map,this.destroyed=!1,this.knownIds=new Set,this.load()}enqueue(t){if(this.destroyed)return;const i={id:Q(),record:t,withdrawal:Xi(t),attempts:0,notFoundAttempts:0,failures:0,notBefore:0,createdAt:Date.now()};this.knownIds.add(i.id);const e=de(t);e&&(this.entries=this.entries.filter(i=>i===this.inFlight||de(i.record)!==e||!this.sameOwner(i.record,t))),this.entries.push(i),this.trim(),this.persist(),this.kick()}discardNonWithdrawals(){this.entries=this.entries.filter(t=>t.withdrawal),this.persist({discardNonWithdrawals:!0})}persistNow(){this.persist()}find(t){return this.entries.find(t)}findLast(t){for(let i=this.entries.length-1;i>=0;i--)if(t(this.entries[i]))return this.entries[i]}cancel(t){const i=this.entries.length;this.entries=this.entries.filter(i=>i===this.inFlight||!t(i)),this.entries.length!==i&&this.persist()}pinOwner(t,i){let e=!1;for(const s of this.entries){const n=s.record.payload;n.anonymousId!==t||n.userId||(s.record=Object.assign(Object.assign({},s.record),{payload:Object.assign(Object.assign({},n),{userId:i})}),e=!0)}e&&this.persist()}isInFlight(t){return this.inFlight===t}size(){return this.entries.length}records(){return this.entries.map(t=>t.record)}kick(){if(this.destroyed||this.stopped||this.inFlight)return;if(null!==this.timer&&(clearTimeout(this.timer),this.timer=null),pe())return;const t=Date.now(),i=new Set;let e=1/0,s=null;for(const n of[...this.entries]){const r=this.blockKey(n);if(i.has(r))continue;const o=this.safeGate(n);if("drop"!==o)if("hold"!==o){if(n.notBefore<=t){s=n;break}i.add(r),e=Math.min(e,n.notBefore)}else i.add(r);else this.remove(n)}s?this.run(s):1/0>e&&(this.timer=setTimeout(()=>{this.timer=null,this.kick()},Math.max(0,e-t)))}handOffAtUnload(t){let i=0;if(!this.deps.keepalive||this.destroyed||this.stopped||pe())return i;this.persist();const e=Date.now(),s=new Set;this.inFlight&&s.add(this.blockKey(this.inFlight));for(const n of[...this.entries]){const r=this.blockKey(n);if(s.has(r))continue;if(n!==this.inFlight&&this.removedElsewhere(n)){this.deps.logger.debug(fe(n.record)+" not handed off: another tab settled or replaced it");const t=this.entries.indexOf(n);0>t||this.entries.splice(t,1);continue}if(s.add(r),n===this.inFlight||"send"!==this.safeGate(n))continue;const o=this.handedOffAt.get(n.id);if(void 0===o||e-o>=1e4)try{const s=this.deps.keepalive(n,this.deps.resolveOwner(ce(n.record)));if(null===s)break;if(this.handedOffAt.set(n.id,e),i+=s,i>=t)break}catch(t){break}}return this.persist(),i}destroy(){this.destroyed=!0,null!==this.timer&&clearTimeout(this.timer),this.timer=null}async run(t){this.inFlight=t;const i=fe(t.record);try{if(await this.deps.beforeSend(t).catch(()=>{}),!this.entries.includes(t))return;const e=this.safeGate(t);if("drop"===e)return void this.remove(t);if("hold"===e)return;if(this.removedElsewhere(t))return this.deps.logger.debug(i+" not sent: another tab settled or replaced it"),void this.remove(t);const s=this.deps.resolveOwner(ce(t.record)),n=await this.deps.send(t,s);if(!this.entries.includes(t))return;const r=Yi(n,{isSdkAuthError:this.deps.isSdkAuthError(n.status,n.data),ownerIsCurrentUser:this.deps.ownerIsCurrentUser(s)});switch(r.action){case"done":return void this.settle(t,"done");case"drop":return this.deps.logger.error(`${i} dropped: ${r.reason}`),void this.settle(t,"drop");case"hold":return this.deps.logger.error(`${i} not sent: ${r.reason}; kept for the next page view`),void(this.stopped=!0);case"retry":return this.hasNewerOfSameSubject(t)?void this.remove(t):(t.failures++,r.counts&&(r.notFound?t.notFoundAttempts++:t.attempts++),te(t.attempts,t.notFoundAttempts)?(this.deps.logger.error(`${i} failed (HTTP ${n.status||"no response"}) too many times; dropping it`),void this.settle(t,"drop")):(t.notBefore=Date.now()+Zi(t.failures,r.retryAfterMs),void this.deps.logger.debug(`${i} failed with HTTP ${n.status||"no response"}; retrying`)))}}catch(e){this.deps.logger.error(i+" failed:",e),t.failures++,t.notBefore=Date.now()+Zi(t.failures)}finally{this.inFlight===t&&(this.inFlight=null),this.persist(),this.kick()}}safeGate(t){try{return this.deps.gate(t)}catch(t){return"hold"}}settle(t,i){var e,s;this.remove(t);try{null===(s=(e=this.deps).onSettled)||void 0===s||s.call(e,t,i)}catch(t){this.deps.logger.error("Outbox bookkeeping failed:",t)}}remove(t){const i=this.entries.indexOf(t);0>i||(this.entries.splice(i,1),this.persist())}hasNewerOfSameSubject(t){const i=de(t.record);if(!i)return!1;const e=this.entries.indexOf(t);return this.entries.slice(e+1).some(e=>de(e.record)===i&&this.sameOwner(e.record,t.record))}effectiveUser(t){if(t.userId)return t.userId;const i=this.deps.currentIdentity();return t.anonymousId===i.anonymousId?i.userId:null}sameOwner(t,i){const e=ce(t),s=ce(i);return e.anonymousId===s.anonymousId&&this.effectiveUser(e)===this.effectiveUser(s)}blockKey(t){var i;const e=ce(t.record);return`${null!==(i=de(t.record))&&void 0!==i?i:`${t.record.kind}:${t.id}`}|${e.anonymousId}`}trim(){for(;this.entries.length>200;){let t=this.entries.findIndex(t=>!t.withdrawal&&t!==this.inFlight);if(0>t&&(t=this.entries.findIndex(t=>t!==this.inFlight)),0>t)break;const[i]=this.entries.splice(t,1);this.deps.logger.warn(`Too many profile writes waiting; dropped the oldest (${fe(i.record)})`)}}persist(t={}){try{const i=this.deps.storage.get(ae),e=Array.isArray(i)?i.filter(t=>t&&"string"==typeof t.id).map(t=>t.id):[],s=this.readRemoved();this.entries=this.entries.filter(t=>t===this.inFlight||!s.has(t.id));let n=this.foreignStoredEntries(i).filter(t=>!s.has(t.id));t.discardNonWithdrawals&&(n=n.filter(t=>t.withdrawal));let r=this.entries;if(n.length){const t=[...this.entries,...n].sort((t,i)=>t.createdAt-i.createdAt),i=(i,e)=>{const s=de(i.record);return!!s&&i!==this.inFlight&&t.slice(e+1).some(t=>de(t.record)===s&&this.sameOwner(t.record,i.record))};for(r=t.filter((t,e)=>!i(t,e));r.length>200;){let t=r.findIndex(t=>!t.withdrawal&&t!==this.inFlight);if(0>t&&(t=r.findIndex(t=>t!==this.inFlight)),0>t)break;this.deps.logger.warn(`Too many profile writes waiting; dropped the oldest (${fe(r[t].record)})`),r=r.filter((i,e)=>e!==t)}this.entries=this.entries.filter(t=>t===this.inFlight||r.includes(t))}const o=r.filter(t=>!s.has(t.id));this.write(o);const h=new Set(o.map(t=>t.id)),a=e.filter(t=>!h.has(t)&&!s.has(t));a.length&&this.writeRemoved(s,a)}catch(t){this.deps.logger.error("Failed to store pending profile writes:",t)}}removedElsewhere(t){try{if(this.readRemoved().has(t.id))return!0;const i=de(t.record);if(!i)return!1;const e=this.deps.storage.get(ae);return!!Array.isArray(e)&&e.some(e=>e&&e.id!==t.id&&ye(e.record)&&"number"==typeof e.createdAt&&e.createdAt>t.createdAt&&de(e.record)===i&&this.sameOwner(e.record,t.record))}catch(t){return!1}}readRemoved(){const t=new Map,i=this.deps.storage.get(ue);if(!Array.isArray(i))return t;const e=Date.now();for(const s of i)Array.isArray(s)&&"string"==typeof s[0]&&"number"==typeof s[1]&&(e-s[1]>2592e6||t.set(s[0],s[1]));return t}writeRemoved(t,i){const e=Date.now(),s=[...t.entries(),...i.map(t=>[t,e])];this.deps.storage.set(ue,s.slice(-500))}write(t){t.length?this.deps.storage.set(ae,t.map(t=>({id:t.id,record:t.record,attempts:t.attempts,notFoundAttempts:t.notFoundAttempts,failures:t.failures,createdAt:t.createdAt}))):this.deps.storage.remove(ae)}foreignStoredEntries(t){if(!Array.isArray(t))return[];const i=[];for(const e of t){if(!e||"string"!=typeof e.id||this.knownIds.has(e.id)||!ye(e.record))continue;const t=ve(e);t&&i.push(t)}return i}load(){const t=this.deps.storage.get(ae);if(Array.isArray(t))for(const i of t){const t=ve(i);t&&(this.entries.push(t),this.knownIds.add(t.id))}const i=this.deps.storage.get(le);if(Array.isArray(i)){for(const t of i){if(!ye(t))continue;const i={id:Q(),record:t,withdrawal:Xi(t),attempts:0,notFoundAttempts:0,failures:0,notBefore:0,createdAt:0};this.entries.push(i),this.knownIds.add(i.id)}this.deps.storage.remove(le),this.trim(),this.persist()}else this.entries.length>200&&(this.trim(),this.persist())}}function be(t){const i=[],e=(t,s)=>{switch(typeof t){case"number":return Number.isFinite(t)?null:"a non-finite number (NaN or Infinity)";case"bigint":return"a BigInt";case"function":return"a function";case"symbol":return"a symbol";case"object":if(null===t)return null;if(s>100)return"a value nested deeper than 100 levels";if("function"==typeof t.toJSON)try{return JSON.stringify(t),null}catch(t){return"a value that cannot be serialized"}if(i.includes(t))return"a circular reference";i.push(t);try{const i=Array.isArray(t)?t:Object.values(t);for(const t of i){const i=e(t,s+1);if(i)return i}}finally{i.pop()}return null;default:return null}};try{return e(t,1)}catch(t){return"a value that cannot be serialized"}}function ge(t,i){const e={};for(const s of Object.keys(t)){const n=be(t[s]);n?i(s,n):e[s]=t[s]}return e}const we=/^[A-Za-z0-9._:-]{8,255}$/,ke=/^[0-9a-f]{24}$/,Se="signed_in_anonymous_ids",je="jr_t",Oe=/^[A-Za-z0-9_-]{16,512}$/;function Ae(t){if("string"!=typeof t||!t.includes(je+"="))return null;try{const i="undefined"!=typeof window&&window.location?window.location.href:"https://x.invalid/",e=new URL(t,i).searchParams.get(je);return e&&Oe.test(e)?e:null}catch(t){return null}}function Ie(t){try{const i=new URL(t);return i.searchParams.has(je)?(i.searchParams.delete(je),i.toString()):null}catch(t){return null}}const _e="tracking_opted_out",Te="tracking_consent",$e="tracking_consent_granted_at",De="tracking_consent_denied_at",Ce="tracking_opted_out_at",Pe="tracking_opt_in_at",Me="reported_tracking_opted_out",xe="tracking_opted_out_marker_given_up",Ke="session_start_sent",Ne="withdrawal_user_id",Fe="retired_sdk_auth_tokens",Ee=[$t,Dt,Ct,ae,ne,"held_attribute_writes"];function Ue(t,i,e=0){if(t&&"object"==typeof t&&6>=e)if(Array.isArray(t))for(const s of t)Ue(s,i,e+1);else for(const[s,n]of Object.entries(t))"userId"===s&&"string"==typeof n&&n?i.add(n):Ue(n,i,e+1)}const qe=new WeakMap;function ze(t,i,e){const s=t,n=s.dataGate;s.dataGate=new Set([...n,...i]);try{e()}finally{s.dataGate=n}}const Je="anonymous_id",Re="user_id",Le=["jry_sdk_ios_","jry_sdk_android_"],He="tracking_opted_out",Be="held_attribute_writes",Ve="joryio_reported_push_permission",We="push_permission";class Xe{constructor(t,i){if(this.attributeFlushTimer=null,this.attributeFlushInFlight=!1,this.attributeFlushAgain=!1,this.attributeGeneration=0,this.attributeFailures=0,this.links=new Mi(t=>{var i;return null===(i=this.logger)||void 0===i?void 0:i.error("Your link handler threw; the link opens as without one:",t)}),this.editor=null,this.t=null,this.isInitialized=!1,this.isOptedOut=!1,this.disabled=!1,this.consentPending=!1,this.userOptedOut=!1,this.dntEnabled=!1,this.trackingConsent="granted",this.lastTrackedUrl=null,this.boundHandlePageUnload=null,this.boundHandleOnline=null,this.boundHandleStorage=null,this.withdrawalUserId=null,this.optedOutAt=0,this.consentDeniedAt=0,this.lastDecisionStamp=0,this.awaitingSessionOf=null,this.pruneTimer=null,this.pendingLinkToken=null,this.sentLinkTokens=new Set,this.dataGate=new Set,this.inflightSessionStartAtClear=null,Xe.instance)return console.warn("[Joryio] SDK already initialized. Returning existing instance."),Xe.instance;const e=t&&"object"==typeof t&&"string"==typeof t.sdkKey&&t.sdkKey?t.sdkKey.startsWith("jry_sdk_")?Le.some(i=>t.sdkKey.startsWith(i))?"this is a mobile app key - use the web SDK key (jry_sdk_web_...) from Settings -> Apps":null:"invalid SDK key format, expected jry_sdk_*":"sdkKey is required";e&&(console.error(`[Joryio] SDK not started: ${e}. Calls on this instance are ignored.`),this.disabled=!0),this.config=function(t){var i,e,s,n,r,o,l,u,c,d,f,p,y,v,m,b,g,w,k,S,j;!function(t){const i=t;for(const[t,e]of Object.entries(a))void 0!==i[t]&&console.warn(`[Joryio] \`${t}\` must be nested under \`${e}\`, not passed at the top level - as written it is IGNORED. Use: { ${e}: { ${t}: ${JSON.stringify(i[t])} } }`);void 0!==i.disablePlugins&&console.warn("[Joryio] `disablePlugins` was removed in 1.3.0 and is ignored - leave a plugin out of `plugins` instead.")}(t);const O={enabled:!1!==(null===(i=t.inApp)||void 0===i?void 0:i.enabled),evaluationMode:"session-start-only"===(null===(e=t.inApp)||void 0===e?void 0:e.evaluationMode)?"session-start-only":"differential-sync",syncInterval:(null===(s=t.inApp)||void 0===s?void 0:s.syncInterval)&&t.inApp.syncInterval>0?Math.max(3e4,t.inApp.syncInterval):0,displayOptions:{defaultPosition:(null===(r=null===(n=t.inApp)||void 0===n?void 0:n.displayOptions)||void 0===r?void 0:r.defaultPosition)||"center",defaultAnimation:(null===(l=null===(o=t.inApp)||void 0===o?void 0:o.displayOptions)||void 0===l?void 0:l.defaultAnimation)||"fade",backdropColor:(null===(c=null===(u=t.inApp)||void 0===u?void 0:u.displayOptions)||void 0===c?void 0:c.backdropColor)||"rgba(0, 0, 0, 0.5)",closeButtonColor:(null===(f=null===(d=t.inApp)||void 0===d?void 0:d.displayOptions)||void 0===f?void 0:f.closeButtonColor)||void 0,zIndex:(null===(y=null===(p=t.inApp)||void 0===p?void 0:p.displayOptions)||void 0===y?void 0:y.zIndex)||999999},allowHtmlJsInAppMessages:!0===(null===(v=t.inApp)||void 0===v?void 0:v.allowHtmlJsInAppMessages),autoMountPlacements:!1!==(null===(m=t.inApp)||void 0===m?void 0:m.autoMountPlacements),onMessageDisplay:(null===(b=t.inApp)||void 0===b?void 0:b.onMessageDisplay)||(()=>{}),onMessageClick:(null===(g=t.inApp)||void 0===g?void 0:g.onMessageClick)||(()=>{}),onMessageDismiss:(null===(w=t.inApp)||void 0===w?void 0:w.onMessageDismiss)||(()=>{})};return{sdkKey:t.sdkKey,apiEndpoint:h(t.apiEndpoint),userId:t.userId,anonymousId:t.anonymousId||"",batchSize:t.batchSize||50,batchFlushInterval:"number"==typeof t.batchFlushInterval&&t.batchFlushInterval>0?Math.max(1e3,t.batchFlushInterval):5e3,sendImmediately:t.sendImmediately||!1,maxQueueSize:t.maxQueueSize||1e3,sessionTimeout:t.sessionTimeout||18e5,trackSessionStart:!1!==t.trackSessionStart,trackPageViews:!0===t.trackPageViews,captureUTM:!1!==t.captureUTM,resetSessionOnNewCampaign:t.resetSessionOnNewCampaign||!1,trackPageProperties:!1!==t.trackPageProperties,trackDeviceProperties:!1!==t.trackDeviceProperties,inApp:O,pageContext:{pageVariables:Array.isArray(null===(k=t.pageContext)||void 0===k?void 0:k.pageVariables)?t.pageContext.pageVariables.filter(t=>"string"==typeof t):[],dataLayerVariables:Array.isArray(null===(S=t.pageContext)||void 0===S?void 0:S.dataLayerVariables)?t.pageContext.dataLayerVariables.filter(t=>"string"==typeof t):[],dataLayerName:"string"==typeof(null===(j=t.pageContext)||void 0===j?void 0:j.dataLayerName)&&/^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/.test(t.pageContext.dataLayerName)?t.pageContext.dataLayerName:"dataLayer"},pageEdits:!1!==t.pageEdits,editorScriptUrl:"string"==typeof t.editorScriptUrl&&/^https:\/\//i.test(t.editorScriptUrl)?t.editorScriptUrl:void 0,cardsUiScriptUrl:"string"==typeof t.cardsUiScriptUrl&&/^https:\/\//i.test(t.cardsUiScriptUrl)?t.cardsUiScriptUrl:void 0,webPush:!0===t.webPush||!1!==t.webPush&&void 0,persistQueue:!1!==t.persistQueue,maxRetries:"number"!=typeof t.maxRetries||0>t.maxRetries?3:Math.floor(t.maxRetries),retryBackoffMs:t.retryBackoffMs||1e3,requestTimeout:t.requestTimeout&&t.requestTimeout>0?t.requestTimeout:1e4,respectDoNotTrack:!1!==t.respectDoNotTrack,optOut:!0===t.optOut,trackingConsent:"granted"===t.trackingConsent||"denied"===t.trackingConsent||"pending"===t.trackingConsent?t.trackingConsent:void 0,enableSdkAuthentication:!0===t.enableSdkAuthentication,sdkAuthenticationToken:t.sdkAuthenticationToken,storefrontIdentityToken:"string"==typeof t.storefrontIdentityToken&&t.storefrontIdentityToken?t.storefrontIdentityToken:void 0,storefrontIdentityTokenProvider:"function"==typeof t.storefrontIdentityTokenProvider?t.storefrontIdentityTokenProvider:void 0,enableDebug:t.enableDebug||!1,logLevel:t.logLevel||(t.enableDebug?"debug":"error"),loggingEnabled:!0===t.enableDebug||!!t.logLevel,plugins:t.plugins||[]}}(e?Object.assign(Object.assign({},t&&"object"==typeof t?t:{}),{sdkKey:"jry_sdk_invalid",optOut:!1}):t),this.logger=new zi(this.config.loggingEnabled,this.config.logLevel),this.logger.info("Initializing Joryio SDK v"+s),this.storage=new G(this.config.sdkKey,this.logger),this.dntEnabled=this.config.respectDoNotTrack&&this.isDoNotTrackEnabled(),this.dntEnabled&&this.logger.warn("Do Not Track is enabled, SDK will not track events"),this.config.optOut&&this.writeOptOut(),this.userOptedOut=this.config.optOut||this.storedOptOut(),this.userOptedOut&&(this.optedOutAt=this.storedStamp(Ce)),this.trackingConsent=this.initialConsent(this.config.trackingConsent);const n=function(){if("undefined"==typeof window||!window.location)return null;const t=window.location.href,i=Ae(t),e=Ie(t);if(e)try{window.history&&"function"==typeof window.history.replaceState&&window.history.replaceState(window.history.state,"",e)}catch(t){}return i}();n&&!this.disabled&&(this.pendingLinkToken=n),this.utm=new zt(this.storage,this.logger,this.config.resetSessionOnNewCampaign);const r=this.config.resetSessionOnNewCampaign&&this.config.captureUTM&&this.utm.hasNewCampaign();this.session=new st(this.storage,this.logger,this.config.sessionTimeout),r&&(this.logger.info("New campaign detected, resetting session"),this.session.resetSession()),this.identity=new ft(this.storage,this.logger,this.config.userId,this.config.anonymousId),this.deviceId=this.getOrCreateDeviceId(),this.queue=new Kt(this.storage,this.logger,this.config.batchSize,this.config.batchFlushInterval,this.config.persistQueue,this.config.maxQueueSize,this.config.retryBackoffMs),this.network=new Tt(this.config.sdkKey,this.logger,{maxRetries:this.config.maxRetries,backoffMs:this.config.retryBackoffMs,timeoutMs:this.config.requestTimeout}),this.network.setRetiredTokenStore({load:()=>this.storage.get(Fe),update:t=>{const i=this.storage.get(Fe),e=t(i&&"object"==typeof i&&!Array.isArray(i)?i:{});Object.keys(e).length?this.storage.set(Fe,e):this.storage.remove(Fe)}});const o=this.storage.get(Ne),l="string"==typeof this.config.userId&&this.config.userId?this.config.userId:null;this.withdrawalUserId="string"==typeof o&&o&&o!==this.identity.getUserId()&&!l?o:null,!this.withdrawalUserId&&o&&this.storage.remove(Ne),this.network.setCurrentUserId(this.withdrawalUserId||this.identity.getUserId()),this.config.enableSdkAuthentication&&(this.network.setSdkAuthenticationEnabled(!0),this.config.sdkAuthenticationToken&&this.network.setSdkAuthenticationToken(this.config.sdkAuthenticationToken)),this.network.setAnonymousIdSource(()=>this.identity.getAnonymousId()),this.config.storefrontIdentityTokenProvider&&this.network.setStorefrontIdentityTokenProvider(this.config.storefrontIdentityTokenProvider),this.config.storefrontIdentityToken&&this.network.setStorefrontIdentityToken(this.config.storefrontIdentityToken),this.outbox=this.createOutbox(),this.inapp=new Yt(this.config.apiEndpoint,this.config.sdkKey,this.identity,this.session,this.logger,this.storage,Object.assign(Object.assign({closeButton:!0,backdropClose:!0},this.config.inApp.displayOptions),{onDisplay:this.config.inApp.onMessageDisplay,onClick:this.config.inApp.onMessageClick,onDismiss:this.config.inApp.onMessageDismiss}),{logCustomEvent:(t,i)=>this.track(t,i),setCustomUserAttribute:(t,i)=>this.setAttribute(t,i),changeUser:t=>this.identify(t),requestPushPermission:()=>{this.i.subscribe().catch(t=>{this.logger.warn("Push subscribe failed:",t)})},preparePushPermission:()=>{this.i.prepare().catch(t=>{this.logger.warn("Push prepare failed:",t)})}},this.network,{canSend:()=>this.canSend(),requestTimeoutMs:this.config.requestTimeout,syncIntervalMs:this.config.inApp.syncInterval,evaluationMode:this.config.inApp.evaluationMode,noteStatus:(t,i)=>{this.network.noteSuspended(t,i)}}),this.inapp.setAllowHtmlJsInAppMessages(this.config.inApp.allowHtmlJsInAppMessages),this.pageContext=new w(this.config.pageContext),this.pageContext.setUtmSource(()=>this.config.captureUTM&&this.utm?this.utm.getUTMData():null),this.inapp.setPageContext(this.pageContext),this.placements=new vi(this.config.apiEndpoint,this.config.sdkKey,this.identity,this.session,this.logger,{consent:()=>this.placementConsent(),allowHtml:()=>this.config.inApp.allowHtmlJsInAppMessages,requestTimeoutMs:this.config.requestTimeout,noteStatus:(t,i)=>this.network.noteSuspended(t,i),bridge:{logCustomEvent:(t,i)=>this.track(t,i),setCustomUserAttribute:(t,i)=>this.setAttribute(t,i),changeUser:t=>this.identify(t),requestPushPermission:()=>{this.i.subscribe().catch(t=>this.logger.warn("Push subscribe failed:",t))}}},this.network),this.placements.setPageContext(this.pageContext),this.pageEdits=new U(this.config.apiEndpoint,this.config.sdkKey,this.identity,this.session,this.logger,{consent:()=>this.placementConsent(),requestTimeoutMs:this.config.requestTimeout,noteStatus:(t,i)=>this.network.noteSuspended(t,i)},this.network),this.pageEdits.setPageContext(this.pageContext),this.cards=new Pi(this.config.apiEndpoint,this.config.sdkKey,this.identity,this.session,this.logger,{consent:()=>this.placementConsent(),requestTimeoutMs:this.config.requestTimeout,noteStatus:(t,i)=>this.network.noteSuspended(t,i),cardsUiScriptUrl:this.config.cardsUiScriptUrl},this.network),this.inapp.links=this.links,this.placements.links=this.links,this.cards.links=this.links,this.flags=new Ni(this.config.apiEndpoint,this.config.sdkKey,this.identity,this.session,this.logger,{canSend:()=>this.isInitialized&&!this.disabled&&!this.network.isSuspended()&&this.canSend(),requestTimeoutMs:this.config.requestTimeout,noteStatus:(t,i)=>this.network.noteSuspended(t,i)},this.network),this.o=new Ui(this.logger,this.network,this.identity,this.config.apiEndpoint,(t,i)=>this.runWrite(t,i)),this.i=new oe(this.logger,this.network,this.identity,this.config.apiEndpoint,{canSend:()=>this.canSend(),canWithdraw:()=>this.isInitialized&&!this.disabled,withdrawalUserId:()=>this.effectiveUserId(),storage:this.storage,getDeviceId:()=>this.deviceId,onSubscribeSettled:()=>this.reportPushPermissionIfChanged(),onPrepared:()=>this.reportPushPermissionIfChanged()}),this.queue.setClearedInflightCallback(t=>{const i=this.inflightSessionStartAtClear;i&&(this.inflightSessionStartAtClear=null,t.some(t=>"Session Start"===t.type&&t.sessionId===i)||this.storage.get(Ke)!==i||this.storage.set(Ke,""))}),this.queue.setFlushCallback(async(t,i)=>{try{return await this.flushEvents(t,i)}finally{this.scheduleRetiredTokenPrune()}}),qe.set(this,{optedOut:this.userOptedOut,consent:this.trackingConsent});for(const t of i||[])this.applyPreInitDecision(t);this.recomputePrivacy(),this.isOptedOut&&this.logger.warn("Tracking is off (opt-out, Do Not Track or consent denied)"),this.queue.setPaused(this.consentPending),this.isOptedOut&&this.queue.clear(),this.restoreAttributeWrites(),this.disabled||"undefined"==typeof window||"function"!=typeof window.addEventListener||(this.boundHandlePageUnload=this.handlePageUnload.bind(this),window.addEventListener("pagehide",this.boundHandlePageUnload),window.addEventListener("beforeunload",this.boundHandlePageUnload),this.boundHandleOnline=()=>{this.queue.resetBackoff(),this.canSend()&&this.queue.flush().catch(t=>this.logger.error("Flush failed:",t)),this.outbox.kick(),this.i.retryPendingUnregister(),!this.identity.pending.isEmpty()&&this.canSend()&&(this.attributeFailures=0,null!==this.attributeFlushTimer&&(clearTimeout(this.attributeFlushTimer),this.attributeFlushTimer=null),this.scheduleAttributeFlush(0))},window.addEventListener("online",this.boundHandleOnline),this.boundHandleStorage=t=>this.handleStorageEvent(t),window.addEventListener("storage",this.boundHandleStorage)),this.disabled||this.loadPlugins().catch(t=>this.logger.error("Plugin load failed:",t)),this.isInitialized=!0,this.disabled||(Xe.instance=this),this.logger.info("SDK initialized successfully"),!this.disabled&&this.config.inApp.autoMountPlacements&&this.placements.autoMount(),this.disabled||this.pageContext.start(),!this.disabled&&this.config.pageEdits&&(V()?(this.editor=new X(this.config.apiEndpoint,this.config.sdkKey,this.logger,{scriptUrl:this.config.editorScriptUrl}),this.editor.start()):this.pageEdits.start()),this.disabled||this.flags.start(),this.reportPushPermissionIfChanged();let u=!1;if(this.session.ensureSession(),this.config.trackSessionStart&&!this.isOptedOut){const t=this.session.getSessionInfo(),i=this.storage.get(Ke),e=null!==i&&i!==t.sessionId;(t.isNewSession||r||e)&&(this.trackSessionStart(),u=!0)}!this.config.trackPageViews||this.isOptedOut||u||(this.trackPageView(),"undefined"!=typeof document&&"loading"===document.readyState&&document.addEventListener("DOMContentLoaded",()=>{this.trackPageView()},{once:!0})),this.session.onNewSession(()=>{this.isOptedOut||(this.config.trackSessionStart&&(this.logger.debug("New session created (mid-visit), tracking session start"),this.trackSessionStart()),this.resyncInApp())}),this.canSend()&&(this.queue.start(),this.config.inApp.enabled&&this.inapp.initialize().catch(t=>{this.logger.error("Failed to initialize in-app messaging:",t)}),this.i.syncExistingSubscription().catch(()=>{}),this.releaseHeldWrites()),this.syncWorkerReporting(),this.isOptedOut||this.releaseDeferredIdentify(),this.flushLinkIdentity(),this.syncOptOutMarker(),this.scheduleRetiredTokenPrune(),this.outbox.kick(),this.i.retryPendingUnregister()}createOutbox(){return new me({storage:this.storage,logger:this.logger,gate:t=>!this.isInitialized||this.disabled?"hold":t.withdrawal?"send":this.network.isSuspended()?"hold":this.isOptedOut?"drop":this.consentPending?"hold":"send",resolveOwner:t=>this.resolveOwner(t),ownerIsCurrentUser:t=>(t.userId||null)===this.effectiveUserId(),currentIdentity:()=>({anonymousId:this.identity.getAnonymousId(),userId:this.effectiveUserId()}),send:(t,i)=>this.sendWrite(t.record,i),beforeSend:()=>this.flushQueueForWrite(),isSdkAuthError:(t,i)=>this.network.isSdkAuthError(t,i),onSettled:(t,i)=>{this.onWriteSettled(t,i),this.scheduleRetiredTokenPrune()},keepalive:(t,i)=>{const e=this.writeRequest(t.record,i),s=JSON.stringify(e.body);return this.network.postKeepalive(e.url,e.body)?vt(s)+256:null}})}currentOwner(){const t=this.effectiveUserId();return Object.assign({anonymousId:this.identity.getAnonymousId()},t?{userId:t}:{})}effectiveUserId(){return this.withdrawalUserId||this.identity.getUserId()}deferIdentify(t){t!==this.effectiveUserId()&&(this.network.switchUser(t),this.withdrawalUserId=t===this.identity.getUserId()?null:t,this.withdrawalUserId?this.storage.set(Ne,this.withdrawalUserId):this.storage.remove(Ne),this.logger.debug("Tracking is off: identify kept on this device for withdrawals only, not sent"))}releaseDeferredIdentify(){const t=this.withdrawalUserId;t&&(this.forgetDeferredIdentify(),this.identify(t))}forgetDeferredIdentify(){this.withdrawalUserId=null,this.storage.remove(Ne)}scheduleRetiredTokenPrune(t=0){null!==this.pruneTimer||this.disabled||(this.pruneTimer=setTimeout(()=>{this.pruneTimer=null,this.pruneRetiredTokens()},t))}pruneRetiredTokens(){var t;try{if(!this.network.retiredSdkAuthUsers().length)return;const i=new Set,e=this.network.getCurrentUserId();e&&i.add(e),this.withdrawalUserId&&i.add(this.withdrawalUserId);for(const t of this.queue.getQueuedEvents())t.userId&&i.add(t.userId);for(const t of this.queue.getPendingIdentifies())i.add(t.userId);for(const t of this.outbox.records()){const e=t.payload.userId;"string"==typeof e&&e&&i.add(e)}for(const e of this.identity.pending.serialize())(null===(t=e.owner)||void 0===t?void 0:t.userId)&&i.add(e.owner.userId);for(const t of this.i.pendingUnregisterUsers())i.add(t);for(const t of Ee)Ue(this.storage.get(t),i);const s=this.network.forgetRetiredSdkAuthTokensExcept(i);null!==s&&this.scheduleRetiredTokenPrune(s+50)}catch(t){this.logger.warn("Could not prune stored SDK authentication tokens:",t)}}handleStorageEvent(t){var i,e;try{if(!this.isInitialized||this.disabled||!t)return;const s=null!==(i=t.key)&&void 0!==i?i:null,n=t=>null===s||s===this.storage.storageKeyFor(t);if(null===s)this.repersistPrivacyDecisions(),this.outbox.persistNow();else if(n(_e)||n(Ce)||n(Pe)||n(Te)||n(De)||n($e)){const t=this.storedOptOut(),i=this.storedDenial();t&&(this.optedOutAt=this.storedStamp(Ce)),i&&(this.consentDeniedAt=this.storedStamp(De)),this.noteDecisionStamps();let e=!1;t!==this.userOptedOut&&(this.userOptedOut=t,e=!0),i&&"denied"!==this.trackingConsent?(this.trackingConsent="denied",e=!0):i||"denied"!==this.trackingConsent?!i&&"pending"===this.trackingConsent&&n($e)&&null!==this.storage.get($e)&&(this.trackingConsent="granted",e=!0):(this.trackingConsent="granted",e=!0),e&&this.applyPrivacyState()}if(null!==s&&n(Ne)){const t=this.storage.get(Ne),i="string"==typeof t&&t&&t!==this.identity.getUserId()?t:null;i!==this.withdrawalUserId&&(this.network.switchUser(i||this.identity.getUserId()),this.withdrawalUserId=i)}if(null!==s&&n(Y)&&this.awaitingSessionOf&&(this.awaitingSessionOf===this.identity.getAnonymousId()&&this.storage.get(Y)&&this.session.followStoredSession(),this.awaitingSessionOf=null),n(Je)||n(Re)){const t=this.storage.get(Je),i=this.storage.get(Re)||null;if(!t)return;if(t===this.identity.getAnonymousId()&&i===this.identity.getUserId())return;this.logger.info("Another tab changed the visitor identity; following it");const s=t!==this.identity.getAnonymousId();this.config.inApp.enabled?this.inapp.clearAll():this.inapp.invalidate(),this.pinAnonymousWrites(),this.network.switchUser(i),this.identity.adopt(t,i),this.placements.invalidate(),this.cards.invalidate(!0),null===(e=this.pageEdits)||void 0===e||e.invalidate(),this.flags.onIdentityChanged(),this.withdrawalUserId=null,s&&(this.utm.reset(),this.session.followStoredSession(),this.awaitingSessionOf=t),this.resyncInApp(!0)}}catch(t){this.logger.error("Could not follow a change made in another tab:",t)}}repersistPrivacyDecisions(){this.userOptedOut&&!0!==this.storage.get(_e)&&this.writeOptOut(this.optedOutAt),"denied"===this.trackingConsent&&"denied"!==this.storage.get(Te)&&this.writeDenial(this.consentDeniedAt),this.withdrawalUserId&&this.storage.get(Ne)!==this.withdrawalUserId&&this.storage.set(Ne,this.withdrawalUserId)}storedStamp(t){const i=this.storage.get(t);return"number"==typeof i&&Number.isFinite(i)?i:0}noteDecisionStamps(){for(const t of[Ce,Pe,De,$e])this.lastDecisionStamp=Math.max(this.lastDecisionStamp,this.storedStamp(t))}nextDecisionStamp(){return this.noteDecisionStamps(),this.lastDecisionStamp=Math.max(Date.now(),this.lastDecisionStamp+1,this.optedOutAt+1,this.consentDeniedAt+1),this.lastDecisionStamp}storedOptOut(){return!0===this.storage.get(_e)&&!(this.storedStamp(Pe)>this.storedStamp(Ce))}storedDenial(){return"denied"===this.storage.get(Te)&&!(this.storedStamp($e)>this.storedStamp(De))}writeOptOut(t){const i=void 0===t?this.nextDecisionStamp():t;this.optedOutAt=i,this.storage.set(_e,!0),this.storage.set(Ce,i)}writeOptIn(){const t=this.nextDecisionStamp();this.optedOutAt=0,this.storage.remove(_e),this.storage.remove(Ce),this.storage.set(Pe,t)}writeDenial(t){const i=void 0===t?this.nextDecisionStamp():t;this.consentDeniedAt=i,this.storage.set(Te,"denied"),this.storage.set(De,i)}writeGrant(){const t=this.nextDecisionStamp();this.consentDeniedAt=0,this.storage.remove(Te),this.storage.remove(De),this.storage.set($e,t)}resolveOwner(t){if(t.userId)return t;const i=this.effectiveUserId();return i&&t.anonymousId===this.identity.getAnonymousId()?this.queue.getPendingIdentifies().some(i=>i.anonymousId===t.anonymousId)?t:{anonymousId:t.anonymousId,userId:i}:t}pinAnonymousWrites(){const t=this.identity.getUserId();if(!t)return;const i=this.identity.getAnonymousId();this.identity.pending.pinOwner(i,t),this.persistAttributeWrites(),this.outbox.pinOwner(i,t)}writeRequest(t,i){const e=this.config.apiEndpoint,s=Object.assign(Object.assign({},i.userId?{userId:i.userId}:{}),{anonymousId:i.anonymousId});switch(t.kind){case"alias":return{url:e+"/v1/alias/add",body:Object.assign(Object.assign({},t.payload),s)};case"subscription":return{url:e+"/v1/subscriptions/channel",body:Object.assign(Object.assign({},t.payload),s)};case"group":return{url:e+"/v1/subscriptions/group",body:Object.assign(Object.assign({},t.payload),s)};default:return{url:e+"/v1/attributes",body:Object.assign(Object.assign({},i.userId?{userId:i.userId}:{anonymousId:i.anonymousId}),this.markerOps(t))}}}markerOps(t){const i=t.payload.value;return{attributes:{[He]:i}}}sendWrite(t,i){const e=this.config.apiEndpoint,s=Object.assign(Object.assign({},i.userId?{userId:i.userId}:{}),{anonymousId:i.anonymousId});switch(t.kind){case"alias":return this.network.sendAddAlias(e,Object.assign(Object.assign({},t.payload),s));case"subscription":return this.network.sendSubscriptionUpdate(e,Object.assign(Object.assign({},t.payload),s));case"group":return this.network.sendSubscriptionGroupUpdate(e,Object.assign(Object.assign({},t.payload),s));default:return this.network.sendSetAttributes(e,this.markerOps(t),i.userId,i.anonymousId)}}onWriteSettled(t,i){if("marker"!==t.record.kind)return;const e=t.record.payload.value;"done"===i?(e?this.storage.set(Me,!0):this.storage.remove(Me),this.storage.remove(xe)):this.storage.set(xe,e),this.syncOptOutMarker()}syncWorkerReporting(){this.disabled||this.i.setTrackingOptedOut(this.isOptedOut||this.consentPending).catch(()=>{})}initialConsent(t){const i=this.storedDenial();return"granted"===t?(this.storage.remove(Te),this.storage.remove(De),"granted"):"denied"===t?(this.writeDenial(),"denied"):i?(this.consentDeniedAt=this.storedStamp(De),"denied"):"pending"===t?"pending":"granted"}storeConsent(t){return"granted"===t?(this.writeGrant(),"granted"):"denied"===t?(this.writeDenial(),"denied"):this.storedDenial()?(this.logger.info("updateConsent('pending') ignored: consent was denied, and only 'granted' lifts that"),"denied"):"pending"}applyPreInitDecision(t){try{switch(t.method){case"optOut":this.userOptedOut=!0,this.writeOptOut();break;case"optIn":this.userOptedOut=!1,this.writeOptIn();break;case"updateConsent":"granted"!==t.consent&&"denied"!==t.consent&&"pending"!==t.consent||(this.trackingConsent=this.storeConsent(t.consent));break;case"wipeData":this.i.forget().catch(()=>{}),this.wipeLocalState(),this.config.userId&&(this.identity.identify(this.config.userId),this.network.setCurrentUserId(this.config.userId)),this.config.enableSdkAuthentication&&this.config.sdkAuthenticationToken&&this.network.setSdkAuthenticationToken(this.config.sdkAuthenticationToken)}}catch(i){this.logger.error(`Applying ${t.method} from before init failed:`,i)}}getTrackingConsent(){return this.trackingConsent}isUserOptedOut(){return this.userOptedOut}syncOptOutMarker(){if(this.disabled||!this.isInitialized)return;const t=this.userOptedOut,i=!0===this.storage.get(Me),e=this.identity.getAnonymousId(),s=this.outbox.findLast(t=>"marker"===t.record.kind&&t.record.payload.anonymousId===e);if(s){if("marker"===s.record.kind&&s.record.payload.value===t)return;if(t===i&&!this.outbox.isInFlight(s))return void this.outbox.cancel(t=>"marker"===t.record.kind&&t.record.payload.anonymousId===e)}else{if(t===i)return;if(this.storage.get(xe)===t)return}this.outbox.enqueue({kind:"marker",payload:Object.assign({value:t},this.currentOwner())})}recomputePrivacy(){this.isOptedOut=this.disabled||this.userOptedOut||this.dntEnabled||"denied"===this.trackingConsent,this.consentPending=!this.isOptedOut&&"pending"===this.trackingConsent}canSend(){return this.isInitialized&&!this.isOptedOut&&!this.consentPending&&!this.network.isSuspended()}applyPrivacyState(){var t,i,e,s;const n=this.isOptedOut,r=this.consentPending;if(this.recomputePrivacy(),this.syncWorkerReporting(),n===this.isOptedOut&&r===this.consentPending||(this.inapp.invalidate(),null===(t=this.placements)||void 0===t||t.invalidate(),null===(i=this.cards)||void 0===i||i.invalidate(!1),null===(e=this.pageEdits)||void 0===e||e.invalidate({siteSettings:!0}),null===(s=this.flags)||void 0===s||s.onIdentityChanged()),this.isOptedOut){const t=this.session.getSessionId(),i=i=>"Session Start"===i.type&&i.sessionId===t;return this.queue.getWaitingEvents().some(i)?this.storage.set(Ke,""):t&&this.queue.getInflightEvents().some(i)&&(this.inflightSessionStartAtClear=t),this.queue.stop(),this.queue.clear(),this.queue.setPaused(!1),this.clearPendingAttributeWrites(),this.outbox.discardNonWithdrawals(),this.outbox.kick(),this.config.inApp.enabled&&this.inapp.stop(),void(this.pendingLinkToken=null)}if(n&&this.releaseDeferredIdentify(),n&&this.trackSessionStartIfMissing(),this.consentPending)return this.queue.stop(),this.queue.setPaused(!0),void(this.config.inApp.enabled&&this.inapp.stop());this.queue.setPaused(!1),this.queue.isStarted()||this.queue.start(),this.queue.flush().catch(t=>this.logger.error("Flush failed:",t)),this.releaseHeldWrites(),this.config.inApp.enabled&&this.inapp.initialize().catch(t=>{this.logger.error("Failed to initialize in-app messaging:",t)}),this.i.syncExistingSubscription().catch(()=>{}),this.flushLinkIdentity()}flushLinkIdentity(){const t=this.pendingLinkToken;t&&(this.disabled||this.isOptedOut?this.pendingLinkToken=null:this.canSend()&&(this.pendingLinkToken=null,this.sentLinkTokens.has(t)||(this.effectiveUserId()?this.logger.debug("Link identity not sent: a user is identified on this browser"):this.network.hasStorefrontIdentity()?this.logger.debug("Link identity not sent: a signed-in store customer is on this browser"):(this.sentLinkTokens.add(t),this.network.sendIdentifyLink(this.config.apiEndpoint,{token:t,anonymousId:this.identity.getAnonymousId()}).catch(t=>this.logger.debug("Link identity request failed:",t))))))}identifyFromLink(t){if(!this.isInitialized||this.disabled)return;const i=Ae(t);if(i){try{if("undefined"!=typeof window&&window.location&&Ae(window.location.href)===i){const t=Ie(window.location.href);t&&window.history&&"function"==typeof window.history.replaceState&&window.history.replaceState(window.history.state,"",t)}}catch(t){}this.pendingLinkToken=i,this.flushLinkIdentity()}}releaseHeldWrites(){this.identity.pending.isEmpty()||this.scheduleAttributeFlush(0),this.outbox.kick()}runWrite(t,i){this.isInitialized&&!this.disabled?!this.isOptedOut&&0>=this.dataGate.size||Xi(i)?(this.withdrawalUserId&&Xi(i)&&i.payload.anonymousId===this.identity.getAnonymousId()&&(i=Object.assign(Object.assign({},i),{payload:Object.assign(Object.assign({},i.payload),{userId:this.withdrawalUserId})})),this.outbox.enqueue(i)):this.logger.debug(t+" not sent: tracking is off"):this.logger.error(t+": SDK not initialized")}restoreAttributeWrites(){const t=this.storage.get(Be);if(this.isOptedOut)return this.storage.remove(Be),void this.outbox.discardNonWithdrawals();t&&"object"==typeof t&&(Array.isArray(t.entries)?this.identity.pending.restore(t.entries):(t.ops&&"object"==typeof t.ops&&this.identity.pending.mark(t.ops),t.increment&&"object"==typeof t.increment&&this.identity.pending.mark({increment:t.increment})))}persistAttributeWrites(){this.identity.pending.isEmpty()?this.storage.remove(Be):this.storage.set(Be,{entries:this.identity.pending.serialize()})}async flushQueueForWrite(){this.canSend()&&(this.queue.getPendingIdentify()||this.queue.getQueueSize()>0)&&await this.queue.flush().catch(()=>{})}trackSessionStart(){this.logger.debug("Tracking session start");const t={};this.config.trackDeviceProperties&&(Object.assign(t,(()=>{var t,i;if("undefined"==typeof window||"undefined"==typeof navigator)return{};const e=navigator.userAgent||"",s=navigator.language||"",n=Array.isArray(navigator.languages)?navigator.languages:void 0;return{$user_agent:e,$timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,$screen_width:null===(t=window.screen)||void 0===t?void 0:t.width,$screen_height:null===(i=window.screen)||void 0===i?void 0:i.height,$viewport_width:window.innerWidth,$viewport_height:window.innerHeight,$language:s,$languages:n,$platform:navigator.platform,$browser:Ji(e)}})()),t.$device_id=this.deviceId),"undefined"!=typeof window&&window.location&&(t.landing_page=window.location.href,t.landing_path=window.location.pathname,t.landing_search=window.location.search,t.landing_title="undefined"!=typeof document?document.title:"",t.landing_referrer="undefined"!=typeof document&&document.referrer||null),this.track("Session Start",t),this.storage.set(Ke,this.session.getSessionId())}trackSessionStartIfMissing(){this.config.trackSessionStart&&!this.isOptedOut&&(this.session.ensureSession(),this.storage.get(Ke)!==this.session.getSessionId()&&this.trackSessionStart())}getOrCreateDeviceId(){const t="device_id",i=this.storage.get(t);if(i)return i;const e=Q();return this.storage.set(t,e),e}trackPageView(){if("undefined"==typeof window||!window.location)return;const t=window.location.href;if(this.lastTrackedUrl===t)return;const i={url:t,path:window.location.pathname,search:window.location.search,title:"undefined"!=typeof document?document.title:""};this.config.trackPageProperties&&"undefined"!=typeof document&&(i.referrer=document.referrer||null,i.landing_page=this.utm.getSessionLandingPage()||null),this.lastTrackedUrl=t,this.track("Page Viewed",i)}track(t,i){var e,s;if(this.isInitialized){if(!this.isDroppingDataCalls("track"))if(this.isOptedOut)this.logger.debug("Tracking disabled, event not tracked:",t);else if("string"!=typeof t||1>t.length||t.length>255)this.logger.error("track() needs an event name of 1-255 characters; event dropped");else try{"Session Start"!==t&&this.session.refreshIfExpired(),this.session.ensureSession(),this.session.updateActivity();const n=i&&"object"==typeof i&&!Array.isArray(i)?Object.assign({},i):{};this.config.captureUTM&&Object.assign(n,this.utm.getUTMProperties()),this.deviceId&&!n.$device_id&&(n.$device_id=this.deviceId);let r={eventId:Q(),type:t,properties:n,timestamp:(new Date).toISOString(),userId:this.identity.getUserId(),anonymousId:this.identity.getAnonymousId(),sessionId:this.session.getSessionId()};for(const t of this.config.plugins)if(t.beforeTrack){try{r=t.beforeTrack(r)}catch(i){this.logger.error(`Plugin ${t.name} beforeTrack threw; event kept unchanged:`,i)}if(null===r)return void this.logger.debug("Event blocked by plugin: "+t.name)}r&&r.properties&&"object"==typeof r.properties&&(r=Object.assign(Object.assign({},r),{properties:ge(r.properties,(i,e)=>this.logger.warn(`Event "${t}": property "${i}" dropped - ${e}`))}));const o=r&&r.properties&&"object"==typeof r.properties?function(t){const i=Object.keys(t).length;if(i>200)return i+" property keys (the limit is 200)";const e=(t,i)=>i>5||null!==t&&"object"==typeof t&&(Array.isArray(t)?t:Object.values(t)).some(t=>null!==t&&"object"==typeof t&&e(t,i+1));if(e(t,1))return"properties nested deeper than 5 levels";let s;try{s=JSON.stringify(t)}catch(t){return"properties that cannot be serialized (a circular reference?)"}return s.length>51200?s.length+" characters of properties (the limit is 51200)":null}(r.properties):null;if(o)return void this.logger.error(`Event "${t}" dropped: ${o}`);if(this.queue.enqueue(r),this.canSend())try{null===(e=this.inapp)||void 0===e||e.onEventTracked(t,n),null===(s=this.placements)||void 0===s||s.onEventTracked(t,n)}catch(t){this.logger.error("In-app trigger evaluation failed:",t)}for(const t of this.config.plugins)if(t.afterTrack)try{t.afterTrack(r)}catch(i){this.logger.error(`Plugin ${t.name} afterTrack threw:`,i)}this.config.sendImmediately&&this.canSend()&&this.flush().catch(t=>this.logger.error("Immediate flush failed:",t))}catch(t){this.logger.error("track() failed:",t)}}else this.logger.error("SDK not initialized")}identify(t){var i;if(!this.isInitialized)return void this.logger.error("SDK not initialized");if("string"!=typeof t||!t.trim()||t.length>255)return void this.logger.error("identify() needs a userId of 1-255 characters");if(this.isOptedOut)return void(this.disabled||this.deferIdentify(t));this.withdrawalUserId&&this.forgetDeferredIdentify();const e=this.identity.getUserId(),s=this.identity.getAnonymousId();this.queue.setPendingIdentify({userId:t,anonymousId:s,attributes:{}});const n=!!e&&e!==t;n&&(this.pinAnonymousWrites(),this.config.inApp.enabled&&this.inapp.clearAll()),this.identity.identify(t),this.network.switchUser(t),e!==t&&(this.inapp.invalidate(),this.placements.invalidate(),this.cards.invalidate(!0),null===(i=this.pageEdits)||void 0===i||i.invalidate(),this.flags.onIdentityChanged()),this.canSend()&&this.queue.flush(!1,!0).catch(t=>{this.logger.error("Failed to flush with identify:",t)}).then(()=>{e!==t&&this.resyncInApp(n)})}addAlias(t,i){if(!this.isInitialized)return void this.logger.error("SDK not initialized");if(this.isDroppingDataCalls("addAlias"))return;if("string"!=typeof t||!t.trim()||"string"!=typeof i||!i.trim())return void this.logger.error("addAlias(aliasLabel, aliasName) needs two non-empty strings");const e=this.identity.getUserId(),s=Object.assign(Object.assign({anonymousId:this.identity.getAnonymousId()},e?{userId:e}:{}),{aliasLabel:t,aliasName:i});this.runWrite("addAlias",{kind:"alias",payload:s})}setAttributes(t){if(!this.isInitialized)return void this.logger.error("SDK not initialized");if(this.isDroppingDataCalls("setAttributes"))return;if(!t||"object"!=typeof t||Array.isArray(t))return void this.logger.error('setAttributes requires a plain object, e.g. setAttributes({ email: "user@example.com" })');const i={},e=[];for(const[s,n]of Object.entries(t)){if(!s)continue;if(null==n){e.push(s);continue}const t=be(n);t?this.logger.warn(`Attribute "${s}" not set: its value is ${t}`):i[s]=n}this.identity.setAttributes(i);for(const t of e)this.identity.unsetAttribute(t);this.isOptedOut||!Object.keys(i).length&&!e.length||this.sendAttributesAfterPendingIdentify(Object.assign(Object.assign({},Object.keys(i).length?{attributes:i}:{}),e.length?{unset:e}:{}))}sendAttributesAfterPendingIdentify(t){this.identity.pending.mark(t,this.currentOwner()),this.persistAttributeWrites(),this.scheduleAttributeFlush(Xe.ATTRIBUTE_FLUSH_DEBOUNCE_MS)}scheduleAttributeFlush(t){null===this.attributeFlushTimer&&(this.attributeFlushTimer=setTimeout(()=>{this.attributeFlushTimer=null,this.canSend()&&this.flushAttributeOps()},t))}clearPendingAttributeWrites(){null!==this.attributeFlushTimer&&(clearTimeout(this.attributeFlushTimer),this.attributeFlushTimer=null),this.identity.pending.clear(),this.attributeGeneration++,this.attributeFlushInFlight=!1,this.attributeFlushAgain=!1,this.attributeFailures=0,this.storage.remove(Be)}flushAttributeOps(){(this.queue.getPendingIdentify()?this.queue.flush(!1,!0).catch(()=>{}):Promise.resolve()).then(()=>{var t;if(!this.canSend())return;if(this.queue.getPendingIdentify())return void this.scheduleAttributeFlush(this.attributeRetryDelay());if(this.attributeFlushInFlight)return void(this.attributeFlushAgain=!0);const i=this.identity.pending.nextRequest(t=>this.resolveOwner(null!=t?t:this.currentOwner()));if(!i)return;this.attributeFlushInFlight=!0;const e=this.attributeGeneration,{ops:s,entries:n}=i,r=this.resolveOwner(null!==(t=i.owner)&&void 0!==t?t:this.currentOwner());this.network.sendSetAttributes(this.config.apiEndpoint,s,r.userId,r.anonymousId).then(t=>{var i,o;if(e!==this.attributeGeneration)return;const h=Yi(t,{isSdkAuthError:this.network.isSdkAuthError(t.status,t.data),ownerIsCurrentUser:(r.userId||null)===this.identity.getUserId()});if("done"===h.action){this.attributeFailures=0,this.identity.pending.acknowledge(n),this.persistAttributeWrites();const t=null===(i=s.attributes)||void 0===i?void 0:i[We];return"string"==typeof t&&this.storage.set(Ve,t),this.identity.pending.hasUnsent()&&(this.attributeFlushAgain=!0),void this.scheduleRetiredTokenPrune()}if("drop"===h.action)return this.logger.error("Attributes dropped: "+h.reason,t.error),this.identity.pending.drop(n),this.persistAttributeWrites(),this.identity.pending.hasUnsent()&&(this.attributeFlushAgain=!0),void this.scheduleRetiredTokenPrune();const a=!(t.softFailure||0!==t.status&&500>t.status),l=this.identity.pending.release(n,a);if(l>0&&this.logger.error(`Failed to send attributes (HTTP ${t.status||"no response"}); ${l} increment(s) are LOST (an $inc cannot be safely retried).`),"hold"===h.action)return this.persistAttributeWrites(),void this.logger.error(`Attributes not sent: ${h.reason}; they are kept for the next page view.`);if(h.counts){const i=n.filter(t=>(t.attempts=(t.attempts||0)+1,t.attempts>=10));i.length&&(this.logger.error(`Attributes failed (HTTP ${t.status}) too many times; dropping them`),this.identity.pending.drop(i))}this.persistAttributeWrites(),this.logger.warn(`Failed to send attributes (HTTP ${t.status||"no response"}); will retry`),this.attributeFailures++,this.scheduleAttributeFlush(Math.max(this.attributeRetryDelay(),Math.min(null!==(o=h.retryAfterMs)&&void 0!==o?o:0,3e5)))}).then(()=>{e===this.attributeGeneration&&(this.attributeFlushInFlight=!1,this.attributeFlushAgain&&(this.attributeFlushAgain=!1,this.flushAttributeOps()))}).catch(t=>{e===this.attributeGeneration&&(this.attributeFlushInFlight=!1),this.logger.error("Attribute flush bookkeeping failed:",t)})})}attributeRetryDelay(){const t=Math.max(1,this.attributeFailures);return Math.min(5e3*Math.pow(2,t-1),3e5)}reportPushPermissionIfChanged(){if(this.isInitialized&&!this.isOptedOut&&this.pushPermissionReported())try{const t=this.i.getPermissionState(),i="notDetermined"===t?"not_determined":t;if(this.storage.get(Ve)===i)return;this.logger.debug(`Push permission changed to ${i}; reporting`),this.setAttribute(We,i)}catch(t){this.logger.warn("Could not report push permission:",t)}}pushPermissionReported(){return!0===this.config.webPush||!!this.i.usedOnThisPage()||!1!==this.config.webPush&&this.i.usedEarlier()}setAttribute(t,i){"string"==typeof t&&t?this.setAttributes({[t]:i}):this.logger.error("setAttribute(key, value) needs a non-empty key")}incrementAttribute(t,i=1){this.isInitialized?this.isDroppingDataCalls("incrementAttribute")||("string"==typeof t&&t&&"number"==typeof i&&Number.isFinite(i)?(this.identity.incrementAttribute(t,i),this.isOptedOut||this.sendAttributesAfterPendingIdentify({increment:{[t]:i}})):this.logger.error("incrementAttribute(key, value) needs a key and a finite number")):this.logger.error("SDK not initialized")}unsetAttribute(t){this.isInitialized?this.isDroppingDataCalls("unsetAttribute")||("string"==typeof t&&t?(this.identity.unsetAttribute(t),this.isOptedOut||this.sendAttributesAfterPendingIdentify({unset:[t]})):this.logger.error("unsetAttribute() needs a non-empty attribute key")):this.logger.error("SDK not initialized")}addToArray(t,i){if(!this.isInitialized)return void this.logger.error("SDK not initialized");if(this.isDroppingDataCalls("addToArray"))return;if("string"!=typeof t||!t)return void this.logger.error("addToArray() needs a non-empty attribute key");const e=be(i);e?this.logger.warn(`addToArray("${t}") ignored: the value is ${e}`):(this.identity.addToArray(t,i),this.isOptedOut||this.sendAttributesAfterPendingIdentify({append:{[t]:i}}))}removeFromArray(t,i){if(!this.isInitialized)return void this.logger.error("SDK not initialized");if(this.isDroppingDataCalls("removeFromArray"))return;if("string"!=typeof t||!t)return void this.logger.error("removeFromArray() needs a non-empty attribute key");const e=be(i);e?this.logger.warn(`removeFromArray("${t}") ignored: the value is ${e}`):(this.identity.removeFromArray(t,i),this.isOptedOut||this.sendAttributesAfterPendingIdentify({remove:{[t]:i}}))}async reset(){return this.resetIdentity(void 0)}async resetTo(t){if(!this.isInitialized)return this.logger.error("SDK not initialized"),!1;const i=this.identity.getUserId(),e=function(t,i,e=null,s=[]){return"string"==typeof t&&we.test(t)?ke.test(t)?"resetTo: the anonymous id has the shape of a Joryio profile id":i.some(i=>"string"==typeof i&&i===t)?"resetTo: the anonymous id is a user id":"string"==typeof e&&e===t||s.includes(t)?"resetTo: the anonymous id belongs to the signed-in user":null:'resetTo: the anonymous id must be 8 to 255 letters, digits, ".", "_", ":" or "-"'}(t,[i,this.withdrawalUserId],i?this.identity.getAnonymousId():null,this.signedInAnonymousIds());return e&&this.logger.error(e+"; a random anonymous id is used instead"),await this.resetIdentity(e?void 0:t),!e}signedInAnonymousIds(){const t=this.storage.get(Se);return Array.isArray(t)?t.filter(t=>"string"==typeof t):[]}async resetIdentity(t){var i,e,s;this.isInitialized?(this.logger.info("Resetting user identity"),this.pendingLinkToken=null,this.config.inApp.enabled&&this.inapp.clearAll(),this.network.retireSdkAuthToken(),this.network.clearStorefrontIdentityToken(),this.forgetDeferredIdentify(),this.identity.getUserId()&&this.storage.set(Se,(e=this.signedInAnonymousIds(),s=this.identity.getAnonymousId(),[...e.filter(t=>t!==s),s].slice(-20))),this.pinAnonymousWrites(),this.identity.reset(t),this.flags.onIdentityChanged(),this.network.setCurrentUserId(this.identity.getUserId()),this.placements.invalidate(),this.cards.invalidate(!0),null===(i=this.pageEdits)||void 0===i||i.invalidate({siteSettings:!0}),this.utm.reset(),this.session.resetSession(),await this.flush().catch(()=>{}),this.canSend()&&(this.resyncInApp(!0),this.i.syncExistingSubscription(!0).catch(()=>{})),this.outbox.kick(),this.logger.info("User identity reset")):this.logger.error("SDK not initialized")}async wipeData(){if(!this.isInitialized)return void this.logger.error("SDK not initialized");this.logger.info("Wiping local SDK data"),this.pendingLinkToken=null;const t=this.i.forget().catch(()=>{});this.wipeLocalState(),this.session.ensureSession(),this.trackSessionStartIfMissing(),await t,this.canSend()&&this.resyncInApp(!0),this.logger.info("Local SDK data wiped")}wipeLocalState(){var t,i;this.clearPendingAttributeWrites(),this.outbox.discardNonWithdrawals(),this.storage.remove(Ve),this.storage.remove(Se),this.storage.set(Ke,""),this.queue.clear(),this.config.inApp.enabled?this.inapp.clearAll():this.inapp.invalidate(),this.inapp.forgetImpressions();const e=new Set;for(const t of[this.effectiveUserId(),this.identity.getUserId(),this.network.getCurrentUserId()])t&&e.add(t);for(const t of this.outbox.records()){const i=t.payload.userId;"string"==typeof i&&i&&e.add(i)}for(const t of this.i.pendingUnregisterUsers())e.add(t);for(const t of[ae,ne])Ue(this.storage.get(t),e);this.network.retireSdkAuthToken(),this.network.dropStandbySdkAuthTokens(e),this.network.clearStorefrontIdentityToken(),this.forgetDeferredIdentify(),this.pinAnonymousWrites(),this.identity.reset(),this.flags.onIdentityChanged(),this.network.setCurrentUserId(null),this.placements.invalidate(),null===(t=this.cards)||void 0===t||t.invalidate(!0),null===(i=this.pageEdits)||void 0===i||i.invalidate({siteSettings:!0}),this.utm.reset(),this.session.clear(),this.lastTrackedUrl=null,this.storage.remove("device_id"),this.deviceId=this.getOrCreateDeviceId()}resyncInApp(t=!1){this.config.inApp.enabled&&this.canSend()&&(t?this.inapp.initialize():this.inapp.sync().then(()=>{})).catch(t=>this.logger.debug("In-app re-sync failed:",t))}async flush(){this.isInitialized?await this.queue.flush(!1,!0):this.logger.error("SDK not initialized")}async flushEvents(t,i){var e,s,n,r;if(!this.canSend())return{status:"retry"};this.logger.debug(`Sending ${t.length} events${i?" + identify":""} to backend`);const o=await this.network.sendEvents(this.config.apiEndpoint,t,i);if(o.ok||o.softFailure){const h=Array.isArray(null===(e=o.data)||void 0===e?void 0:e.rejectedIndices)?o.data.rejectedIndices:void 0;let a=!1,l=!1,u=!0;if(i&&!(null===(s=o.data)||void 0===s?void 0:s.identified)&&o.softFailure)a=!0;else if(i&&!(null===(n=o.data)||void 0===n?void 0:n.identified)){this.logger.debug("Backend did not confirm atomic identify, falling back to standalone");const t=await this.network.sendIdentify(this.config.apiEndpoint,i.userId,i.attributes||{},i.anonymousId);if(!t.ok){const e=!(t.softFailure||0!==t.status&&408!==t.status&&429!==t.status&&500>t.status);!0===t.softFailure||e||401===t.status&&this.network.isSdkAuthError(t.status,t.data)&&i.userId===this.identity.getUserId()||402===t.status?(this.logger.error("Standalone identify fallback failed; it is kept and retried:",t.error),a=!0,u=!e&&402!==t.status):(this.logger.error(`Standalone identify fallback refused (HTTP ${t.status}); dropping it:`,t.error),l=!0)}}return o.softFailure?{status:"ok",failedIndices:Array.isArray(null===(r=o.data)||void 0===r?void 0:r.failedIndices)?o.data.failedIndices:t.map((t,i)=>i),rejectedIndices:h,identifyFailed:a,identifyAttemptCounts:u,identifyDropped:l}:(this.logger.debug("Events sent successfully"),{status:"ok",rejectedIndices:h,identifyFailed:a,identifyAttemptCounts:u,identifyDropped:l})}return this.classifyFailure(o,t,i)}classifyFailure(t,i=[],e){var s,n;const r=t.status;if(400===r||413===r||422===r)return{status:"rejected",httpStatus:r};if(401===r){if(this.network.isSdkAuthError(r,t.data)){const r=null===(s=t.data)||void 0===s?void 0:s.reason,o=(null==e?void 0:e.userId)||(null===(n=i.find(t=>t.userId))||void 0===n?void 0:n.userId)||null;return o&&o!==this.identity.getUserId()?{status:"dropped",reason:"401 "+(r||"sdk_authentication_error")}:{status:"retry",counts:!0}}return{status:"suspended",reason:"the SDK key was refused (401)"}}return 402===r?{status:"suspended",reason:"event ingestion is paused for this workspace (402)"}:403===r?{status:"suspended",reason:"the request was forbidden (403)"}:0!==r&&408!==r&&429!==r&&500>r?{status:"suspended",reason:"the API answered HTTP "+r}:{status:"retry",retryAfterMs:t.retryAfterMs}}handlePageUnload(){if(this.isInitialized)if("undefined"==typeof navigator||!1!==navigator.onLine){try{this.outbox.handOffAtUnload(8192)}catch(t){this.logger.error("Page-unload write hand-off failed:",t)}if(!this.canSend()||this.queue.isSuspended()||this.queue.isBackingOff())this.queue.persistNow();else try{this.sendAttributesAtUnload();const t=Math.max(0,this.network.keepaliveBudget()-256),i=this.queue.getQueuedEvents(),e=this.queue.getPendingIdentify();if(0===i.length&&!e)return;if(!this.network.supportsKeepalive())return void this.queue.persistNow();const s=i[0],n=!e||s&&(s.anonymousId!==e.anonymousId||s.userId&&s.userId!==e.userId)?null:e;let r=64+(n?vt(JSON.stringify(n)):0);const o=[];let h=null;for(const e of i){if(s&&e.anonymousId!==s.anonymousId)break;if(e.userId&&h&&e.userId!==h)break;if(n&&(e.anonymousId!==n.anonymousId||e.userId&&e.userId!==n.userId))break;const i=vt(JSON.stringify(e))+1;if(r+i>t)break;o.push(e),e.userId&&(h=e.userId),r+=i}if(0===o.length&&!n)return void this.queue.persistNow();this.logger.debug(`Page unload: handing ${o.length} of ${i.length} events${n?" + identify":""} to keepalive`);const a=this.network.sendEventsKeepalive(this.config.apiEndpoint,o,n||void 0);if(!a)return void this.queue.persistNow();this.queue.markHandedOff(o,n),a.then(t=>{t.ok||!t.softFailure&&0!==t.status&&429!==t.status&&500>t.status||this.queue.takeBack(o,n)}).catch(()=>{})}catch(t){this.logger.error("Page-unload send failed:",t),this.queue.persistNow()}}else this.queue.persistNow()}sendAttributesAtUnload(){var t;if(this.queue.getPendingIdentify())return 0;const i=this.identity.pending.peekRequest(t=>this.resolveOwner(null!=t?t:this.currentOwner()));if(!i||!this.network.supportsKeepalive())return 0;try{const e=this.resolveOwner(null!==(t=i.owner)&&void 0!==t?t:this.currentOwner()),s=Object.assign({userId:e.userId||void 0,anonymousId:e.userId?void 0:e.anonymousId},i.ops),n=this.network.postKeepalive(this.config.apiEndpoint+"/v1/attributes",s);return n?(n.catch(()=>{}),this.identity.pending.dropIncrements(i.entries),this.persistAttributeWrites(),vt(JSON.stringify(s))+256):0}catch(t){return 0}}optOut(){this.isInitialized?(this.logger.info("User opted out of tracking"),this.userOptedOut=!0,this.writeOptOut(),this.storage.remove(xe),this.syncOptOutMarker(),this.applyPrivacyState()):this.logger.error("SDK not initialized")}optIn(){this.isInitialized?(this.logger.info("User opted in to tracking"),this.userOptedOut=!1,this.liftDataGate("optedOut"),this.writeOptIn(),this.applyPrivacyState(),this.storage.remove(xe),this.syncOptOutMarker()):this.logger.error("SDK not initialized")}updateConsent(t){this.isInitialized?"granted"===t||"denied"===t||"pending"===t?(this.trackingConsent=this.storeConsent(t),this.config.trackingConsent=this.trackingConsent,"granted"===t&&this.liftDataGate("denied"),this.applyPrivacyState(),this.syncOptOutMarker()):this.logger.error("updateConsent expects 'granted', 'denied' or 'pending', got "+t):this.logger.error("SDK not initialized")}isDoNotTrackEnabled(){if("undefined"==typeof window||"undefined"==typeof navigator)return!1;const t=navigator.doNotTrack||window.doNotTrack||navigator.msDoNotTrack;return"1"===t||"yes"===t}async loadPlugins(){for(const t of this.config.plugins)try{this.logger.debug(`Loading plugin: ${t.name} v${t.version}`),await t.load(this),this.logger.info("Plugin loaded: "+t.name)}catch(i){this.logger.error(`Failed to load plugin ${t.name}:`,i)}}async unloadPlugins(){for(const t of this.config.plugins)try{this.logger.debug("Unloading plugin: "+t.name),await t.unload()}catch(i){this.logger.error(`Failed to unload plugin ${t.name}:`,i)}}get user(){var t;return this.isInitialized||null===(t=this.logger)||void 0===t||t.error("SDK not initialized"),this.o}get push(){var t;return this.isInitialized||null===(t=this.logger)||void 0===t||t.error("SDK not initialized"),this.i}ecommerce(t){var i;return this.isInitialized||null===(i=this.logger)||void 0===i||i.error("SDK not initialized"),this.t&&!t||(this.t=Vi(this,t,this.logger)),this.t}setSdkAuthenticationToken(t){var i;this.isInitialized?this.config.enableSdkAuthentication?this.network.setSdkAuthenticationToken(t):this.logger.warn("setSdkAuthenticationToken called but enableSdkAuthentication is false - ignoring"):null===(i=this.logger)||void 0===i||i.error("SDK not initialized")}setStorefrontIdentityToken(t){var i;this.isInitialized?this.network.setStorefrontIdentityToken(t):null===(i=this.logger)||void 0===i||i.error("SDK not initialized")}setStorefrontIdentityTokenProvider(t){var i;this.isInitialized?this.network.setStorefrontIdentityTokenProvider(t):null===(i=this.logger)||void 0===i||i.error("SDK not initialized")}setSdkAuthenticationErrorCallback(t){var i;this.isInitialized?this.network.setSdkAuthenticationFailureCallback(t):null===(i=this.logger)||void 0===i||i.error("SDK not initialized")}getAnonymousId(){return this.identity?this.identity.getAnonymousId():""}getUserId(){return this.identity?this.identity.getUserId():null}liftDataGate(t){if(!this.dataGate.has(t))return;const i=new Set(this.dataGate);i.delete(t),this.dataGate=i}isDroppingDataCalls(t){return 0!==this.dataGate.size&&(this.logger.debug(t+"() in a ready() callback queued while tracking was off: dropped"),!0)}ready(t){if("function"==typeof t)try{t(this)}catch(t){this.logger.error("Error in ready() callback:",t)}else this.logger.error("ready(callback) requires a function")}getIdentity(){return this.identity.getIdentity()}getSessionInfo(){return this.session.getSessionInfo()}getUTMData(){return this.utm.getUTMData()}updateUTM(){this.isInitialized?(this.utm.updateUTM(),this.config.resetSessionOnNewCampaign&&this.utm.hasNewCampaign()&&(this.logger.info("New campaign detected, resetting session"),this.session.resetSession())):this.logger.error("SDK not initialized")}async syncInAppCampaigns(t){if(this.isInitialized)if(this.config.inApp.enabled)if(this.canSend())try{await this.inapp.sync(t)}catch(t){this.logger.error("In-app sync failed:",t)}else this.logger.debug("Tracking disabled or consent pending, not syncing in-app campaigns");else this.logger.warn("In-app messaging is not enabled");else this.logger.error("SDK not initialized")}getInAppCampaigns(){return this.isInitialized?this.config.inApp.enabled?this.inapp.getCampaigns():[]:(this.logger.error("SDK not initialized"),[])}async displayInAppCampaign(t){if(!this.isInitialized)return void this.logger.error("SDK not initialized");if(!this.config.inApp.enabled)return void this.logger.warn("In-app messaging is not enabled");if(!this.canSend())return void this.logger.debug("Tracking disabled or consent pending, not displaying in-app campaign");const i=this.inapp.getCampaigns().find(i=>i.id===t);if(i)try{await this.inapp.displayCampaign(i)}catch(t){this.logger.error("In-app display failed:",t)}else this.logger.error(`Campaign ${t} not found`)}dismissInAppMessage(t){this.isInitialized?this.config.inApp.enabled&&this.inapp.dismiss(t).catch(t=>this.logger.error("In-app dismiss failed:",t)):this.logger.error("SDK not initialized")}async trackInAppConversion(t,i){if(this.isInitialized){if(!this.isDroppingDataCalls("trackInAppConversion"))if(this.config.inApp.enabled)if(this.canSend())try{await this.inapp.trackConversion(t,i)}catch(t){this.logger.error("In-app conversion failed:",t)}else this.logger.debug("Tracking disabled or consent pending, not tracking in-app conversion");else this.logger.warn("In-app messaging is not enabled")}else this.logger.error("SDK not initialized")}placementConsent(){return!this.isInitialized||this.disabled||this.network.isSuspended()?null:this.canSend()?"granted":this.consentPending?"pending":"denied"}setLinkHandler(t){var i;"function"==typeof t?this.links.setHandler(t):null===(i=this.logger)||void 0===i||i.warn("setLinkHandler() needs a function; use clearLinkHandler() to remove one")}clearLinkHandler(){this.links.setHandler(null)}setPageVariables(t){var i;try{null===(i=this.pageContext)||void 0===i||i.setPageVariables(t)}catch(t){this.logger.warn("setPageVariables failed:",t)}}insertPlacement(t,i,e){return this.isInitialized?this.placements.insertPlacement(t,i,e):(this.logger.error("SDK not initialized"),null)}async getPlacements(t){return this.isInitialized?this.placements.getPlacements(t):(this.logger.error("SDK not initialized"),{})}async refreshPlacements(t){this.isInitialized&&await this.placements.refreshPlacements(t)}onPlacementsUpdated(t){return this.isInitialized?this.placements.onPlacementsUpdated(t):(this.logger.error("SDK not initialized"),ei(()=>{}))}async getCards(t){return this.isInitialized?this.cards.getCards(t):(this.logger.error("SDK not initialized"),{cards:[],unreadCount:0,nextCursor:null,stateScope:"server"})}getUnreadCardCount(){return this.isInitialized?this.cards.getUnreadCardCount():0}markCardViewed(t){this.isInitialized&&this.cards.markCardViewed(t)}markCardRead(t){this.isInitialized&&this.cards.markCardRead(t)}markCardClicked(t){this.isInitialized&&this.cards.markCardClicked(t)}dismissCard(t){this.isInitialized&&this.cards.dismissCard(t)}async refreshCards(){this.isInitialized&&await this.cards.refreshCards()}onCardsUpdated(t){return this.isInitialized?this.cards.onCardsUpdated(t):(this.logger.error("SDK not initialized"),ei(()=>{}))}mountCardFeed(t,i){return this.isInitialized?this.cards.mountCardFeed(t,i):(this.logger.error("SDK not initialized"),null)}getFlag(t,i){return this.isInitialized?this.flags.getFlag(t,i):i}getBoolFlag(t,i){return this.isInitialized?this.flags.getBoolFlag(t,i):i}getStringFlag(t,i){return this.isInitialized?this.flags.getStringFlag(t,i):i}getNumberFlag(t,i){return this.isInitialized?this.flags.getNumberFlag(t,i):i}getJsonFlag(t,i){return this.isInitialized?this.flags.getJsonFlag(t,i):i}getAllFlags(){return this.isInitialized?this.flags.getAllFlags():{}}async refreshFlags(){this.isInitialized&&await this.flags.refreshFlags()}onFlagsUpdated(t){return this.isInitialized?this.flags.onFlagsUpdated(t):(this.logger.error("SDK not initialized"),ei(()=>{}))}async destroy(){var t,i,e;this.isInitialized&&(this.logger.info("Destroying SDK instance"),null!==this.attributeFlushTimer&&(clearTimeout(this.attributeFlushTimer),this.attributeFlushTimer=null,this.canSend()&&this.flushAttributeOps()),this.outbox.destroy(),this.i.destroy(),"undefined"!=typeof window&&"function"==typeof window.removeEventListener&&(this.boundHandlePageUnload&&(window.removeEventListener("pagehide",this.boundHandlePageUnload),window.removeEventListener("beforeunload",this.boundHandlePageUnload)),this.boundHandleOnline&&window.removeEventListener("online",this.boundHandleOnline),this.boundHandleStorage&&window.removeEventListener("storage",this.boundHandleStorage)),this.boundHandlePageUnload=null,this.boundHandleOnline=null,this.boundHandleStorage=null,null!==this.pruneTimer&&(clearTimeout(this.pruneTimer),this.pruneTimer=null),await this.queue.flush().catch(()=>{}),this.queue.stop(),await this.unloadPlugins(),this.session.destroy(),this.inapp.clearAll(),this.inapp.destroy(),this.placements.destroy(),this.cards.destroy(),null===(t=this.pageEdits)||void 0===t||t.destroy(),null===(i=this.editor)||void 0===i||i.stop(),null===(e=this.pageContext)||void 0===e||e.destroy(),this.flags.destroy(),this.isInitialized=!1,Xe.instance===this&&(Xe.instance=null),this.logger.info("SDK destroyed"))}static getInstance(){return Xe.instance}}Xe.instance=null,Xe.ATTRIBUTE_FLUSH_DEBOUNCE_MS=800;const Ge=["init","optOut","optIn","updateConsent","wipeData"],Qe=["track","setAttributes","setAttribute","incrementAttribute","unsetAttribute","addToArray","removeFromArray","addAlias","trackInAppConversion"];function Ze(t){var i,e;try{const s=t&&t.joryio;if(!Array.isArray(s))return;const n=s.find(t=>Array.isArray(t)&&"init"===t[0]);if(!n){if(s.__joryioWaitingForInit)return;return s.__joryioWaitingForInit=!0,void(s.push=function(...i){for(let t=s.length+i.length-1e3;t>0;t--){const t=s.findIndex(t=>!(Array.isArray(t)&&Ge.includes(t[0])));if(0>t)break;s.splice(t,1)}const e=Array.prototype.push.apply(s,i);return i.some(t=>Array.isArray(t)&&"init"===t[0])&&Ze(t),e})}const r=s.slice(),o=r.indexOf(n),h=[],a=new Set;r.forEach((t,i)=>{if(!Array.isArray(t))return;const[e,s]=t;if("optOut"===e||"optIn"===e)h.push({method:e});else if("updateConsent"===e)h.push({method:e,consent:s});else{if("wipeData"!==e||i>=o)return;h.push({method:e})}a.add(t)});let l=null;try{l=new Xe(n[1],h)}catch(t){console.error("[Joryio] init failed:",t)}if(!l||Xe.getInstance()!==l){const i=s.indexOf(n);return 0>i||s.splice(i,1),s.__joryioWaitingForInit=!1,void Ze(t)}const u=new Map,c=function(t,i,e=t.length,s=new Map){const n=new Set,r=(t,i)=>{n.add(t);const e=s.get(t)||new Set;e.add(i),s.set(t,e)};let o=!!(null==i?void 0:i.optedOut),h=(null==i?void 0:i.consent)||"granted";const a=[],l=(t=!1)=>{const i=a.filter(i=>t&&"ready"===i[0]);a.forEach(t=>{i.includes(t)||r(t,"purged")}),a.length=0,a.push(...i)};return t.forEach((t,i)=>{if(!Array.isArray(t))return;const[s,n]=t;"optOut"===s?(o=!0,l()):"optIn"===s?o=!1:"updateConsent"===s?("granted"===n||"denied"===n?h=n:"pending"===n&&"denied"!==h&&(h="pending"),"denied"===n&&l()):"wipeData"===s&&e>i?l(!0):(Qe.includes(s)||"ready"===s)&&(o&&r(t,"optedOut"),"denied"===h&&r(t,"denied"),o||"denied"===h||a.push(t))}),n}(r,qe.get(l),o,u);t.joryio=l;for(const t of r){if(!Array.isArray(t)||a.has(t))continue;const[s,...n]=t;if("init"===s)continue;const r=c.has(t);if(r&&"ready"!==s){null===(e=null===(i=l.logger)||void 0===i?void 0:i.debug)||void 0===e||e.call(i,s+" queued before load dropped: tracking was off when it was called");continue}const o=l[s];if("function"==typeof o)try{let i;r?ze(l,u.get(t)||[],()=>i=o.apply(l,n)):i=o.apply(l,n),i&&"function"==typeof i.catch&&i.catch(t=>{console.error(`[Joryio] Error executing ${s+""}:`,t)})}catch(t){console.error(`[Joryio] Error executing ${s+""}:`,t)}else console.warn("[Joryio] Unknown method queued before load: "+s)}}catch(t){console.error("[Joryio] Could not process the snippet queue:",t)}}return"undefined"!=typeof window&&(window.Joryio=Xe,Ze(window)),t.CARD_FEED_TTL_SECONDS=gi,t.CARD_MIN_REFRESH_SECONDS=30,t.EcommerceTracker=Bi,t.FLAGS_MIN_REFRESH_SECONDS=60,t.FLAG_SYNC_PUSH_VALUE="flags",t.IN_APP_DISPLAY_DWELL_MS=Bt,t.JoryioSDK=Xe,t.PLACEMENT_MIN_REFRESH_SECONDS=30,t.PLACEMENT_PRODUCT_CARD_WIDTH=160,t.PLACEMENT_PRODUCT_ELEMENT_PREFIX=si,t.PLACEMENT_VIEWABLE_FRACTION=.5,t.PushManager=oe,t.SDK_VERSION=s,t.User=Ui,t.createEcommerceTracker=Vi,t.default=Xe,t.installSnippetQueue=Ze,t.placementProductElementId=ni,Object.defineProperty(t,"__esModule",{value:!0}),function(t,i){if("object"==typeof module&&module&&"object"==typeof module.exports)module.exports=i;else if(t&&(t.JoryioSDK=i),"function"==typeof define&&define.amd){var e="undefined"!=typeof document?document.currentScript:null;e&&"function"==typeof e.getAttribute&&e.getAttribute("data-requiremodule")?define(function(){return i}):define("joryio-web-sdk",[],function(){return i})}}("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:null,t),t}({});
7
7
  //# sourceMappingURL=joryio.min.js.map