@syntrologie/runtime-sdk 2.8.0-canary.74 → 2.8.0-canary.76

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.
@@ -165,7 +165,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
165
165
  s.textContent = '.${e} { ${a} }';
166
166
  document.head.appendChild(s);
167
167
  document.documentElement.className += ' ${e}';
168
- })();`}function Zf(t,e,a="merge"){return a==="first-match"?sP(t,e):lP(t,e)}function sP(t,e){for(let a of e){let r=t.getFeatureValue?.(a,null);if(!r||typeof r!="object")continue;let n=r,o=n.tiles&&n.tiles.length>0,i=n.actions&&n.actions.length>0;if(o||i)return N1([n])}return null}function lP(t,e){let a=[];for(let r of e){let n=t.getFeatureValue?.(r,null);if(!n||typeof n!="object")continue;let o=n,i=o.tiles&&o.tiles.length>0,s=o.actions&&o.actions.length>0;(i||s)&&a.push(o)}return a.length===0?null:N1(a)}function N1(t){let e=[],a=[],r,n,o,i,s,l,u;for(let c of t)c.tiles&&e.push(...c.tiles),c.actions&&a.push(...c.actions),r??(r=c.fetchedAt),n??(n=c.schemaVersion),o??(o=c.configVersion),i??(i=c.canvasTitle),s??(s=c.theme),l??(l=c.launcher),u??(u=c.meta);return{tiles:e,actions:a,fetchedAt:r??new Date().toISOString(),...n&&{schemaVersion:n},...o&&{configVersion:o},...i&&{canvasTitle:i},...s&&{theme:s},...l&&{launcher:l},...u&&{meta:u}}}var ty=!1;function F1(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function ay(t){if(F1()){ty=!0;return}ty=t??!1}function uP(){return F1()?!0:ty}function K(t,e,a){uP()&&(a!==void 0?console.log(`[${t}]`,e,a):console.log(`[${t}]`,e))}function na(t,e,a){a!==void 0?console.warn(`[${t}]`,e,a):console.warn(`[${t}]`,e)}function Xf(t,e,a){a!==void 0?console.error(`[${t}]`,e,a):console.error(`[${t}]`,e)}var ry="2.8.0-canary.74";var eo="2.0";var cP=["api.syntrologie.com","cdn.syntrologie.com","localhost","127.0.0.1"];function dP(t){try{let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(console.warn("[SmartCanvas] Config URI must use HTTPS:",t),!1):cP.some(n=>e.hostname===n)?!0:(console.warn("[SmartCanvas] Config URI host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid config URI:",t),!1}}function fP(t){if(typeof window>"u")return!1;try{return new URL(t).origin===window.location.origin}catch{return!1}}var H1="syntro_config_cache",pP=1440*60*1e3;function U1(){try{return typeof localStorage<"u"&&localStorage!==null}catch{return!1}}function hP(t,e){if(U1())try{let a={config:t,timestamp:Date.now(),sdkVersion:e};localStorage.setItem(H1,JSON.stringify(a))}catch{}}function mP(t){if(!U1())return null;try{let e=localStorage.getItem(H1);if(!e)return null;let a=JSON.parse(e);return!a.config||typeof a.timestamp!="number"||!a.sdkVersion||a.sdkVersion!==t||Date.now()-a.timestamp>pP?null:a.config}catch{return null}}var ny=({configUri:t,experiments:e,featureKey:a})=>{if(t)return t;if(e&&a){let r=e.getFeatureValue?.(a,null);if(r)return r}};function gP(t,e,a){if(e){let r=t.getFeatureValue?.(e,null);if(r&&typeof r=="object"){let n=r.variant_flags;if(n&&n.length>0)return n}}if(t.getAllFeatures){let r=t.getAllFeatures();return a?Object.keys(r).filter(n=>n.startsWith(a)):Object.keys(r)}return[]}var Cs=({configUri:t,experiments:e,featureKey:a,credentials:r,configFeatureKey:n,manifestKey:o,variantFlagPrefix:i,sdkVersion:s})=>async()=>{if(e&&n){let c=e.getFeatureValue?.(n,null);if(c&&typeof c=="object")return K("SmartCanvas Config","Resolved config directly from feature flag",c),c}if(e&&(o||i||e.getAllFeatures)){let c=gP(e,o,i);if(c.length>0){let d=Zf(e,c);if(d)return K("SmartCanvas Config","Resolved config from variant flags",d),d}}let l=ny({configUri:t,experiments:e,featureKey:a});if(!l)return K("SmartCanvas Config","No config available \u2014 returning empty config"),{tiles:[],actions:[],fetchedAt:new Date().toISOString()};if(!dP(l))throw new Error(`SmartCanvas: config URI not allowed: ${l}`);let u=r??(fP(l)?"include":"omit");try{let c=await fetch(l,{credentials:u,headers:{"X-SDK-Version":ry,"X-SDK-Schema-Version":eo}});if(!c.ok)throw new Error(`SmartCanvas: failed to fetch config (${c.status})`);let d=await c.json();return K("SmartCanvas Config","Fetched config from URI",d),s&&hP(d,s),d}catch(c){if(s){let d=mP(s);if(d)return K("SmartCanvas Config","Serving config from offline cache"),d}throw c}};var vP=["cdn.syntrologie.com","api.syntrologie.com","dev-api.syntrologie.com","localhost","127.0.0.1",".syntrologie.com"];function z1(t){if(typeof window>"u")return null;let a=new URLSearchParams(window.location.search).get(t);if(!a)return null;try{let r=a.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(r))}catch(r){return na("Syntro Runtime",`Failed to decode ${t}:`,r),null}}var ws,Ls;function Su(){if(ws==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.token)ws={token:t.token,api_base:t.apiBase||""},console.log(`[DIAG] getEditorSource: from __SYNTRO_EDITOR_PARAMS__ (token=${ws.token.slice(0,15)}...)`);else{let e=z1("editor_source");e&&(ws=e),console.log(`[DIAG] getEditorSource: from URL param \u2192 ${e?`token=${e.token?.slice(0,15)}...`:"NULL"}`),!e&&typeof window<"u"&&console.log(`[DIAG] getEditorSource: URL search = ${window.location.search.slice(0,200)}`)}}return ws??null}function Kf(){if(Ls==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.mode)Ls={mode:t.mode,audit_session_id:t.auditSessionId,syntro_token:t.syntroToken,workspace_id:t.workspaceId},console.log(`[DIAG] getEditorConf: from __SYNTRO_EDITOR_PARAMS__ (mode=${Ls.mode})`);else{let e=z1("editor_conf");e&&(Ls=e),console.log(`[DIAG] getEditorConf: from URL param \u2192 ${e?`mode=${e.mode}`:"NULL"}`)}}return Ls??null}function yP(t){K("Syntro Runtime","Validating editor URL:",t);try{if(t.startsWith("/"))return K("Syntro Runtime","\u2713 Relative URL allowed (same-origin):",t),!0;let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(na("Syntro Runtime","\u274C Editor URL must use HTTPS:",t),!1):vP.some(n=>n.startsWith(".")?e.hostname.endsWith(n)||e.hostname===n.slice(1):e.hostname===n)?(K("Syntro Runtime","\u2713 Editor URL validated"),!0):(na("Syntro Runtime","\u274C Editor URL host not in allowlist:",e.hostname),!1)}catch(e){return na("Syntro Runtime",`\u274C Invalid editor URL: ${t}`,e),!1}}var Yf=()=>{let t=Kf();return!Su()?.token||!t?.mode?null:t.mode};function xP(){return Su()?.token??null}function bP(){return Su()?.api_base??null}var bu=null,q1=async t=>{if(K("Syntro Runtime","====== LOAD EDITOR SDK ======"),typeof window>"u"){K("Syntro Runtime","Not in browser - skipping editor SDK load");return}if(window.SyntroEditor){K("Syntro Runtime","Editor SDK already loaded (window.SyntroEditor exists)");return}if(bu)return K("Syntro Runtime","Editor SDK load already in progress, waiting..."),bu;let e=typeof t=="string"?{editorUrl:t}:t??{};if(e.editorUrl==="skip"){K("Syntro Runtime",'editorUrl="skip" \u2014 deferring to caller'),K("Syntro Runtime","================================");return}let a=bP(),n=(a?`${a}/api/editor/sdk/editor-sdk.js`:null)||e.editorUrl;if(!n){na("Syntro Runtime","\u274C No editor SDK URL available (no api_base, no editorUrl option)"),K("Syntro Runtime","================================");return}let o=xP();if(!o){na("Syntro Runtime","\u274C No token found in editor_source."),K("Syntro Runtime","================================");return}let i=`${n}?token=${encodeURIComponent(o)}`;if(K("Syntro Runtime","Editor URL:",i),K("Syntro Runtime","Options:",{hasIntegrity:!!e.integrity,hasEditorUrl:!!n,hasApiBase:!!a,tokenPrefix:`${o.slice(0,10)}...`}),!yP(n)){console.error("[Syntro Runtime] \u274C BLOCKED: Editor from untrusted URL:",n),K("Syntro Runtime","================================");return}return K("Syntro Runtime","\u2713 URL validated, injecting script tag..."),bu=new Promise((s,l)=>{let u=document.createElement("script");u.src=i,u.async=!0,e.integrity&&(u.integrity=e.integrity,u.crossOrigin="anonymous",K("Syntro Runtime","SRI integrity check enabled")),u.onload=()=>{K("Syntro Runtime","\u2713 Editor SDK script loaded successfully"),K("Syntro Runtime","================================"),s()},u.onerror=c=>{console.error("[Syntro Runtime] \u274C Failed to load Editor SDK:",c),console.error("[Syntro Runtime] URL attempted:",i),K("Syntro Runtime","================================"),bu=null,l(c)},document.head.appendChild(u),K("Syntro Runtime","Script tag appended to <head>")}),bu};var SP=new Set(["tag_name","$el_text"]);function _P(t){return SP.has(t)||t.startsWith("attr__")}function V1(t,e){return t.equals!==void 0?e===t.equals:t.contains!==void 0?typeof e=="string"&&e.includes(t.contains):!1}function CP(t){let{events:e,match:a}=t;return r=>{if(!e.includes(r.name))return!1;if(a){for(let[n,o]of Object.entries(a))if(_P(n)){let i=r.props?.elements;if(!i||!i.some(l=>V1(o,l[n])))return!1}else if(!V1(o,r.props?.[n]))return!1}return!0}}function $1(t,e){for(let a of t.rules)for(let r of a.conditions)if(r.type==="event_count"&&r.key){let n=r.counter,o=n?CP(n):()=>!0,i=typeof r.withinMs=="number";e.register(r.key,o,i)}}function Qf(t,e,a){for(let r of t){let n=r.props;if(!n)continue;let o=n.actions;if(o)for(let i of o)i.triggerWhen?.type==="rules"&&$1(i.triggerWhen,e)}if(a)for(let r of a){let n=r;n.triggerWhen?.type==="rules"&&$1(n.triggerWhen,e)}}var Sr=null;function G1(t){Sr&&Sr!==t?t.appendChild(Sr):Sr=t;let e=t.getRootNode();e instanceof ShadowRoot&&wP(e)}function W1(){return Sr||(Sr=document.createElement("div"),Sr.id="syntro-overlays",Object.assign(Sr.style,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"}),document.body.appendChild(Sr)),Sr}var j1=!1;function wP(t){if(j1)return;let e=`
168
+ })();`}function Zf(t,e,a="merge"){return a==="first-match"?sP(t,e):lP(t,e)}function sP(t,e){for(let a of e){let r=t.getFeatureValue?.(a,null);if(!r||typeof r!="object")continue;let n=r,o=n.tiles&&n.tiles.length>0,i=n.actions&&n.actions.length>0;if(o||i)return N1([n])}return null}function lP(t,e){let a=[];for(let r of e){let n=t.getFeatureValue?.(r,null);if(!n||typeof n!="object")continue;let o=n,i=o.tiles&&o.tiles.length>0,s=o.actions&&o.actions.length>0;(i||s)&&a.push(o)}return a.length===0?null:N1(a)}function N1(t){let e=[],a=[],r,n,o,i,s,l,u;for(let c of t)c.tiles&&e.push(...c.tiles),c.actions&&a.push(...c.actions),r??(r=c.fetchedAt),n??(n=c.schemaVersion),o??(o=c.configVersion),i??(i=c.canvasTitle),s??(s=c.theme),l??(l=c.launcher),u??(u=c.meta);return{tiles:e,actions:a,fetchedAt:r??new Date().toISOString(),...n&&{schemaVersion:n},...o&&{configVersion:o},...i&&{canvasTitle:i},...s&&{theme:s},...l&&{launcher:l},...u&&{meta:u}}}var ty=!1;function F1(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function ay(t){if(F1()){ty=!0;return}ty=t??!1}function uP(){return F1()?!0:ty}function K(t,e,a){uP()&&(a!==void 0?console.log(`[${t}]`,e,a):console.log(`[${t}]`,e))}function na(t,e,a){a!==void 0?console.warn(`[${t}]`,e,a):console.warn(`[${t}]`,e)}function Xf(t,e,a){a!==void 0?console.error(`[${t}]`,e,a):console.error(`[${t}]`,e)}var ry="2.8.0-canary.76";var eo="2.0";var cP=["api.syntrologie.com","cdn.syntrologie.com","localhost","127.0.0.1"];function dP(t){try{let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(console.warn("[SmartCanvas] Config URI must use HTTPS:",t),!1):cP.some(n=>e.hostname===n)?!0:(console.warn("[SmartCanvas] Config URI host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid config URI:",t),!1}}function fP(t){if(typeof window>"u")return!1;try{return new URL(t).origin===window.location.origin}catch{return!1}}var H1="syntro_config_cache",pP=1440*60*1e3;function U1(){try{return typeof localStorage<"u"&&localStorage!==null}catch{return!1}}function hP(t,e){if(U1())try{let a={config:t,timestamp:Date.now(),sdkVersion:e};localStorage.setItem(H1,JSON.stringify(a))}catch{}}function mP(t){if(!U1())return null;try{let e=localStorage.getItem(H1);if(!e)return null;let a=JSON.parse(e);return!a.config||typeof a.timestamp!="number"||!a.sdkVersion||a.sdkVersion!==t||Date.now()-a.timestamp>pP?null:a.config}catch{return null}}var ny=({configUri:t,experiments:e,featureKey:a})=>{if(t)return t;if(e&&a){let r=e.getFeatureValue?.(a,null);if(r)return r}};function gP(t,e,a){if(e){let r=t.getFeatureValue?.(e,null);if(r&&typeof r=="object"){let n=r.variant_flags;if(n&&n.length>0)return n}}if(t.getAllFeatures){let r=t.getAllFeatures();return a?Object.keys(r).filter(n=>n.startsWith(a)):Object.keys(r)}return[]}var Cs=({configUri:t,experiments:e,featureKey:a,credentials:r,configFeatureKey:n,manifestKey:o,variantFlagPrefix:i,sdkVersion:s})=>async()=>{if(e&&n){let c=e.getFeatureValue?.(n,null);if(c&&typeof c=="object")return K("SmartCanvas Config","Resolved config directly from feature flag",c),c}if(e&&(o||i||e.getAllFeatures)){let c=gP(e,o,i);if(c.length>0){let d=Zf(e,c);if(d)return K("SmartCanvas Config","Resolved config from variant flags",d),d}}let l=ny({configUri:t,experiments:e,featureKey:a});if(!l)return K("SmartCanvas Config","No config available \u2014 returning empty config"),{tiles:[],actions:[],fetchedAt:new Date().toISOString()};if(!dP(l))throw new Error(`SmartCanvas: config URI not allowed: ${l}`);let u=r??(fP(l)?"include":"omit");try{let c=await fetch(l,{credentials:u,headers:{"X-SDK-Version":ry,"X-SDK-Schema-Version":eo}});if(!c.ok)throw new Error(`SmartCanvas: failed to fetch config (${c.status})`);let d=await c.json();return K("SmartCanvas Config","Fetched config from URI",d),s&&hP(d,s),d}catch(c){if(s){let d=mP(s);if(d)return K("SmartCanvas Config","Serving config from offline cache"),d}throw c}};var vP=["cdn.syntrologie.com","api.syntrologie.com","dev-api.syntrologie.com","localhost","127.0.0.1",".syntrologie.com"];function z1(t){if(typeof window>"u")return null;let a=new URLSearchParams(window.location.search).get(t);if(!a)return null;try{let r=a.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(r))}catch(r){return na("Syntro Runtime",`Failed to decode ${t}:`,r),null}}var ws,Ls;function Su(){if(ws==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.token)ws={token:t.token,api_base:t.apiBase||""},console.log(`[DIAG] getEditorSource: from __SYNTRO_EDITOR_PARAMS__ (token=${ws.token.slice(0,15)}...)`);else{let e=z1("editor_source");e&&(ws=e),console.log(`[DIAG] getEditorSource: from URL param \u2192 ${e?`token=${e.token?.slice(0,15)}...`:"NULL"}`),!e&&typeof window<"u"&&console.log(`[DIAG] getEditorSource: URL search = ${window.location.search.slice(0,200)}`)}}return ws??null}function Kf(){if(Ls==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.mode)Ls={mode:t.mode,audit_session_id:t.auditSessionId,syntro_token:t.syntroToken,workspace_id:t.workspaceId},console.log(`[DIAG] getEditorConf: from __SYNTRO_EDITOR_PARAMS__ (mode=${Ls.mode})`);else{let e=z1("editor_conf");e&&(Ls=e),console.log(`[DIAG] getEditorConf: from URL param \u2192 ${e?`mode=${e.mode}`:"NULL"}`)}}return Ls??null}function yP(t){K("Syntro Runtime","Validating editor URL:",t);try{if(t.startsWith("/"))return K("Syntro Runtime","\u2713 Relative URL allowed (same-origin):",t),!0;let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(na("Syntro Runtime","\u274C Editor URL must use HTTPS:",t),!1):vP.some(n=>n.startsWith(".")?e.hostname.endsWith(n)||e.hostname===n.slice(1):e.hostname===n)?(K("Syntro Runtime","\u2713 Editor URL validated"),!0):(na("Syntro Runtime","\u274C Editor URL host not in allowlist:",e.hostname),!1)}catch(e){return na("Syntro Runtime",`\u274C Invalid editor URL: ${t}`,e),!1}}var Yf=()=>{let t=Kf();return!Su()?.token||!t?.mode?null:t.mode};function xP(){return Su()?.token??null}function bP(){return Su()?.api_base??null}var bu=null,q1=async t=>{if(K("Syntro Runtime","====== LOAD EDITOR SDK ======"),typeof window>"u"){K("Syntro Runtime","Not in browser - skipping editor SDK load");return}if(window.SyntroEditor){K("Syntro Runtime","Editor SDK already loaded (window.SyntroEditor exists)");return}if(bu)return K("Syntro Runtime","Editor SDK load already in progress, waiting..."),bu;let e=typeof t=="string"?{editorUrl:t}:t??{};if(e.editorUrl==="skip"){K("Syntro Runtime",'editorUrl="skip" \u2014 deferring to caller'),K("Syntro Runtime","================================");return}let a=bP(),n=(a?`${a}/api/editor/sdk/editor-sdk.js`:null)||e.editorUrl;if(!n){na("Syntro Runtime","\u274C No editor SDK URL available (no api_base, no editorUrl option)"),K("Syntro Runtime","================================");return}let o=xP();if(!o){na("Syntro Runtime","\u274C No token found in editor_source."),K("Syntro Runtime","================================");return}let i=`${n}?token=${encodeURIComponent(o)}`;if(K("Syntro Runtime","Editor URL:",i),K("Syntro Runtime","Options:",{hasIntegrity:!!e.integrity,hasEditorUrl:!!n,hasApiBase:!!a,tokenPrefix:`${o.slice(0,10)}...`}),!yP(n)){console.error("[Syntro Runtime] \u274C BLOCKED: Editor from untrusted URL:",n),K("Syntro Runtime","================================");return}return K("Syntro Runtime","\u2713 URL validated, injecting script tag..."),bu=new Promise((s,l)=>{let u=document.createElement("script");u.src=i,u.async=!0,e.integrity&&(u.integrity=e.integrity,u.crossOrigin="anonymous",K("Syntro Runtime","SRI integrity check enabled")),u.onload=()=>{K("Syntro Runtime","\u2713 Editor SDK script loaded successfully"),K("Syntro Runtime","================================"),s()},u.onerror=c=>{console.error("[Syntro Runtime] \u274C Failed to load Editor SDK:",c),console.error("[Syntro Runtime] URL attempted:",i),K("Syntro Runtime","================================"),bu=null,l(c)},document.head.appendChild(u),K("Syntro Runtime","Script tag appended to <head>")}),bu};var SP=new Set(["tag_name","$el_text"]);function _P(t){return SP.has(t)||t.startsWith("attr__")}function V1(t,e){return t.equals!==void 0?e===t.equals:t.contains!==void 0?typeof e=="string"&&e.includes(t.contains):!1}function CP(t){let{events:e,match:a}=t;return r=>{if(!e.includes(r.name))return!1;if(a){for(let[n,o]of Object.entries(a))if(_P(n)){let i=r.props?.elements;if(!i||!i.some(l=>V1(o,l[n])))return!1}else if(!V1(o,r.props?.[n]))return!1}return!0}}function $1(t,e){for(let a of t.rules)for(let r of a.conditions)if(r.type==="event_count"&&r.key){let n=r.counter,o=n?CP(n):()=>!0,i=typeof r.withinMs=="number";e.register(r.key,o,i)}}function Qf(t,e,a){for(let r of t){let n=r.props;if(!n)continue;let o=n.actions;if(o)for(let i of o)i.triggerWhen?.type==="rules"&&$1(i.triggerWhen,e)}if(a)for(let r of a){let n=r;n.triggerWhen?.type==="rules"&&$1(n.triggerWhen,e)}}var Sr=null;function G1(t){Sr&&Sr!==t?t.appendChild(Sr):Sr=t;let e=t.getRootNode();e instanceof ShadowRoot&&wP(e)}function W1(){return Sr||(Sr=document.createElement("div"),Sr.id="syntro-overlays",Object.assign(Sr.style,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"}),document.body.appendChild(Sr)),Sr}var j1=!1;function wP(t){if(j1)return;let e=`
169
169
  :host {
170
170
  --syntro-surface: var(--sc-overlay-background, #0f1318);
171
171
  --syntro-fg: var(--sc-overlay-text-color, #cbd0d7);
@@ -500,7 +500,7 @@ ${l}
500
500
  `).replace(/\r/g,`
501
501
  `)).length,n=0;n<r;n++){var i=t.charCodeAt(n),s=null;i<128?a++:s=i>127&&i<2048?String.fromCharCode(i>>6|192,63&i|128):String.fromCharCode(i>>12|224,i>>6&63|128,63&i|128),cr(s)||(a>e&&(o+=t.substring(e,a)),o+=s,e=a=n+1)}return a>e&&(o+=t.substring(e,t.length)),o},a4=!!Sx||!!bx,nE="text/plain",oh=function(t,e,a){var r;a===void 0&&(a=!0);var[n,o]=t.split("?"),i=j({},e),s=(r=o?.split("&").map((u=>{var c,[d,f]=u.split("="),h=a&&(c=i[d])!==null&&c!==void 0?c:f;return delete i[d],d+"="+h})))!==null&&r!==void 0?r:[],l=E3(i);return l&&s.push(l),n+"?"+s.join("&")},dc=(t,e)=>JSON.stringify(t,((a,r)=>typeof r=="bigint"?r.toString():r),e),px=t=>{var{data:e,compression:a}=t;if(e){if(a===mn.GZipJS){var r=e4((function(l,u){var c=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var d=new ja(l.length+(l.length>>>1)),f=0,h=function(g){d[f++]=g},S=0;S<c;++S){if(f+5>d.length){var x=new ja(f+8+(c-S<<1));x.set(d),d=x}var b=l.charCodeAt(S);b<128||u?h(b):b<2048?(h(192|b>>>6),h(128|63&b)):b>55295&&b<57344?(h(240|(b=65536+(1047552&b)|1023&l.charCodeAt(++S))>>>18),h(128|b>>>12&63),h(128|b>>>6&63),h(128|63&b)):(h(224|b>>>12),h(128|b>>>6&63),h(128|63&b))}return vT(d,0,f)})(dc(e)),{mtime:0}),n=new Blob([r],{type:nE});return{contentType:nE,body:n,estimatedSize:n.size}}if(a===mn.Base64){var o=(function(l){var u,c,d,f,h,S="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",x=0,b=0,g="",m=[];if(!l)return l;l=t4(l);do u=(h=l.charCodeAt(x++)<<16|l.charCodeAt(x++)<<8|l.charCodeAt(x++))>>18&63,c=h>>12&63,d=h>>6&63,f=63&h,m[b++]=S.charAt(u)+S.charAt(c)+S.charAt(d)+S.charAt(f);while(x<l.length);switch(g=m.join(""),l.length%3){case 1:g=g.slice(0,-2)+"==";break;case 2:g=g.slice(0,-1)+"="}return g})(dc(e)),i=(l=>"data="+encodeURIComponent(typeof l=="string"?l:dc(l)))(o);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var s=dc(e);return{contentType:"application/json",body:s,estimatedSize:new Blob([s]).size}}},qp=[];bx&&qp.push({transport:"fetch",method:t=>{var e,a,{contentType:r,body:n,estimatedSize:o}=(e=px(t))!==null&&e!==void 0?e:{},i=new Headers;Be(t.headers,(function(c,d){i.append(d,c)})),r&&i.append("Content-Type",r);var s=t.url,l=null;if(wA){var u=new wA;l={signal:u.signal,timeout:setTimeout((()=>u.abort()),t.timeout)}}bx(s,j({method:t?.method||"GET",headers:i,keepalive:t.method==="POST"&&(o||0)<52428.8,body:n,signal:(a=l)==null?void 0:a.signal},t.fetchOptions)).then((c=>c.text().then((d=>{var f={statusCode:c.status,text:d};if(c.status===200)try{f.json=JSON.parse(d)}catch(h){$.error(h)}t.callback==null||t.callback(f)})))).catch((c=>{$.error(c),t.callback==null||t.callback({statusCode:0,text:c})})).finally((()=>l?clearTimeout(l.timeout):null))}}),Sx&&qp.push({transport:"XHR",method:t=>{var e,a=new Sx;a.open(t.method||"GET",t.url,!0);var{contentType:r,body:n}=(e=px(t))!==null&&e!==void 0?e:{};Be(t.headers,(function(o,i){a.setRequestHeader(i,o)})),r&&a.setRequestHeader("Content-Type",r),t.timeout&&(a.timeout=t.timeout),t.disableXHRCredentials||(a.withCredentials=!0),a.onreadystatechange=()=>{if(a.readyState===4){var o={statusCode:a.status,text:a.responseText};if(a.status===200)try{o.json=JSON.parse(a.responseText)}catch{}t.callback==null||t.callback(o)}},a.send(n)}}),ka!=null&&ka.sendBeacon&&qp.push({transport:"sendBeacon",method:t=>{var e=oh(t.url,{beacon:"1"});try{var a,{contentType:r,body:n}=(a=px(t))!==null&&a!==void 0?a:{},o=typeof n=="string"?new Blob([n],{type:r}):n;ka.sendBeacon(e,o)}catch{}}});var ih=function(t,e){if(!(function(a){try{new RegExp(a)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function oE(t,e,a){return dc({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:a})}var yT={exact:(t,e)=>e.some((a=>t.some((r=>a===r)))),is_not:(t,e)=>e.every((a=>t.every((r=>a!==r)))),regex:(t,e)=>e.some((a=>t.some((r=>ih(a,r))))),not_regex:(t,e)=>e.every((a=>t.every((r=>!ih(a,r))))),icontains:(t,e)=>e.map(Up).some((a=>t.map(Up).some((r=>a.includes(r))))),not_icontains:(t,e)=>e.map(Up).every((a=>t.map(Up).every((r=>!a.includes(r))))),gt:(t,e)=>e.some((a=>{var r=parseFloat(a);return!isNaN(r)&&t.some((n=>r>parseFloat(n)))})),lt:(t,e)=>e.some((a=>{var r=parseFloat(a);return!isNaN(r)&&t.some((n=>r<parseFloat(n)))}))},Up=t=>t.toLowerCase();function xT(t,e){return!t||Object.entries(t).every((a=>{var[r,n]=a,o=e?.[r];if(V(o)||cr(o))return!1;var i=[String(o)],s=yT[n.operator];return!!s&&s(n.values,i)}))}var hx=et("[Error tracking]"),cb=class{constructor(e){var a,r;this.Zt=[],this.ti=new Ex([new Rx,new Fx,new Ox,new Mx,new Px,new Bx,new Dx,new Nx],d3()),this._instance=e,this.Zt=(a=(r=this._instance.persistence)==null?void 0:r.get_property(Ux))!==null&&a!==void 0?a:[]}onRemoteConfig(e){var a,r,n,o=(a=(r=e.errorTracking)==null?void 0:r.suppressionRules)!==null&&a!==void 0?a:[],i=(n=e.errorTracking)==null?void 0:n.captureExtensionExceptions;this.Zt=o,this._instance.persistence&&this._instance.persistence.register({[Ux]:this.Zt,[NA]:i})}get ii(){var e,a=!!this._instance.get_property(NA),r=this._instance.config.error_tracking.captureExtensionExceptions;return(e=r??a)!==null&&e!==void 0&&e}buildProperties(e,a){return this.ti.buildFromUnknown(e,{syntheticException:a?.syntheticException,mechanism:{handled:a?.handled}})}sendExceptionEvent(e){var a=e.$exception_list;if(this.ei(a)){if(this.ri(a))return void hx.info("Skipping exception capture because a suppression rule matched");if(!this.ii&&this.si(a))return void hx.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ni(a))return void hx.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"})}ri(e){if(e.length===0)return!1;var a=e.reduce(((r,n)=>{var{type:o,value:i}=n;return vt(o)&&o.length>0&&r.$exception_types.push(o),vt(i)&&i.length>0&&r.$exception_values.push(i),r}),{$exception_types:[],$exception_values:[]});return this.Zt.some((r=>{var n=r.values.map((o=>{var i,s=yT[o.operator],l=Ce(o.value)?o.value:[o.value],u=(i=a[o.key])!==null&&i!==void 0?i:[];return l.length>0&&s(l,u)}));return r.type==="OR"?n.some(Boolean):n.every(Boolean)}))}si(e){return e.flatMap((a=>{var r,n;return(r=(n=a.stacktrace)==null?void 0:n.frames)!==null&&r!==void 0?r:[]})).some((a=>a.filename&&a.filename.startsWith("chrome-extension://")))}ni(e){if(e.length>0){var a,r,n,o,i=(a=(r=e[0].stacktrace)==null?void 0:r.frames)!==null&&a!==void 0?a:[],s=i[i.length-1];return(n=s==null||(o=s.filename)==null?void 0:o.includes("posthog.com/static"))!==null&&n!==void 0&&n}return!1}ei(e){return!ge(e)&&Ce(e)}},La=et("[FeatureFlags]"),ac=et("[FeatureFlags]",{debugEnabled:!0}),mx="$active_feature_flags",$s="$override_feature_flags",iE="$feature_flag_payloads",rc="$override_feature_flag_payloads",sE="$feature_flag_request_id",lE="$feature_flag_evaluated_at",uE=t=>{var e={};for(var[a,r]of zp(t||{}))r&&(e[a]=r);return e},r4=t=>{var e=t.flags;return e?(t.featureFlags=Object.fromEntries(Object.keys(e).map((a=>{var r;return[a,(r=e[a].variant)!==null&&r!==void 0?r:e[a].enabled]}))),t.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter((a=>e[a].enabled)).filter((a=>{var r;return(r=e[a].metadata)==null?void 0:r.payload})).map((a=>{var r;return[a,(r=e[a].metadata)==null?void 0:r.payload]})))):La.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),t},n4=(function(t){return t.FeatureFlags="feature_flags",t.Recordings="recordings",t})({}),db=class{constructor(e){this.oi=!1,this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.ci=!1,this._instance=e,this.featureFlagEventHandlers=[]}fi(){var e,a=(e=this._instance.config.evaluation_contexts)!==null&&e!==void 0?e:this._instance.config.evaluation_environments;return!this._instance.config.evaluation_environments||this._instance.config.evaluation_contexts||this.ci||(La.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.ci=!0),a!=null&&a.length?a.filter((r=>{var n=r&&typeof r=="string"&&r.trim().length>0;return n||La.error("Invalid evaluation context found:",r,"Expected non-empty string"),n})):[]}pi(){return this.fi().length>0}flags(){if(this._instance.config.__preview_remote_config)this.di=!0;else{var e=!this.gi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.mi({disableFlags:e})}}get hasLoadedFlags(){return this.ai}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(zx),a=this._instance.get_property($s),r=this._instance.get_property(rc);if(!r&&!a)return e||{};var n=ot({},e||{}),o=[...new Set([...Object.keys(r||{}),...Object.keys(a||{})])];for(var i of o){var s,l,u=n[i],c=a?.[i],d=V(c)?(s=u?.enabled)!==null&&s!==void 0&&s:!!c,f=V(c)?u.variant:typeof c=="string"?c:void 0,h=r?.[i],S=j({},u,{enabled:d,variant:d?f??u?.variant:void 0});d!==u?.enabled&&(S.original_enabled=u?.enabled),f!==u?.variant&&(S.original_variant=u?.variant),h&&(S.metadata=j({},u?.metadata,{payload:h,original_payload:u==null||(l=u.metadata)==null?void 0:l.payload})),n[i]=S}return this.oi||(La.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:r,finalDetails:n}),this.oi=!0),n}getFlagVariants(){var e=this._instance.get_property(Ks),a=this._instance.get_property($s);if(!a)return e||{};for(var r=ot({},e),n=Object.keys(a),o=0;o<n.length;o++)r[n[o]]=a[n[o]];return this.oi||(La.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:a,finalFlags:r}),this.oi=!0),r}getFlagPayloads(){var e=this._instance.get_property(iE),a=this._instance.get_property(rc);if(!a)return e||{};for(var r=ot({},e||{}),n=Object.keys(a),o=0;o<n.length;o++)r[n[o]]=a[n[o]];return this.oi||(La.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:a,finalPayloads:r}),this.oi=!0),r}reloadFeatureFlags(){this.ui||this._instance.config.advanced_disable_feature_flags||this.gi||(this.gi=setTimeout((()=>{this.mi()}),5))}bi(){clearTimeout(this.gi),this.gi=void 0}ensureFlagsLoaded(){this.ai||this.li||this.gi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.ui=e}mi(e){var a;if(this.bi(),!this._instance.M())if(this.li)this.hi=!0;else{var r=this._instance.config.token,n=this._instance.get_property("$device_id"),o={token:r,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:j({},((a=this._instance.persistence)==null?void 0:a.get_initial_props())||{},this._instance.get_property(cc)||{}),group_properties:this._instance.get_property(wi)};cr(n)||V(n)||(o.$device_id=n),(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(o.disable_flags=!0),this.pi()&&(o.evaluation_contexts=this.fi());var i=this._instance.config.__preview_remote_config,s=i?"/flags/?v=2":"/flags/?v=2&config=true",l=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",u=this._instance.requestRouter.endpointFor("flags",s+l);i&&(o.timezone=pT()),this.li=!0,this._instance._send_request({method:"POST",url:u,data:o,compression:this._instance.config.disable_compression?void 0:mn.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:c=>{var d,f,h=!0;if(c.statusCode===200&&(this.hi||(this.$anon_distinct_id=void 0),h=!1),this.li=!1,this.di||(this.di=!0,this._instance.yi((f=c.json)!==null&&f!==void 0?f:{})),!o.disable_flags||this.hi)if(this.vi=!h,c.json&&(d=c.json.quotaLimited)!=null&&d.includes(n4.FeatureFlags))La.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var S;o.disable_flags||this.receivedFeatureFlags((S=c.json)!==null&&S!==void 0?S:{},h),this.hi&&(this.hi=!1,this.mi())}}})}}getFeatureFlag(e,a){var r;if(a===void 0&&(a={}),this.ai||this.getFlags()&&this.getFlags().length>0){var n=this.getFeatureFlagResult(e,a);return(r=n?.variant)!==null&&r!==void 0?r:n?.enabled}La.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var a=this.getFeatureFlagResult(e,{send_event:!1});return a?.payload}getFeatureFlagResult(e,a){if(a===void 0&&(a={}),this.ai||this.getFlags()&&this.getFlags().length>0){var r=this.getFlagVariants(),n=e in r,o=r[e],i=this.getFlagPayloads()[e],s=String(o),l=this._instance.get_property(sE)||void 0,u=this._instance.get_property(lE)||void 0,c=this._instance.get_property(Wp)||{};if((a.send_event||!("send_event"in a))&&(!(e in c)||!c[e].includes(s))){var d,f,h,S,x,b,g,m,y;Ce(c[e])?c[e].push(s):c[e]=[s],(d=this._instance.persistence)==null||d.register({[Wp]:c});var v=this.getFeatureFlagDetails(e),C={$feature_flag:e,$feature_flag_response:o,$feature_flag_payload:i||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((f=this._instance.config.bootstrap)==null||(f=f.featureFlags)==null?void 0:f[e])||null,$feature_flag_bootstrapped_payload:((h=this._instance.config.bootstrap)==null||(h=h.featureFlagPayloads)==null?void 0:h[e])||null,$used_bootstrap_value:!this.vi};V(v==null||(S=v.metadata)==null?void 0:S.version)||(C.$feature_flag_version=v.metadata.version);var w,_=(x=v==null||(b=v.reason)==null?void 0:b.description)!==null&&x!==void 0?x:v==null||(g=v.reason)==null?void 0:g.code;_&&(C.$feature_flag_reason=_),v!=null&&(m=v.metadata)!=null&&m.id&&(C.$feature_flag_id=v.metadata.id),V(v?.original_variant)&&V(v?.original_enabled)||(C.$feature_flag_original_response=V(v.original_variant)?v.original_enabled:v.original_variant),v!=null&&(y=v.metadata)!=null&&y.original_payload&&(C.$feature_flag_original_payload=v==null||(w=v.metadata)==null?void 0:w.original_payload),this._instance.capture("$feature_flag_called",C)}if(n){var L=i;if(!V(i))try{L=JSON.parse(i)}catch{}return{key:e,enabled:!!o,variant:typeof o=="string"?o:void 0,payload:L}}}else La.warn('getFeatureFlagResult for key "'+e+`" failed. Feature flags didn't load in time.`)}getRemoteConfigPayload(e,a){var r=this._instance.config.token,n={distinct_id:this._instance.get_distinct_id(),token:r};this.pi()&&(n.evaluation_contexts=this.fi()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:n,compression:this._instance.config.disable_compression?void 0:mn.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:o=>{var i,s=(i=o.json)==null?void 0:i.featureFlagPayloads;a(s?.[e]||void 0)}})}isFeatureEnabled(e,a){if(a===void 0&&(a={}),this.ai||this.getFlags()&&this.getFlags().length>0){var r=this.getFeatureFlag(e,a);return V(r)?void 0:!!r}La.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((a=>a!==e))}receivedFeatureFlags(e,a){if(this._instance.persistence){this.ai=!0;var r=this.getFlagVariants(),n=this.getFlagPayloads(),o=this.getFlagsWithDetails();(function(i,s,l,u,c){l===void 0&&(l={}),u===void 0&&(u={}),c===void 0&&(c={});var d=r4(i),f=d.flags,h=d.featureFlags,S=d.featureFlagPayloads;if(h){var x=i.requestId,b=i.evaluatedAt;if(Ce(h)){La.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var g={};if(h)for(var m=0;m<h.length;m++)g[h[m]]=!0;s&&s.register({[mx]:h,[Ks]:g})}else{var y=h,v=S,C=f;if(i.errorsWhileComputingFlags)if(f){var w=new Set(Object.keys(f).filter((_=>{var L;return!((L=f[_])!=null&&L.failed)})));y=j({},l,Object.fromEntries(Object.entries(y).filter((_=>{var[L]=_;return w.has(L)})))),v=j({},u,Object.fromEntries(Object.entries(v||{}).filter((_=>{var[L]=_;return w.has(L)})))),C=j({},c,Object.fromEntries(Object.entries(C||{}).filter((_=>{var[L]=_;return w.has(L)}))))}else y=j({},l,y),v=j({},u,v),C=j({},c,C);s&&s.register(j({[mx]:Object.keys(uE(y)),[Ks]:y||{},[iE]:v||{},[zx]:C||{}},x?{[sE]:x}:{},b?{[lE]:b}:{}))}}})(e,this._instance.persistence,r,n,o),this.wi(a)}}override(e,a){a===void 0&&(a=!1),La.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:a})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return La.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister($s),this._instance.persistence.unregister(rc),this.wi(),ac.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var a,r=e;if(this.oi=!!((a=r.suppressWarning)!==null&&a!==void 0&&a),"flags"in r){if(r.flags===!1)this._instance.persistence.unregister($s),ac.info("Flag overrides cleared");else if(r.flags){if(Ce(r.flags)){for(var n={},o=0;o<r.flags.length;o++)n[r.flags[o]]=!0;this._instance.persistence.register({[$s]:n})}else this._instance.persistence.register({[$s]:r.flags});ac.info("Flag overrides set",{flags:r.flags})}}return"payloads"in r&&(r.payloads===!1?(this._instance.persistence.unregister(rc),ac.info("Payload overrides cleared")):r.payloads&&(this._instance.persistence.register({[rc]:r.payloads}),ac.info("Payload overrides set",{payloads:r.payloads}))),void this.wi()}this.wi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ai){var{flags:a,flagVariants:r}=this.xi();e(a,r)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,a,r){var n,o=(this._instance.get_property(uc)||[]).find((u=>u.flagKey===e)),i={["$feature_enrollment/"+e]:a},s={$feature_flag:e,$feature_enrollment:a,$set:i};o&&(s.$early_access_feature_name=o.name),r&&(s.$feature_enrollment_stage=r),this._instance.capture("$feature_enrollment_update",s),this.setPersonPropertiesForFlags(i,!1);var l=j({},this.getFlagVariants(),{[e]:a});(n=this._instance.persistence)==null||n.register({[mx]:Object.keys(uE(l)),[Ks]:l}),this.wi()}getEarlyAccessFeatures(e,a,r){a===void 0&&(a=!1);var n=this._instance.get_property(uc),o=r?"&"+r.map((i=>"stage="+i)).join("&"):"";if(n&&!a)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+o),method:"GET",callback:i=>{var s,l;if(i.json){var u=i.json.earlyAccessFeatures;return(s=this._instance.persistence)==null||s.unregister(uc),(l=this._instance.persistence)==null||l.register({[uc]:u}),e(u)}}})}xi(){var e=this.getFlags(),a=this.getFlagVariants();return{flags:e.filter((r=>a[r])),flagVariants:Object.keys(a).filter((r=>a[r])).reduce(((r,n)=>(r[n]=a[n],r)),{})}}wi(e){var{flags:a,flagVariants:r}=this.xi();this.featureFlagEventHandlers.forEach((n=>n(a,r,{errorsLoading:e})))}setPersonPropertiesForFlags(e,a){a===void 0&&(a=!0);var r=this._instance.get_property(cc)||{};this._instance.register({[cc]:j({},r,e)}),a&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(cc)}setGroupPropertiesForFlags(e,a){a===void 0&&(a=!0);var r=this._instance.get_property(wi)||{};Object.keys(r).length!==0&&Object.keys(r).forEach((n=>{r[n]=j({},r[n],e[n]),delete e[n]})),this._instance.register({[wi]:j({},r,e)}),a&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var a=this._instance.get_property(wi)||{};this._instance.register({[wi]:j({},a,{[e]:{}})})}else this._instance.unregister(wi)}reset(){this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.$anon_distinct_id=void 0,this.bi(),this.oi=!1}},o4=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],mc=class{constructor(e,a){this.R=e,this.props={},this.Ei=!1,this.$i=(r=>{var n="";return r.token&&(n=r.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),r.persistence_name?"ph_"+r.persistence_name:"ph_"+n+"_posthog"})(e),this.Y=this.Si(e),this.load(),e.debug&&$.info("Persistence loaded",e.persistence,j({},this.props)),this.update_config(e,e,a),this.save()}isDisabled(){return!!this.ki}Si(e){o4.indexOf(e.persistence.toLowerCase())===-1&&($.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var a=(function(n){n===void 0&&(n=[]);var o=[...P3,...n];return j({},Ke,{W:function(i){try{var s={};try{s=kr.W(i)||{}}catch{}var l=ot(s,JSON.parse(Ke.q(i)||"{}"));return Ke.G(i,l),l}catch{}return null},G:function(i,s,l,u,c,d){try{Ke.G(i,s,void 0,void 0,d);var f={};o.forEach((h=>{s[h]&&(f[h]=s[h])})),Object.keys(f).length&&kr.G(i,f,l,u,c,d)}catch(h){Ke.B(h)}},V:function(i,s){try{T?.localStorage.removeItem(i),kr.V(i,s)}catch(l){Ke.B(l)}}})})(e.cookie_persisted_properties||[]),r=e.persistence.toLowerCase();return r==="localstorage"&&Ke.H()?Ke:r==="localstorage+cookie"&&a.H()?a:r==="sessionstorage"&&Dt.H()?Dt:r==="memory"?N3:r==="cookie"?kr:a.H()?a:kr}properties(){var e={};return Be(this.props,(function(a,r){if(r===Ks&&gt(a))for(var n=Object.keys(a),o=0;o<n.length;o++)e["$feature/"+n[o]]=a[n[o]];else s=r,l=!1,(cr(i=x3)?l:CA&&i.indexOf===CA?i.indexOf(s)!=-1:(Be(i,(function(u){if(l||(l=u===s))return jp})),l))||(e[r]=a);var i,s,l})),e}load(){if(!this.ki){var e=this.Y.W(this.$i);e&&(this.props=ot({},e))}}save(){this.ki||this.Y.G(this.$i,this.props,this.Pi,this.Ti,this.Ii,this.R.debug)}remove(){this.Y.V(this.$i,!1),this.Y.V(this.$i,!0)}clear(){this.remove(),this.props={}}register_once(e,a,r){if(gt(e)){V(a)&&(a="None"),this.Pi=V(r)?this.Ci:r;var n=!1;if(Be(e,((o,i)=>{this.props.hasOwnProperty(i)&&this.props[i]!==a||(this.props[i]=o,n=!0)})),n)return this.save(),!0}return!1}register(e,a){if(gt(e)){this.Pi=V(a)?this.Ci:a;var r=!1;if(Be(e,((n,o)=>{e.hasOwnProperty(o)&&this.props[o]!==n&&(this.props[o]=n,r=!0)})),r)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.Ei){var e=sT(this.R.custom_campaign_params,this.R.mask_personal_data_properties,this.R.custom_personal_data_properties);Xs(Nb(e))||this.register(e),this.Ei=!0}}update_search_keyword(){var e;this.register((e=q?.referrer)?uT(e):{})}update_referrer_info(){var e;this.register_once({$referrer:cT(),$referring_domain:q!=null&&q.referrer&&((e=Qp(q.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[jx]||this.props[Gx]||this.register_once({[Zp]:dT(this.R.mask_personal_data_properties,this.R.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};Be([Gx,jx],(i=>{var s=this.props[i];s&&Be(s,(function(l,u){e["$initial_"+_x(u)]=l}))}));var a,r,n=this.props[Zp];if(n){var o=(a=fT(n),r={},Be(a,(function(i,s){r["$initial_"+_x(s)]=i})),r);ot(e,o)}return e}safe_merge(e){return Be(this.props,(function(a,r){r in e||(e[r]=a)})),e}update_config(e,a,r){if(this.Ci=this.Pi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==a.persistence||!((i,s)=>{if(i.length!==s.length)return!1;var l=[...i].sort(),u=[...s].sort();return l.every(((c,d)=>c===u[d]))})(e.cookie_persisted_properties||[],a.cookie_persisted_properties||[])){var n=this.Si(e),o=this.props;this.clear(),this.Y=n,this.props=o,this.save()}}set_disabled(e){this.ki=e,this.ki?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ti&&(this.Ti=e,this.remove(),this.save())}set_secure(e){e!==this.Ii&&(this.Ii=e,this.remove(),this.save())}set_event_timer(e,a){var r=this.props[lc]||{};r[e]=a,this.props[lc]=r,this.save()}remove_event_timer(e){var a=(this.props[lc]||{})[e];return V(a)||(delete this.props[lc][e],this.save()),a}get_property(e){return this.props[e]}set_property(e,a){this.props[e]=a,this.save()}},cE=et("[Product Tours]"),gx="ph_product_tours",fb=class{constructor(e){this.Ri=null,this.Fi=null,this._instance=e}onRemoteConfig(e){this._instance.persistence&&this._instance.persistence.register({[HA]:!(e==null||!e.productTours)}),this.loadIfEnabled()}loadIfEnabled(){var e,a;this.Ri||(e=this._instance).config.disable_product_tours||(a=e.persistence)==null||!a.get_property(HA)||this.it((()=>this.Oi()))}it(e){var a,r;(a=Q.__PosthogExtensions__)!=null&&a.generateProductTours?e():(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"product-tours",(n=>{n?cE.error("Could not load product tours script",n):e()}))}Oi(){var e;!this.Ri&&(e=Q.__PosthogExtensions__)!=null&&e.generateProductTours&&(this.Ri=Q.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,a){if(a===void 0&&(a=!1),!Ce(this.Fi)||a){var r=this._instance.persistence;if(r){var n=r.props[gx];if(Ce(n)&&!a)return this.Fi=n,void e(n,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:o=>{var i=o.statusCode;if(i!==200||!o.json){var s="Product Tours API could not be loaded, status: "+i;return cE.error(s),void e([],{isLoaded:!1,error:s})}var l=Ce(o.json.product_tours)?o.json.product_tours:[];this.Fi=l,r&&r.register({[gx]:l}),e(l,{isLoaded:!0})}})}else e(this.Fi,{isLoaded:!0})}getActiveProductTours(e){ge(this.Ri)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.Ri.getActiveProductTours(e)}showProductTour(e){var a;(a=this.Ri)==null||a.showTourById(e)}previewTour(e){this.Ri?this.Ri.previewTour(e):this.it((()=>{var a;this.Oi(),(a=this.Ri)==null||a.previewTour(e)}))}dismissProductTour(){var e;(e=this.Ri)==null||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.Ri)==null||e.nextStep()}previousStep(){var e;(e=this.Ri)==null||e.previousStep()}clearCache(){var e;this.Fi=null,(e=this._instance.persistence)==null||e.unregister(gx)}resetTour(e){var a;(a=this.Ri)==null||a.resetTour(e)}resetAllTours(){var e;(e=this.Ri)==null||e.resetAllTours()}cancelPendingTour(e){var a;(a=this.Ri)==null||a.cancelPendingTour(e)}},nc=(function(t){return t.Activation="events",t.Cancellation="cancelEvents",t})({}),E8=(function(t){return t.Button="button",t.Tab="tab",t.Selector="selector",t})({}),T8=(function(t){return t.TopLeft="top_left",t.TopRight="top_right",t.TopCenter="top_center",t.MiddleLeft="middle_left",t.MiddleRight="middle_right",t.MiddleCenter="middle_center",t.Left="left",t.Center="center",t.Right="right",t.NextToTrigger="next_to_trigger",t})({}),R8=(function(t){return t.Top="top",t.Left="left",t.Right="right",t.Bottom="bottom",t})({}),vx=(function(t){return t.Popover="popover",t.API="api",t.Widget="widget",t.ExternalSurvey="external_survey",t})({}),M8=(function(t){return t.Open="open",t.MultipleChoice="multiple_choice",t.SingleChoice="single_choice",t.Rating="rating",t.Link="link",t})({}),O8=(function(t){return t.NextQuestion="next_question",t.End="end",t.ResponseBased="response_based",t.SpecificQuestion="specific_question",t})({}),D8=(function(t){return t.Once="once",t.Recurring="recurring",t.Always="always",t})({}),fc=(function(t){return t.SHOWN="survey shown",t.DISMISSED="survey dismissed",t.SENT="survey sent",t.ABANDONED="survey abandoned",t})({}),yx=(function(t){return t.SURVEY_ID="$survey_id",t.SURVEY_NAME="$survey_name",t.SURVEY_RESPONSE="$survey_response",t.SURVEY_ITERATION="$survey_iteration",t.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",t.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",t.SURVEY_SUBMISSION_ID="$survey_submission_id",t.SURVEY_QUESTIONS="$survey_questions",t.SURVEY_COMPLETED="$survey_completed",t.PRODUCT_TOUR_ID="$product_tour_id",t.SURVEY_LAST_SEEN_DATE="$survey_last_seen_date",t})({}),pb=(function(t){return t.Popover="popover",t.Inline="inline",t})({}),Oe=et("[Surveys]"),bT="seenSurvey_",i4=(t,e)=>{var a="$survey_"+e+"/"+t.id;return t.current_iteration&&t.current_iteration>0&&(a="$survey_"+e+"/"+t.id+"/"+t.current_iteration),a},dE=t=>((e,a)=>{var r=""+e+a.id;return a.current_iteration&&a.current_iteration>0&&(r=""+e+a.id+"_"+a.current_iteration),r})(bT,t),s4=[vx.Popover,vx.Widget,vx.API],l4={ignoreConditions:!1,ignoreDelay:!1,displayType:pb.Popover},_c=class{constructor(){this.Mi={},this.Mi={}}on(e,a){return this.Mi[e]||(this.Mi[e]=[]),this.Mi[e].push(a),()=>{this.Mi[e]=this.Mi[e].filter((r=>r!==a))}}emit(e,a){for(var r of this.Mi[e]||[])r(a);for(var n of this.Mi["*"]||[])n(e,a)}};function js(t,e,a){if(ge(t))return!1;switch(a){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}var hb=class{constructor(e){this.Ai=new _c,this.ji=(a,r)=>this.Di(a,r)&&this.Li(a,r)&&this.Ni(a,r)&&this.Ui(a,r),this.Di=(a,r)=>r==null||!r.event||a?.event===r?.event,this._instance=e,this.zi=new Set,this.Hi=new Set}init(){var e;if(!V((e=this._instance)==null?void 0:e._addCaptureHook)){var a;(a=this._instance)==null||a._addCaptureHook(((r,n)=>{this.on(r,n)}))}}register(e){var a,r;if(!V((a=this._instance)==null?void 0:a._addCaptureHook)&&(e.forEach((i=>{var s,l;(s=this.Hi)==null||s.add(i),(l=i.steps)==null||l.forEach((u=>{var c;(c=this.zi)==null||c.add(u?.event||"")}))})),(r=this._instance)!=null&&r.autocapture)){var n,o=new Set;e.forEach((i=>{var s;(s=i.steps)==null||s.forEach((l=>{l!=null&&l.selector&&o.add(l?.selector)}))})),(n=this._instance)==null||n.autocapture.setElementSelectors(o)}}on(e,a){var r;a!=null&&e.length!=0&&(this.zi.has(e)||this.zi.has(a?.event))&&this.Hi&&((r=this.Hi)==null?void 0:r.size)>0&&this.Hi.forEach((n=>{this.Bi(a,n)&&this.Ai.emit("actionCaptured",n.name)}))}qi(e){this.onAction("actionCaptured",(a=>e(a)))}Bi(e,a){if(a?.steps==null)return!1;for(var r of a.steps)if(this.ji(e,r))return!0;return!1}onAction(e,a){return this.Ai.on(e,a)}Li(e,a){if(a!=null&&a.url){var r,n=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!n||typeof n!="string"||!js(n,a.url,a.url_matching||"contains"))return!1}return!0}Ni(e,a){return!!this.Wi(e,a)&&!!this.Gi(e,a)&&!!this.Vi(e,a)}Wi(e,a){var r;if(a==null||!a.href)return!0;var n=this.Ji(e);if(n.length>0)return n.some((s=>js(s.href,a.href,a.href_matching||"exact")));var o,i=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!i&&js((o=i.match(/(?::|")href="(.*?)"/))?o[1]:"",a.href,a.href_matching||"exact")}Gi(e,a){var r;if(a==null||!a.text)return!0;var n=this.Ji(e);if(n.length>0)return n.some((u=>js(u.text,a.text,a.text_matching||"exact")||js(u.$el_text,a.text,a.text_matching||"exact")));var o,i,s,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(o=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!ge(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),i=a.text,s=a.text_matching||"exact",o.some((u=>js(u,i,s))))}Vi(e,a){var r,n;if(a==null||!a.selector)return!0;var o=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(o!=null&&o.includes(a.selector))return!0;var i=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";if(a.selector_regex&&i)try{return new RegExp(a.selector_regex).test(i)}catch{return!1}return!1}Ji(e){var a;return(e==null||(a=e.properties)==null?void 0:a.$elements)==null?[]:e?.properties.$elements}Ui(e,a){return a==null||!a.properties||a.properties.length===0||xT(a.properties.reduce(((r,n)=>{var o=Ce(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return r[n.key]={values:o,operator:n.operator||"exact"},r}),{}),e?.properties)}},mb=class{constructor(e){this._instance=e,this.Ki=new Map,this.Yi=new Map,this.Xi=new Map}Qi(e,a){return!!e&&xT(e.propertyFilters,a?.properties)}Zi(e,a){var r=new Map;return e.forEach((n=>{var o;(o=n.conditions)==null||(o=o[a])==null||(o=o.values)==null||o.forEach((i=>{if(i!=null&&i.name){var s=r.get(i.name)||[];s.push(n.id),r.set(i.name,s)}}))})),r}te(e,a,r){var n=(r===nc.Activation?this.Ki:this.Yi).get(e),o=[];return this.ie((i=>{o=i.filter((s=>n?.includes(s.id)))})),o.filter((i=>{var s,l=(s=i.conditions)==null||(s=s[r])==null||(s=s.values)==null?void 0:s.find((u=>u.name===e));return this.Qi(l,a)}))}register(e){var a;V((a=this._instance)==null?void 0:a._addCaptureHook)||(this.ee(e),this.re(e))}re(e){var a=e.filter((r=>{var n,o;return((n=r.conditions)==null?void 0:n.actions)&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0}));a.length!==0&&(this.se==null&&(this.se=new hb(this._instance),this.se.init(),this.se.qi((r=>{this.onAction(r)}))),a.forEach((r=>{var n,o,i,s,l;r.conditions&&(n=r.conditions)!=null&&n.actions&&(o=r.conditions)!=null&&(o=o.actions)!=null&&o.values&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0&&((s=this.se)==null||s.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.Xi.get(u.name);c&&c.push(r.id),this.Xi.set(u.name,c||[r.id])}})))})))}ee(e){var a,r=e.filter((o=>{var i,s;return((i=o.conditions)==null?void 0:i.events)&&((s=o.conditions)==null||(s=s.events)==null||(s=s.values)==null?void 0:s.length)>0})),n=e.filter((o=>{var i,s;return((i=o.conditions)==null?void 0:i.cancelEvents)&&((s=o.conditions)==null||(s=s.cancelEvents)==null||(s=s.values)==null?void 0:s.length)>0}));(r.length!==0||n.length!==0)&&((a=this._instance)==null||a._addCaptureHook(((o,i)=>{this.onEvent(o,i)})),this.Ki=this.Zi(e,nc.Activation),this.Yi=this.Zi(e,nc.Cancellation))}onEvent(e,a){var r,n=this.ne(),o=this.oe(),i=this.ae(),s=((r=this._instance)==null||(r=r.persistence)==null?void 0:r.props[o])||[];if(i===e&&a&&s.length>0){var l,u;n.info("event matched, removing item from activated items",{event:e,eventPayload:a,existingActivatedItems:s});var c=(a==null||(l=a.properties)==null?void 0:l.$survey_id)||(a==null||(u=a.properties)==null?void 0:u.$product_tour_id);if(c){var d=s.indexOf(c);d>=0&&(s.splice(d,1),this.le(s))}}else{if(this.Yi.has(e)){var f=this.te(e,a,nc.Cancellation);f.length>0&&(n.info("cancel event matched, cancelling items",{event:e,itemsToCancel:f.map((S=>S.id))}),f.forEach((S=>{var x=s.indexOf(S.id);x>=0&&s.splice(x,1),this.ue(S.id)})),this.le(s))}if(this.Ki.has(e)){n.info("event name matched",{event:e,eventPayload:a,items:this.Ki.get(e)});var h=this.te(e,a,nc.Activation);this.le(s.concat(h.map((S=>S.id))||[]))}}}onAction(e){var a,r=this.oe(),n=((a=this._instance)==null||(a=a.persistence)==null?void 0:a.props[r])||[];this.Xi.has(e)&&this.le(n.concat(this.Xi.get(e)||[]))}le(e){var a,r=this.ne(),n=this.oe(),o=[...new Set(e)].filter((i=>!this.he(i)));r.info("updating activated items",{activatedItems:o}),(a=this._instance)==null||(a=a.persistence)==null||a.register({[n]:o})}getActivatedIds(){var e,a=this.oe(),r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[a];return r||[]}getEventToItemsMap(){return this.Ki}de(){return this.se}},gb=class extends mb{constructor(e){super(e)}oe(){return"$surveys_activated"}ae(){return fc.SHOWN}ie(e){var a;(a=this._instance)==null||a.getSurveys(e)}ue(e){var a;(a=this._instance)==null||a.cancelPendingSurvey(e)}ne(){return Oe}he(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},vb=class{constructor(e){this.ve=void 0,this._surveyManager=null,this.ce=!1,this.fe=[],this.pe=null,this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var a=e.surveys;if(ge(a))return Oe.warn("Flags not loaded yet. Not loading surveys.");var r=Ce(a);this.ve=r?a.length>0:a,Oe.info("flags response received, isSurveysEnabled: "+this.ve),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],a=0;a<localStorage.length;a++){var r=localStorage.key(a);(r!=null&&r.startsWith(bT)||r!=null&&r.startsWith("inProgressSurvey_"))&&e.push(r)}e.forEach((n=>localStorage.removeItem(n)))}loadIfEnabled(){if(!this._surveyManager)if(this.ce)Oe.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)Oe.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())Oe.info("Not loading surveys in cookieless mode without consent.");else{var e=Q?.__PosthogExtensions__;if(e){if(!V(this.ve)||this._instance.config.advanced_enable_surveys){var a=this.ve||this._instance.config.advanced_enable_surveys;this.ce=!0;try{var r=e.generateSurveys;if(r)return void this.ge(r,a);var n=e.loadExternalDependency;if(!n)return void this._e("PostHog loadExternalDependency extension not found.");n(this._instance,"surveys",(o=>{o||!e.generateSurveys?this._e("Could not load surveys script",o):this.ge(e.generateSurveys,a)}))}catch(o){throw this._e("Error initializing surveys",o),o}finally{this.ce=!1}}}else Oe.error("PostHog Extensions not found.")}}ge(e,a){this._surveyManager=e(this._instance,a),this._surveyEventReceiver=new gb(this._instance),Oe.info("Surveys loaded successfully"),this.me({isLoaded:!0})}_e(e,a){Oe.error(e,a),this.me({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.fe.push(e),this._surveyManager&&this.me({isLoaded:!0}),()=>{this.fe=this.fe.filter((a=>a!==e))}}getSurveys(e,a){if(a===void 0&&(a=!1),this._instance.config.disable_surveys)return Oe.info("Disabled. Not loading surveys."),e([]);var r,n=this._instance.get_property(qx);if(n&&!a)return e(n,{isLoaded:!0});typeof Promise<"u"&&this.pe?this.pe.then((o=>{var{surveys:i,context:s}=o;return e(i,s)})):(typeof Promise<"u"&&(this.pe=new Promise((o=>{r=o}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:o=>{var i;this.pe=null;var s=o.statusCode;if(s!==200||!o.json){var l="Surveys API could not be loaded, status: "+s;Oe.error(l);var u={isLoaded:!1,error:l};return e([],u),void(r==null||r({surveys:[],context:u}))}var c,d=o.json.surveys||[],f=d.filter((S=>(function(x){return!(!x.start_date||x.end_date)})(S)&&((function(x){var b;return!((b=x.conditions)==null||(b=b.events)==null||(b=b.values)==null||!b.length)})(S)||(function(x){var b;return!((b=x.conditions)==null||(b=b.actions)==null||(b=b.values)==null||!b.length)})(S))));f.length>0&&((c=this._surveyEventReceiver)==null||c.register(f)),(i=this._instance.persistence)==null||i.register({[qx]:d});var h={isLoaded:!0};e(d,h),r?.({surveys:d,context:h})}}))}me(e){for(var a of this.fe)try{if(!e.isLoaded)return a([],e);this.getSurveys(a)}catch(r){Oe.error("Error in survey callback",r)}}getActiveMatchingSurveys(e,a){if(a===void 0&&(a=!1),!ge(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,a);Oe.warn("init was not called")}be(e){var a=null;return this.getSurveys((r=>{var n;a=(n=r.find((o=>o.id===e)))!==null&&n!==void 0?n:null})),a}ye(e){if(ge(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var a=typeof e=="string"?this.be(e):e;return a?this._surveyManager.checkSurveyEligibility(a):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(ge(this._surveyManager))return Oe.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var a=this.ye(e);return{visible:a.eligible,disabledReason:a.reason}}canRenderSurveyAsync(e,a){return ge(this._surveyManager)?(Oe.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise((r=>{this.getSurveys((n=>{var o,i=(o=n.find((l=>l.id===e)))!==null&&o!==void 0?o:null;if(i){var s=this.ye(i);r({visible:s.eligible,disabledReason:s.reason})}else r({visible:!1,disabledReason:"Survey not found"})}),a)}))}renderSurvey(e,a,r){var n;if(ge(this._surveyManager))Oe.warn("init was not called");else{var o=typeof e=="string"?this.be(e):e;if(o!=null&&o.id)if(s4.includes(o.type)){var i=q?.querySelector(a);if(i)return(n=o.appearance)!=null&&n.surveyPopupDelaySeconds?(Oe.info("Rendering survey "+o.id+" with delay of "+o.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var s,l;Oe.info("Rendering survey "+o.id+" with delay of "+((s=o.appearance)==null?void 0:s.surveyPopupDelaySeconds)+" seconds"),(l=this._surveyManager)==null||l.renderSurvey(o,i,r),Oe.info("Survey "+o.id+" rendered")}),1e3*o.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(o,i,r);Oe.warn("Survey element not found")}else Oe.warn("Surveys of type "+o.type+" cannot be rendered in the app");else Oe.warn("Survey not found")}}displaySurvey(e,a){var r;if(ge(this._surveyManager))Oe.warn("init was not called");else{var n=this.be(e);if(n){var o=n;if((r=n.appearance)!=null&&r.surveyPopupDelaySeconds&&a.ignoreDelay&&(o=j({},n,{appearance:j({},n.appearance,{surveyPopupDelaySeconds:0})})),a.displayType!==pb.Popover&&a.initialResponses&&Oe.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),a.ignoreConditions===!1){var i=this.canRenderSurvey(n);if(!i.visible)return void Oe.warn("Survey is not eligible to be displayed: ",i.disabledReason)}a.displayType!==pb.Inline?this._surveyManager.handlePopoverSurvey(o,a):this.renderSurvey(o,a.selector,a.properties)}else Oe.warn("Survey not found")}}cancelPendingSurvey(e){ge(this._surveyManager)?Oe.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;(e=this._surveyManager)==null||e.handlePageUnload()}},dn=et("[Conversations]"),yb=class{constructor(e){this.we=void 0,this._conversationsManager=null,this.xe=!1,this.Ee=null,this._instance=e}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var a=e.conversations;ge(a)||(vn(a)?this.we=a:(this.we=a.enabled,this.Ee=a),this.loadIfEnabled())}}reset(){var e;(e=this._conversationsManager)==null||e.reset(),this._conversationsManager=null,this.we=void 0,this.Ee=null}loadIfEnabled(){if(!this._conversationsManager&&!this.xe&&!(this._instance.config.disable_conversations||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=Q?.__PosthogExtensions__;if(e&&!V(this.we)&&this.we)if(this.Ee&&this.Ee.token){this.xe=!0;try{var a=e.initConversations;if(a)return this.$e(a),void(this.xe=!1);var r=e.loadExternalDependency;if(!r)return void this.Se("PostHog loadExternalDependency extension not found.");r(this._instance,"conversations",(n=>{n||!e.initConversations?this.Se("Could not load conversations script",n):this.$e(e.initConversations),this.xe=!1}))}catch(n){this.Se("Error initializing conversations",n),this.xe=!1}}else dn.error("Conversations enabled but missing token in remote config.")}}$e(e){if(this.Ee)try{this._conversationsManager=e(this.Ee,this._instance),dn.info("Conversations loaded successfully")}catch(a){this.Se("Error completing conversations initialization",a)}else dn.error("Cannot complete initialization: remote config is null")}Se(e,a){dn.error(e,a),this._conversationsManager=null,this.xe=!1}show(){this._conversationsManager?this._conversationsManager.show():dn.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.we===!0&&!cr(this._conversationsManager)}isVisible(){var e,a;return(e=(a=this._conversationsManager)==null?void 0:a.isVisible())!==null&&e!==void 0&&e}sendMessage(e,a,r){var n=this;return Zs((function*(){return n._conversationsManager?n._conversationsManager.sendMessage(e,a,r):(dn.warn("Conversations not available yet."),null)}))()}getMessages(e,a){var r=this;return Zs((function*(){return r._conversationsManager?r._conversationsManager.getMessages(e,a):(dn.warn("Conversations not available yet."),null)}))()}markAsRead(e){var a=this;return Zs((function*(){return a._conversationsManager?a._conversationsManager.markAsRead(e):(dn.warn("Conversations not available yet."),null)}))()}getTickets(e){var a=this;return Zs((function*(){return a._conversationsManager?a._conversationsManager.getTickets(e):(dn.warn("Conversations not available yet."),null)}))()}getCurrentTicketId(){var e,a;return(e=(a=this._conversationsManager)==null?void 0:a.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,a;return(e=(a=this._conversationsManager)==null?void 0:a.getWidgetSessionId())!==null&&e!==void 0?e:null}},xb=class{constructor(e){var a;this.ke=!1,this.Pe=!1,this._instance=e,this._instance&&(a=this._instance.config.logs)!=null&&a.captureConsoleLogs&&(this.ke=!0)}onRemoteConfig(e){var a,r=(a=e.logs)==null?void 0:a.captureConsoleLogs;!ge(r)&&r&&(this.ke=!0,this.loadIfEnabled())}reset(){}loadIfEnabled(){if(this.ke&&!this.Pe){var e=et("[logs]"),a=Q?.__PosthogExtensions__;if(a){var r=a.loadExternalDependency;r?r(this._instance,"logs",(n=>{var o;n||(o=a.logs)==null||!o.initializeLogs?e.error("Could not load logs script",n):(a.logs.initializeLogs(this._instance),this.Pe=!0)})):e.error("PostHog loadExternalDependency extension not found.")}else e.error("PostHog Extensions not found.")}}},fE=et("[RateLimiter]"),bb=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=a=>{var r=a.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach((n=>{fE.info((n||"events")+" is quota limited."),this.serverLimits[n]=new Date().getTime()+6e4}))}catch(n){return void fE.warn('could not rate limit - continuing. Error: "'+n?.message+'"',{text:r})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var a,r,n;e===void 0&&(e=!1);var{captureEventsBurstLimit:o,captureEventsPerSecond:i}=this,s=new Date().getTime(),l=(a=(r=this.instance.persistence)==null?void 0:r.get_property($x))!==null&&a!==void 0?a:{tokens:o,last:s};l.tokens+=(s-l.last)/1e3*i,l.last=s,l.tokens>o&&(l.tokens=o);var u=l.tokens<1;return u||e||(l.tokens=Math.max(0,l.tokens-1)),!u||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+i+" events per second and "+o+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=u,(n=this.instance.persistence)==null||n.set_property($x,l),{isRateLimited:u,remainingTokens:l.tokens}}isServerRateLimited(e){var a=this.serverLimits[e||"events"]||!1;return a!==!1&&new Date().getTime()<a}},Ci=et("[RemoteConfig]"),Sb=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=Q._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}Te(e){var a,r;(a=Q.__PosthogExtensions__)!=null&&a.loadExternalDependency?(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"remote-config",(()=>e(this.remoteConfig))):(Ci.error("PostHog Extensions not found. Cannot load remote config."),e())}Ie(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:a=>{e(a.json)}})}load(){try{if(this.remoteConfig)return Ci.info("Using preloaded remote config",this.remoteConfig),void this.yi(this.remoteConfig);if(this._instance.M())return void Ci.warn("Remote config is disabled. Falling back to local config.");this.Te((e=>{if(!e)return Ci.info("No config found after loading remote JS config. Falling back to JSON."),void this.Ie((a=>{this.yi(a)}));this.yi(e)}))}catch(e){Ci.error("Error loading remote config",e)}}yi(e){e?this._instance.config.__preview_remote_config?(this._instance.yi(e),e.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):Ci.info("__preview_remote_config is disabled. Logging config instead",e):Ci.error("Failed to fetch remote config from PostHog.")}},_b=3e3,Cb=class{constructor(e,a){this.Ce=!0,this.Re=[],this.Fe=Ir(a?.flush_interval_ms||_b,250,5e3,$.createLogger("flush interval"),_b),this.Oe=e}enqueue(e){this.Re.push(e),this.Me||this.Ae()}unload(){this.je();var e=this.Re.length>0?this.De():{},a=Object.values(e);[...a.filter((r=>r.url.indexOf("/e")===0)),...a.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.Oe(j({},r,{transport:"sendBeacon"}))}))}enable(){this.Ce=!1,this.Ae()}Ae(){var e=this;this.Ce||(this.Me=setTimeout((()=>{if(this.je(),this.Re.length>0){var a=this.De(),r=function(){var o=a[n],i=new Date().getTime();o.data&&Ce(o.data)&&Be(o.data,(s=>{s.offset=Math.abs(s.timestamp-i),delete s.timestamp})),e.Oe(o)};for(var n in a)r()}}),this.Fe))}je(){clearTimeout(this.Me),this.Me=void 0}De(){var e={};return Be(this.Re,(a=>{var r,n=a,o=(n?n.batchKey:null)||n.url;V(e[o])&&(e[o]=j({},n,{data:[]})),(r=e[o].data)==null||r.push(n.data)})),this.Re=[],e}},u4=["retriesPerformedSoFar"],wb=class{constructor(e){this.Le=!1,this.Ne=3e3,this.Re=[],this._instance=e,this.Re=[],this.Ue=!0,!V(T)&&"onLine"in T.navigator&&(this.Ue=T.navigator.onLine,this.ze=()=>{this.Ue=!0,this.Lt()},this.He=()=>{this.Ue=!1},ft(T,"online",this.ze),ft(T,"offline",this.He))}get length(){return this.Re.length}retriableRequest(e){var{retriesPerformedSoFar:a}=e,r=yE(e,u4);Gs(a)&&(r.url=oh(r.url,{retry_count:a})),this._instance._send_request(j({},r,{callback:n=>{n.statusCode!==200&&(n.statusCode<400||n.statusCode>=500)&&(a??0)<10?this.Be(j({retriesPerformedSoFar:a},r)):r.callback==null||r.callback(n)}}))}Be(e){var a=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=a+1;var r=(function(i){var s=3e3*Math.pow(2,i),l=s/2,u=Math.min(18e5,s),c=(Math.random()-.5)*(u-l);return Math.ceil(u+c)})(a),n=Date.now()+r;this.Re.push({retryAt:n,requestOptions:e});var o="Enqueued failed request for retry in "+r;navigator.onLine||(o+=" (Browser is offline)"),$.warn(o),this.Le||(this.Le=!0,this.qe())}qe(){if(this.We&&clearTimeout(this.We),this.Re.length===0)return this.Le=!1,void(this.We=void 0);this.We=setTimeout((()=>{this.Ue&&this.Re.length>0&&this.Lt(),this.qe()}),this.Ne)}Lt(){var e=Date.now(),a=[],r=this.Re.filter((o=>o.retryAt<e||(a.push(o),!1)));if(this.Re=a,r.length>0)for(var{requestOptions:n}of r)this.retriableRequest(n)}unload(){for(var{requestOptions:e}of(this.We&&(clearTimeout(this.We),this.We=void 0),this.Le=!1,V(T)||(this.ze&&(T.removeEventListener("online",this.ze),this.ze=void 0),this.He&&(T.removeEventListener("offline",this.He),this.He=void 0)),this.Re))try{this._instance._send_request(j({},e,{transport:"sendBeacon"}))}catch(a){$.error(a)}this.Re=[]}},Lb=class{constructor(e){this.Ge=()=>{var a,r,n,o;this.Ve||(this.Ve={});var i=this.scrollElement(),s=this.scrollY(),l=i?Math.max(0,i.scrollHeight-i.clientHeight):0,u=s+(i?.clientHeight||0),c=i?.scrollHeight||0;this.Ve.lastScrollY=Math.ceil(s),this.Ve.maxScrollY=Math.max(s,(a=this.Ve.maxScrollY)!==null&&a!==void 0?a:0),this.Ve.maxScrollHeight=Math.max(l,(r=this.Ve.maxScrollHeight)!==null&&r!==void 0?r:0),this.Ve.lastContentY=u,this.Ve.maxContentY=Math.max(u,(n=this.Ve.maxContentY)!==null&&n!==void 0?n:0),this.Ve.maxContentHeight=Math.max(c,(o=this.Ve.maxContentHeight)!==null&&o!==void 0?o:0)},this._instance=e}getContext(){return this.Ve}resetContext(){var e=this.Ve;return setTimeout(this.Ge,0),e}startMeasuringScrollPosition(){ft(T,"scroll",this.Ge,{capture:!0}),ft(T,"scrollend",this.Ge,{capture:!0}),ft(T,"resize",this.Ge)}scrollElement(){if(!this._instance.config.scroll_root_selector)return T?.document.documentElement;var e=Ce(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var a of e){var r=T?.document.querySelector(a);if(r)return r}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return T&&(T.scrollY||T.pageYOffset||T.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return T&&(T.scrollX||T.pageXOffset||T.document.documentElement.scrollLeft)||0}},c4=t=>dT(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties),sh=class{constructor(e,a,r,n){this.Je=o=>{var i=this.Ke();if(!i||i.sessionId!==o){var s={sessionId:o,props:this.Ye(this._instance)};this.Xe.register({[Vx]:s})}},this._instance=e,this.Qe=a,this.Xe=r,this.Ye=n||c4,this.Qe.onSessionId(this.Je)}Ke(){return this.Xe.props[Vx]}getSetOnceProps(){var e,a=(e=this.Ke())==null?void 0:e.props;return a?"r"in a?fT(a):{$referring_domain:a.referringDomain,$pathname:a.initialPathName,utm_source:a.utm_source,utm_campaign:a.utm_campaign,utm_medium:a.utm_medium,utm_content:a.utm_content,utm_term:a.utm_term}:{}}getSessionProps(){var e={};return Be(Nb(this.getSetOnceProps()),((a,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+_x(r)]=a})),e}},xx=et("[SessionId]"),lh=class{on(e,a){return this.Ze.on(e,a)}constructor(e,a,r){var n;if(this.tr=[],this.ir=void 0,this.Ze=new _c,this.er=(c,d)=>!(!Gs(c)||!Gs(d))&&Math.abs(c-d)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.R=e.config,this.Xe=e.persistence,this.rr=void 0,this.sr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.nr=a||So,this.ar=r||So;var o=this.R.persistence_name||this.R.token,i=this.R.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*Ir(i,60,36e3,xx.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.lr(),this.ur="ph_"+o+"_window_id",this.hr="ph_"+o+"_primary_window_exists",this.dr()){var s=Dt.W(this.ur),l=Dt.W(this.hr);s&&!l?this.rr=s:Dt.V(this.ur),Dt.G(this.hr,!0)}if((n=this.R.bootstrap)!=null&&n.sessionID)try{var u=(c=>{var d=c.replace(/-/g,"");if(d.length!==32)throw new Error("Not a valid UUID");if(d[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(d.substring(0,12),16)})(this.R.bootstrap.sessionID);this.vr(this.R.bootstrap.sessionID,new Date().getTime(),u)}catch(c){xx.error("Invalid sessionID in bootstrap",c)}this.cr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return V(this.tr)&&(this.tr=[]),this.tr.push(e),this.sr&&e(this.sr,this.rr),()=>{this.tr=this.tr.filter((a=>a!==e))}}dr(){return this.R.persistence!=="memory"&&!this.Xe.ki&&Dt.H()}pr(e){e!==this.rr&&(this.rr=e,this.dr()&&Dt.G(this.ur,e))}gr(){return this.rr?this.rr:this.dr()?Dt.W(this.ur):null}vr(e,a,r){e===this.sr&&a===this._sessionActivityTimestamp&&r===this._sessionStartTimestamp||(this._sessionStartTimestamp=r,this._sessionActivityTimestamp=a,this.sr=e,this.Xe.register({[Gp]:[a,e,r]}))}_r(){var e=this.Xe.props[Gp];return Ce(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.vr(null,null,null)}destroy(){clearTimeout(this.mr),this.mr=void 0,this.ir&&T&&(T.removeEventListener("beforeunload",this.ir,{capture:!1}),this.ir=void 0),this.tr=[]}cr(){this.ir=()=>{this.dr()&&Dt.V(this.hr)},ft(T,"beforeunload",this.ir,{capture:!1})}checkAndGetSessionAndWindowId(e,a){if(e===void 0&&(e=!1),a===void 0&&(a=null),this.R.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=a||new Date().getTime(),[n,o,i]=this._r(),s=this.gr(),l=Gs(i)&&Math.abs(r-i)>864e5,u=!1,c=!o,d=!c&&!e&&this.er(r,n);c||d||l?(o=this.nr(),s=this.ar(),xx.info("new session ID generated",{sessionId:o,windowId:s,changeReason:{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}}),i=r,u=!0):s||(s=this.ar(),u=!0);var f=Gs(n)&&e&&!l?n:r,h=Gs(i)?i:new Date().getTime();return this.pr(s),this.vr(o,f,h),e||this.lr(),u&&this.tr.forEach((S=>S(o,s,u?{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}:void 0))),{sessionId:o,windowId:s,sessionStartTimestamp:h,changeReason:u?{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:n}}lr(){clearTimeout(this.mr),this.mr=setTimeout((()=>{var[e]=this._r();if(this.er(new Date().getTime(),e)){var a=this.sr;this.resetSessionId(),this.Ze.emit("forcedIdleReset",{idleSessionId:a})}}),1.1*this.sessionTimeoutMs)}},d4=["$set_once","$set"],xo=et("[SiteApps]"),kb=class{constructor(e){this._instance=e,this.br=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}yr(e,a){if(a){var r=this.globalsForEvent(a);this.br.push(r),this.br.length>1e3&&(this.br=this.br.slice(10))}}get siteAppLoaders(){var e;return(e=Q._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance._addCaptureHook(this.yr.bind(this));this.wr=()=>{e(),this.br=[],this.wr=void 0}}}globalsForEvent(e){var a,r,n,o,i,s,l;if(!e)throw new Error("Event payload is required");var u={},c=this._instance.get_property("$groups")||[],d=this._instance.get_property("$stored_group_properties")||{};for(var[f,h]of Object.entries(d))u[f]={id:c[f],type:f,properties:h};var{$set_once:S,$set:x}=e;return{event:j({},yE(e,d4),{properties:j({},e.properties,x?{$set:j({},(a=(r=e.properties)==null?void 0:r.$set)!==null&&a!==void 0?a:{},x)}:{},S?{$set_once:j({},(n=(o=e.properties)==null?void 0:o.$set_once)!==null&&n!==void 0?n:{},S)}:{}),elements_chain:(i=(s=e.properties)==null?void 0:s.$elements_chain)!==null&&i!==void 0?i:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:u}}setupSiteApp(e){var a=this.apps[e.id],r=()=>{var s;!a.errored&&this.br.length&&(xo.info("Processing "+this.br.length+" events for site app with id "+e.id),this.br.forEach((l=>a.processEvent==null?void 0:a.processEvent(l))),a.processedBuffer=!0),Object.values(this.apps).every((l=>l.processedBuffer||l.errored))&&((s=this.wr)==null||s.call(this))},n=!1,o=s=>{a.errored=!s,a.loaded=!0,xo.info("Site app with id "+e.id+" "+(s?"loaded":"errored")),n&&r()};try{var{processEvent:i}=e.init({posthog:this._instance,callback:s=>{o(s)}});i&&(a.processEvent=i),n=!0}catch(s){xo.error("Error while initializing PostHog app with config id "+e.id,s),o(!1)}if(n&&a.loaded)try{r()}catch(s){xo.error("Error while processing buffered events PostHog app with config id "+e.id,s),a.errored=!0}}Er(){var e=this.siteAppLoaders||[];for(var a of e)this.apps[a.id]={id:a.id,loaded:!1,errored:!1,processedBuffer:!1};for(var r of e)this.setupSiteApp(r)}$r(e){if(Object.keys(this.apps).length!==0){var a=this.globalsForEvent(e);for(var r of Object.values(this.apps))try{r.processEvent==null||r.processEvent(a)}catch(n){xo.error("Error while processing event "+e.event+" for site app "+r.id,n)}}}onRemoteConfig(e){var a,r,n,o=this;if((a=this.siteAppLoaders)!=null&&a.length)return this.isEnabled?(this.Er(),void this._instance.on("eventCaptured",(u=>this.$r(u)))):void xo.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((r=this.wr)==null||r.call(this),(n=e.siteApps)!=null&&n.length)if(this.isEnabled){var i=function(u){var c;Q["__$$ph_site_app_"+u]=o._instance,(c=Q.__PosthogExtensions__)==null||c.loadSiteApp==null||c.loadSiteApp(o._instance,l,(d=>{if(d)return xo.error("Error while initializing PostHog app with config id "+u,d)}))};for(var{id:s,url:l}of e.siteApps)i(s)}else xo.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},ST=function(t,e){if(!t)return!1;var a=t.userAgent;if(a&&kA(a,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some((n=>kA(n?.brand,e))))return!0}catch{}return!!t.webdriver},pc=(function(t){return t.US="us",t.EU="eu",t.CUSTOM="custom",t})({}),pE="i.posthog.com",Ib=class{constructor(e){this.Sr={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,a=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return a||(a=this.apiHost.replace("."+pE,".posthog.com")),a==="https://app.posthog.com"?"https://us.posthog.com":a}get region(){return this.Sr[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=pc.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=pc.EU:this.Sr[this.apiHost]=pc.CUSTOM),this.Sr[this.apiHost]}endpointFor(e,a){if(a===void 0&&(a=""),a&&(a=a[0]==="/"?a:"/"+a),e==="ui")return this.uiHost+a;if(e==="flags")return this.flagsApiHost+a;if(this.region===pc.CUSTOM)return this.apiHost+a;var r=pE+a;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}},f4={icontains:(t,e)=>!!T&&e.href.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>!!T&&e.href.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>!!T&&ih(e.href,t),not_regex:(t,e)=>!!T&&!ih(e.href,t),exact:(t,e)=>e.href===t,is_not:(t,e)=>e.href!==t},Ab=class t{constructor(e){var a=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),a.getWebExperiments((n=>{t.kr("retrieved web experiments from the server"),a.Pr=new Map,n.forEach((o=>{if(o.feature_flag_key){var i;a.Pr&&(t.kr("setting flag key ",o.feature_flag_key," to web experiment ",o),(i=a.Pr)==null||i.set(o.feature_flag_key,o));var s=a._instance.getFeatureFlag(o.feature_flag_key);vt(s)&&o.variants[s]&&a.Tr(o.name,s,o.variants[s].transforms)}else if(o.variants)for(var l in o.variants){var u=o.variants[l];t.Ir(u)&&a.Tr(o.name,l,u.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}onFeatureFlags(e){if(this._is_bot())t.kr("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(ge(this.Pr))return this.Pr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();t.kr("applying feature flags",e),e.forEach((a=>{var r;if(this.Pr&&(r=this.Pr)!=null&&r.has(a)){var n,o=this._instance.getFeatureFlag(a),i=(n=this.Pr)==null?void 0:n.get(a);o&&i!=null&&i.variants[o]&&this.Tr(i.name,o,i.variants[o].transforms)}}))}}previewWebExperiment(){var e=t.getWindowLocation();if(e!=null&&e.search){var a=Jp(e?.search,"__experiment_id"),r=Jp(e?.search,"__experiment_variant");a&&r&&(t.kr("previewing web experiments "+a+" && "+r),this.getWebExperiments((n=>{this.Cr(parseInt(a),r,n)}),!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,a,r){if(this._instance.config.disable_web_experiments&&!r)return e([]);var n=this._instance.get_property("$web_experiments");if(n&&!a)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:o=>{if(o.statusCode!==200||!o.json)return e([]);var i=o.json.experiments||[];return e(i)}})}Cr(e,a,r){var n=r.filter((o=>o.id===e));n&&n.length>0&&(t.kr("Previewing web experiment ["+n[0].name+"] with variant ["+a+"]"),this.Tr(n[0].name,a,n[0].variants[a].transforms))}static Ir(e){return!ge(e.conditions)&&t.Rr(e)&&t.Fr(e)}static Rr(e){var a;if(ge(e.conditions)||ge((a=e.conditions)==null?void 0:a.url))return!0;var r,n,o,i=t.getWindowLocation();return!!i&&((r=e.conditions)==null||!r.url||f4[(n=(o=e.conditions)==null?void 0:o.urlMatchType)!==null&&n!==void 0?n:"icontains"](e.conditions.url,i))}static getWindowLocation(){return T?.location}static Fr(e){var a;if(ge(e.conditions)||ge((a=e.conditions)==null?void 0:a.utm))return!0;var r=sT();if(r.utm_source){var n,o,i,s,l,u,c,d,f=(n=e.conditions)==null||(n=n.utm)==null||!n.utm_campaign||((o=e.conditions)==null||(o=o.utm)==null?void 0:o.utm_campaign)==r.utm_campaign,h=(i=e.conditions)==null||(i=i.utm)==null||!i.utm_source||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_source)==r.utm_source,S=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,x=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return f&&S&&x&&h}return!1}static kr(e){for(var a=arguments.length,r=new Array(a>1?a-1:0),n=1;n<a;n++)r[n-1]=arguments[n];$.info("[WebExperiments] "+e,r)}Tr(e,a,r){this._is_bot()?t.kr("Refusing to render web experiment since the viewer is a likely bot"):a!=="control"?r.forEach((n=>{if(n.selector){var o;t.kr("applying transform of variant "+a+" for experiment "+e+" ",n);var i=(o=document)==null?void 0:o.querySelectorAll(n.selector);i?.forEach((s=>{var l=s;n.html&&(l.innerHTML=n.html),n.css&&l.setAttribute("style",n.css)}))}})):t.kr("Control variants leave the page unmodified.")}_is_bot(){return ka&&this._instance?ST(ka,this._instance.config.custom_blocked_useragents):void 0}},p4=et("[PostHog ExternalIntegrations]"),h4={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},Eb=class{constructor(e){this._instance=e}it(e,a){var r;(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(n=>{if(n)return p4.error("failed to load script",n);a()}))}startIfEnabledOrStop(){var e=this,a=function(i){var s,l,u;!n||(s=Q.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[i]||e.it(h4[i],(()=>{var c;(c=Q.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[i])==null||c.start(e._instance)})),!n&&(l=Q.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[i]&&((u=Q.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[i])==null||u.stop())};for(var[r,n]of Object.entries((o=this._instance.config.integrations)!==null&&o!==void 0?o:{})){var o;a(r)}}},Tb="[SessionRecording]",oc=et(Tb),uh=class{get started(){var e;return!((e=this.Or)==null||!e.isStarted)}get status(){return this.Or?this.Or.status:this.Mr&&!this.Ar?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Mr=!1,this.jr=void 0,this._instance=e,!this._instance.sessionManager)throw oc.error("started without valid sessionManager"),new Error(Tb+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(Tb+' cannot be used with cookieless_mode="always"')}get Ar(){var e,a=!((e=this._instance.get_property(ix))==null||!e.enabled),r=!this._instance.config.disable_session_recording,n=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return T&&a&&r&&!n}startIfEnabledOrStop(e){var a;if(!this.Ar||(a=this.Or)==null||!a.isStarted){var r=!V(Object.assign)&&!V(Array.from);this.Ar&&r?(this.Dr(e),oc.info("starting")):this.stopRecording()}}Dr(e){var a,r,n;this.Ar&&(Q!=null&&(a=Q.__PosthogExtensions__)!=null&&(a=a.rrweb)!=null&&a.record&&(r=Q.__PosthogExtensions__)!=null&&r.initSessionRecording?this.Lr(e):(n=Q.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,this.Nr,(o=>{if(o)return oc.error("could not load recorder",o);this.Lr(e)})))}stopRecording(){var e,a;(e=this.jr)==null||e.call(this),this.jr=void 0,(a=this.Or)==null||a.stop()}Ur(){var e;(e=this._instance.persistence)==null||e.unregister($E)}zr(e){if(this._instance.persistence){var a,r,n=this._instance.persistence,o=()=>{var i=e.sessionRecording===!1?void 0:e.sessionRecording,s=i?.sampleRate,l=ge(s)?null:parseFloat(s);ge(l)&&this.Ur();var u=i?.minimumDurationMilliseconds;n.register({[ix]:j({enabled:!!i},i,{networkPayloadCapture:j({capturePerformance:e.capturePerformance},i?.networkPayloadCapture),canvasRecording:{enabled:i?.recordCanvas,fps:i?.canvasFps,quality:i?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:V(u)?null:u,endpoint:i?.endpoint,triggerMatchType:i?.triggerMatchType,masking:i?.masking,urlTriggers:i?.urlTriggers})})};o(),(a=this.jr)==null||a.call(this),this.jr=(r=this._instance.sessionManager)==null?void 0:r.onSessionId(o)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.zr(e),this.Mr=!0,this.startIfEnabledOrStop()):this.Mr=!0:oc.info("skipping remote config with no sessionRecording",e)}log(e,a){var r;a===void 0&&(a="log"),(r=this.Or)!=null&&r.log?this.Or.log(e,a):oc.warn("log called before recorder was ready")}get Nr(){var e,a,r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(ix);return(r==null||(a=r.scriptConfig)==null?void 0:a.script)||"lazy-recorder"}Lr(e){var a,r;if((a=Q.__PosthogExtensions__)==null||!a.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.Or||(this.Or=(r=Q.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance),this.Or._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.Or.start(e)}onRRwebEmit(e){var a;(a=this.Or)==null||a.onRRwebEmit==null||a.onRRwebEmit(e)}overrideLinkedFlag(){var e,a;this.Or||(a=this._instance.persistence)==null||a.register({$replay_override_linked_flag:!0}),(e=this.Or)==null||e.overrideLinkedFlag()}overrideSampling(){var e,a;this.Or||(a=this._instance.persistence)==null||a.register({$replay_override_sampling:!0}),(e=this.Or)==null||e.overrideSampling()}overrideTrigger(e){var a,r;this.Or||(r=this._instance.persistence)==null||r.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(a=this.Or)==null||a.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.Or)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,a){var r;return!((r=this.Or)==null||!r.tryAddCustomEvent(e,a))}},gc={},Rb=()=>{},Ws="posthog",_T=!a4&&ua?.indexOf("MSIE")===-1&&ua?.indexOf("Mozilla")===-1,hE=t=>{var e;return j({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:y3(q?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Rb,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,debug:Bt&&vt(Bt?.search)&&Bt.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!0,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(T==null||(e=T.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:a=>{var r="Bad HTTP status: "+a.statusCode+" "+a.text;$.error(r)},get_device_id:a=>a,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:_b},error_tracking:{},_onCapture:Rb,__preview_eager_load_replay:!1},(a=>({rageclick:!(a&&a>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(a&&a>="2025-05-24")||"history_change",session_recording:a&&a>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:a&&a>="2026-01-30"?"head":"body",internal_or_test_user_hostname:a&&a>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0}))(t))},mE=t=>{var e={};V(t.process_person)||(e.person_profiles=t.process_person),V(t.xhr_headers)||(e.request_headers=t.xhr_headers),V(t.cookie_name)||(e.persistence_name=t.cookie_name),V(t.disable_cookie)||(e.disable_persistence=t.disable_cookie),V(t.store_google)||(e.save_campaign_params=t.store_google),V(t.verbose)||(e.debug=t.verbose);var a=ot({},e,t);return Ce(t.property_blacklist)&&(V(t.property_denylist)?a.property_denylist=t.property_blacklist:Ce(t.property_denylist)?a.property_denylist=[...t.property_blacklist,...t.property_denylist]:$.error("Invalid value for property_denylist config: "+t.property_denylist)),a},Mb=class{constructor(){this.__forceAllowLocalhost=!1}get Hr(){return this.__forceAllowLocalhost}set Hr(e){$.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},ch=class t{get decideEndpointWasHit(){var e,a;return(e=(a=this.featureFlags)==null?void 0:a.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,a;return(e=(a=this.featureFlags)==null?void 0:a.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new Mb,this.Br=!1,this.version=fn.LIB_VERSION,this.qr=new _c,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=hE(),this.SentryIntegration=tb,this.sentryIntegration=e=>(function(a,r){var n=iT(a,r);return{name:oT,processEvent:o=>n(o)}})(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Wr=!1,this.Gr=null,this.Vr=null,this.Jr=null,this.featureFlags=new db(this),this.toolbar=new ab(this),this.scrollManager=new Lb(this),this.pageViewManager=new ah(this),this.surveys=new vb(this),this.conversations=new yb(this),this.logs=new xb(this),this.experiments=new Ab(this),this.exceptions=new cb(this),this.rateLimiter=new bb(this),this.requestRouter=new Ib(this),this.consent=new Qx(this),this.externalIntegrations=new Eb(this),this.people={set:(e,a,r)=>{var n=vt(e)?{[e]:a}:e;this.setPersonProperties(n),r?.({})},set_once:(e,a,r)=>{var n=vt(e)?{[e]:a}:e;this.setPersonProperties(void 0,n),r?.({})}},this.on("eventCaptured",(e=>$.info('send "'+e?.event+'"',e)))}init(e,a,r){if(r&&r!==Ws){var n,o=(n=gc[r])!==null&&n!==void 0?n:new t;return o._init(e,a,r),gc[r]=o,gc[Ws][r]=o,o}return this._init(e,a,r)}_init(e,a,r){var n;if(a===void 0&&(a={}),V(e)||Cx(e))return $.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},a.debug=this.Kr(a.debug),this.Yr=a,this.Xr=[],a.person_profiles&&(this.Vr=a.person_profiles),this.set_config(ot({},hE(a.defaults),mE(a),{name:r,token:e})),this.config.on_xhr_error&&$.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=a.disable_compression?void 0:mn.GZipJS;var o=this.Qr();this.persistence=new mc(this.config,o),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new mc(j({},this.config,{persistence:"sessionStorage"}),o);var i=j({},this.persistence.props),s=j({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Zr=new Cb((m=>this.ts(m)),this.config.request_queue_config),this.es=new wb(this),this.__request_queue=[];var l=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(l||(this.sessionManager=new lh(this),this.sessionPropsManager=new sh(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?($.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.rs(l)}),0)):($.info("Initializing extensions synchronously"),this.rs(l)),fn.DEBUG=fn.DEBUG||this.config.debug,fn.DEBUG&&$.info("Starting in debug mode",{this:this,config:a,thisC:j({},this.config),p:i,s}),((n=a.bootstrap)==null?void 0:n.distinctID)!==void 0){var u,c,d=this.config.get_device_id(So()),f=(u=a.bootstrap)!=null&&u.isIdentifiedID?d:a.bootstrap.distinctID;this.persistence.set_property(pn,(c=a.bootstrap)!=null&&c.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:a.bootstrap.distinctID,$device_id:f})}if(this.ss()){var h,S,x=Object.keys(((h=a.bootstrap)==null?void 0:h.featureFlags)||{}).filter((m=>{var y;return!((y=a.bootstrap)==null||(y=y.featureFlags)==null||!y[m])})).reduce(((m,y)=>{var v;return m[y]=((v=a.bootstrap)==null||(v=v.featureFlags)==null?void 0:v[y])||!1,m}),{}),b=Object.keys(((S=a.bootstrap)==null?void 0:S.featureFlagPayloads)||{}).filter((m=>x[m])).reduce(((m,y)=>{var v,C;return(v=a.bootstrap)!=null&&(v=v.featureFlagPayloads)!=null&&v[y]&&(m[y]=(C=a.bootstrap)==null||(C=C.featureFlagPayloads)==null?void 0:C[y]),m}),{});this.featureFlags.receivedFeatureFlags({featureFlags:x,featureFlagPayloads:b})}if(l)this.register_once({distinct_id:Yu,$device_id:null},"");else if(!this.get_distinct_id()){var g=this.config.get_device_id(So());this.register_once({distinct_id:g,$device_id:g},""),this.persistence.set_property(pn,"anonymous")}return ft(T,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),a.segment?U3(this,(()=>this.ns())):this.ns(),_o(this.config._onCapture)&&this.config._onCapture!==Rb&&($.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(m=>this.config._onCapture(m.event,m)))),this.config.ip&&$.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this}rs(e){var a=performance.now();this.historyAutocapture=new eb(this),this.historyAutocapture.startIfEnabled();var r=[];r.push((()=>{new rb(this).startIfEnabledOrStop()})),r.push((()=>{var n;this.siteApps=new kb(this),(n=this.siteApps)==null||n.init()})),e||r.push((()=>{this.sessionRecording=new uh(this),this.sessionRecording.startIfEnabledOrStop()})),this.config.disable_scroll_properties||r.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),r.push((()=>{this.autocapture=new Zx(this),this.autocapture.startIfEnabled()})),r.push((()=>{this.surveys.loadIfEnabled()})),r.push((()=>{this.logs.loadIfEnabled()})),r.push((()=>{this.conversations.loadIfEnabled()})),r.push((()=>{this.productTours=new fb(this),this.productTours.loadIfEnabled()})),r.push((()=>{this.heatmaps=new ob(this),this.heatmaps.startIfEnabled()})),r.push((()=>{this.webVitalsAutocapture=new nb(this)})),r.push((()=>{this.exceptionObserver=new Jx(this),this.exceptionObserver.startIfEnabledOrStop()})),r.push((()=>{this.deadClicksAutocapture=new th(this,H3),this.deadClicksAutocapture.startIfEnabled()})),r.push((()=>{if(this.os){var n=this.os;this.os=void 0,this.yi(n)}})),this.ls(r,a)}ls(e,a){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-a>=30&&e.length>0)return void setTimeout((()=>{this.ls(e,a)}),0);var r=e.shift();if(r)try{r()}catch(o){$.error("Error initializing extension:",o)}}var n=Math.round(performance.now()-a);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:n}),this.config.__preview_deferred_init_extensions&&$.info("PostHog extensions initialized ("+n+"ms)")}yi(e){var a,r,n,o,i,s,l,u,c;if(!q||!q.body)return $.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.yi(e)}),500);this.config.__preview_deferred_init_extensions&&(this.os=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=he(e.supportedCompression,mn.GZipJS)?mn.GZipJS:he(e.supportedCompression,mn.Base64)?mn.Base64:void 0),(a=e.analytics)!=null&&a.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Vr?this.Vr:"identified_only"}),(r=this.siteApps)==null||r.onRemoteConfig(e),(n=this.sessionRecording)==null||n.onRemoteConfig(e),(o=this.autocapture)==null||o.onRemoteConfig(e),(i=this.heatmaps)==null||i.onRemoteConfig(e),this.surveys.onRemoteConfig(e),this.logs.onRemoteConfig(e),this.conversations.onRemoteConfig(e),(s=this.productTours)==null||s.onRemoteConfig(e),(l=this.webVitalsAutocapture)==null||l.onRemoteConfig(e),(u=this.exceptionObserver)==null||u.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(c=this.deadClicksAutocapture)==null||c.onRemoteConfig(e)}ns(){try{this.config.loaded(this)}catch(r){$.critical("`loaded` function failed",r)}if(this.us(),this.config.internal_or_test_user_hostname&&Bt!=null&&Bt.hostname){var e=Bt.hostname,a=this.config.internal_or_test_user_hostname;(typeof a=="string"?e===a:a.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.hs()}),1),new Sb(this).load(),this.featureFlags.flags()}us(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.Zr)==null||e.enable())}_dom_loaded(){this.is_capturing()&&Co(this.__request_queue,(e=>this.ts(e))),this.__request_queue=[],this.us()}_handle_unload(){var e,a;this.surveys.handlePageUnload(),this.config.request_batching?(this.ds()&&this.capture("$pageleave"),(e=this.Zr)==null||e.unload(),(a=this.es)==null||a.unload()):this.ds()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}_send_request(e){this.__loaded&&(_T?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=oh(e.url,{ip:this.config.ip?1:0}),e.headers=j({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(a=>{var r,n,o,i=j({},a);i.timeout=i.timeout||6e4,i.url=oh(i.url,{_:new Date().getTime().toString(),ver:fn.LIB_VERSION,compression:i.compression});var s=(r=i.transport)!==null&&r!==void 0?r:"fetch",l=qp.filter((c=>!i.disableTransport||!c.transport||!i.disableTransport.includes(c.transport))),u=(n=(o=zE(l,(c=>c.transport===s)))==null?void 0:o.method)!==null&&n!==void 0?n:l[0].method;if(!u)throw new Error("No available transport method");u(i)})(j({},e,{callback:a=>{var r,n;this.rateLimiter.checkForLimiting(a),a.statusCode>=400&&((r=(n=this.config).on_request_error)==null||r.call(n,a)),e.callback==null||e.callback(a)}}))))}ts(e){this.es?this.es.retriableRequest(e):this._send_request(e)}_execute_array(e){var a,r=[],n=[],o=[];Co(e,(s=>{s&&(a=s[0],Ce(a)?o.push(s):_o(s)?s.call(this):Ce(s)&&a==="alias"?r.push(s):Ce(s)&&a.indexOf("capture")!==-1&&_o(this[a])?o.push(s):n.push(s))}));var i=function(s,l){Co(s,(function(u){if(Ce(u[0])){var c=l;Be(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else this[u[0]].apply(this,u.slice(1))}),l)};i(r,this),i(n,this),i(o,this)}ss(){var e,a;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((a=this.config.bootstrap)==null?void 0:a.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,a,r){var n;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Zr){if(this.is_capturing())if(!V(e)&&vt(e)){var o=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(o&&!this.config.__preview_capture_bot_pageviews)){var i=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(i==null||!i.isRateLimited){a!=null&&a.$current_url&&!vt(a?.$current_url)&&($.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),a==null||delete a.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var s=new Date,l=r?.timestamp||s,u=So(),c={uuid:u,event:e,properties:this.calculateEventProperties(e,a||{},l,u)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&o&&(c.event="$bot_pageview",c.properties.$browser_type="bot"),i&&(c.properties.$lib_rate_limit_remaining_tokens=i.remainingTokens),r?.$set&&(c.$set=r?.$set);var d,f=e!=="$groupidentify",h=this.vs(r?.$set_once,f);if(h&&(c.$set_once=h),(c=g3(c,r!=null&&r._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,V(r?.timestamp)||(c.properties.$event_time_override_provided=!0,c.properties.$event_time_override_system_time=s),e===fc.DISMISSED||e===fc.SENT){var S=a?.[yx.SURVEY_ID],x=a?.[yx.SURVEY_ITERATION];d={id:S,current_iteration:x},localStorage.getItem(dE(d))||localStorage.setItem(dE(d),"true"),c.$set=j({},c.$set,{[i4({id:S,current_iteration:x},e===fc.SENT?"responded":"dismissed")]:!0})}else e===fc.SHOWN&&(c.$set=j({},c.$set,{[yx.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var b=j({},c.properties.$set,c.$set);if(Xs(b)||this.setPersonPropertiesForFlags(b),!ge(this.config.before_send)){var g=this.cs(c);if(!g)return;c=g}this.qr.emit("eventCaptured",c);var m={method:"POST",url:(n=r?._url)!==null&&n!==void 0?n:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:c,compression:"best-available",batchKey:r?._batchKey};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.ts(m):this.Zr.enqueue(m),c}$.critical("This capture call is ignored due to client rate limiting.")}}else $.error("No event name provided to posthog.capture")}else $.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(a=>e(a.event,a)))}calculateEventProperties(e,a,r,n,o){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return a;var i=o?void 0:this.persistence.remove_event_timer(e),s=j({},a);if(s.token=this.config.token,s.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(s.$cookieless_mode=!0),e==="$snapshot"){var l=j({},this.persistence.properties(),this.sessionPersistence.properties());return s.distinct_id=l.distinct_id,(!vt(s.distinct_id)&&!yn(s.distinct_id)||Cx(s.distinct_id))&&$.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),s}var u,c=G3(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:d,windowId:f}=this.sessionManager.checkAndGetSessionAndWindowId(o,r.getTime());s.$session_id=d,s.$window_id=f}this.sessionPropsManager&&ot(s,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&ot(s,this.sessionRecording.sdkDebugProperties),s.$sdk_debug_retry_queue_size=(h=this.es)==null?void 0:h.length}catch(g){s.$sdk_debug_error_capturing_properties=String(g)}if(this.requestRouter.region===pc.CUSTOM&&(s.$lib_custom_api_host=this.config.api_host),u=e!=="$pageview"||o?e!=="$pageleave"||o?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,n),s=ot(s,u),e==="$pageview"&&q&&(s.title=q.title),!V(i)){var S=r.getTime()-i;s.$duration=parseFloat((S/1e3).toFixed(3))}ua&&this.config.opt_out_useragent_filter&&(s.$browser_type=this._is_bot()?"bot":"browser"),(s=ot({},c,this.persistence.properties(),this.sessionPersistence.properties(),s)).$is_identified=this._isIdentified(),Ce(this.config.property_denylist)?Be(this.config.property_denylist,(function(g){delete s[g]})):$.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var x=this.config.sanitize_properties;x&&($.error("sanitize_properties is deprecated. Use before_send instead"),s=x(s,e));var b=this.fs();return s.$process_person_profile=b,b&&!o&&this.ps("_calculate_event_properties"),s}vs(e,a){var r;if(a===void 0&&(a=!0),!this.persistence||!this.fs()||this.Br)return e;var n=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),i=ot({},n,o||{},e||{}),s=this.config.sanitize_properties;return s&&($.error("sanitize_properties is deprecated. Use before_send instead"),i=s(i,"$set_once")),a&&(this.Br=!0),Xs(i)?void 0:i}register(e,a){var r;(r=this.persistence)==null||r.register(e,a)}register_once(e,a,r){var n;(n=this.persistence)==null||n.register_once(e,a,r)}register_for_session(e){var a;(a=this.sessionPersistence)==null||a.register(e)}unregister(e){var a;(a=this.persistence)==null||a.unregister(e)}unregister_for_session(e){var a;(a=this.sessionPersistence)==null||a.unregister(e)}gs(e,a){this.register({[e]:a})}getFeatureFlag(e,a){return this.featureFlags.getFeatureFlag(e,a)}getFeatureFlagPayload(e){return this.featureFlags.getFeatureFlagPayload(e)}getFeatureFlagResult(e,a){return this.featureFlags.getFeatureFlagResult(e,a)}isFeatureEnabled(e,a){return this.featureFlags.isFeatureEnabled(e,a)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateFlags(e,a,r){var n=r!=null&&r.merge?this.featureFlags.getFlagVariants():{},o=r!=null&&r.merge?this.featureFlags.getFlagPayloads():{},i=j({},n,e),s=j({},o,a),l={};for(var[u,c]of Object.entries(i)){var d=typeof c=="string";l[u]={key:u,enabled:!!d||!!c,variant:d?c:void 0,reason:void 0,metadata:V(s?.[u])?void 0:{id:0,version:void 0,description:void 0,payload:s[u]}}}this.featureFlags.receivedFeatureFlags({flags:l})}updateEarlyAccessFeatureEnrollment(e,a,r){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,a,r)}getEarlyAccessFeatures(e,a,r){return a===void 0&&(a=!1),this.featureFlags.getEarlyAccessFeatures(e,a,r)}on(e,a){return this.qr.on(e,a)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var a,r;return(a=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&a!==void 0?a:()=>{}}getSurveys(e,a){a===void 0&&(a=!1),this.surveys.getSurveys(e,a)}getActiveMatchingSurveys(e,a){a===void 0&&(a=!1),this.surveys.getActiveMatchingSurveys(e,a)}renderSurvey(e,a){this.surveys.renderSurvey(e,a)}displaySurvey(e,a){a===void 0&&(a=l4),this.surveys.displaySurvey(e,a)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,a){return a===void 0&&(a=!1),this.surveys.canRenderSurveyAsync(e,a)}identify(e,a,r){if(!this.__loaded||!this.persistence)return $.uninitializedWarning("posthog.identify");if(yn(e)&&(e=e.toString(),$.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))$.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==Yu){if(this.ps("posthog.identify")){var n=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var o=n;this.register_once({$had_persisted_distinct_id:!0,$device_id:o},"")}e!==n&&e!==this.get_property(sc)&&(this.unregister(sc),this.register({distinct_id:e}));var i=(this.persistence.get_property(pn)||"anonymous")==="anonymous";e!==n&&i?(this.persistence.set_property(pn,"identified"),this.setPersonPropertiesForFlags(j({},r||{},a||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:n},{$set:a||{},$set_once:r||{}}),this.Jr=oE(e,a,r),this.featureFlags.setAnonymousDistinctId(n)):(a||r)&&this.setPersonProperties(a,r),e!==n&&(this.reloadFeatureFlags(),this.unregister(Wp))}}else $.critical('The string "'+Yu+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else $.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,a){if((e||a)&&this.ps("posthog.setPersonProperties")){var r=oE(this.get_distinct_id(),e,a);this.Jr!==r?(this.setPersonPropertiesForFlags(j({},a||{},e||{})),this.capture("$set",{$set:e||{},$set_once:a||{}}),this.Jr=r):$.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,a,r){if(e&&a){var n=this.getGroups();n[e]!==a&&this.resetGroupPropertiesForFlags(e),this.register({$groups:j({},n,{[e]:a})}),r&&(this.capture("$groupidentify",{$group_type:e,$group_key:a,$group_set:r}),this.setGroupPropertiesForFlags({[e]:r})),n[e]===a||r||this.reloadFeatureFlags()}else $.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,a){a===void 0&&(a=!0),this.featureFlags.setPersonPropertiesForFlags(e,a)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,a){a===void 0&&(a=!0),this.ps("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,a)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var a,r,n,o;if($.info("reset"),!this.__loaded)return $.uninitializedWarning("posthog.reset");var i=this.get_property("$device_id");if(this.consent.reset(),(a=this.persistence)==null||a.clear(),(r=this.sessionPersistence)==null||r.clear(),this.surveys.reset(),this.featureFlags.reset(),(n=this.persistence)==null||n.set_property(pn,"anonymous"),(o=this.sessionManager)==null||o.resetSessionId(),this.Jr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:Yu,$device_id:null},"");else{var s=this.config.get_device_id(So());this.register_once({distinct_id:s,$device_id:e?s:i},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,a;return(e=(a=this.sessionManager)==null?void 0:a.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:a,sessionStartTimestamp:r}=this.sessionManager.checkAndGetSessionAndWindowId(!0),n=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+a);if(e!=null&&e.withTimestamp&&r){var o,i=(o=e.timestampLookBack)!==null&&o!==void 0?o:10;if(!r)return n;n+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-i,0)}return n}alias(e,a){return e===this.get_property(qE)?($.critical("Attempting to create alias for existing People user - aborting."),-2):this.ps("posthog.alias")?(V(a)&&(a=this.get_distinct_id()),e!==a?(this.gs(sc,e),this.capture("$create_alias",{alias:e,distinct_id:a})):($.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var a=j({},this.config);if(gt(e)){var r,n,o,i,s,l,u;ot(this.config,mE(e));var c=this.Qr();(r=this.persistence)==null||r.update_config(this.config,a,c),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new mc(j({},this.config,{persistence:"sessionStorage"}),c);var d=this.Kr(this.config.debug);vn(d)&&(this.config.debug=d),vn(this.config.debug)&&(this.config.debug?(fn.DEBUG=!0,Ke.H()&&Ke.G("ph_debug","true"),$.info("set_config",{config:e,oldConfig:a,newConfig:j({},this.config)})):(fn.DEBUG=!1,Ke.H()&&Ke.V("ph_debug"))),(n=this.exceptionObserver)==null||n.onConfigChange(),(o=this.sessionRecording)==null||o.startIfEnabledOrStop(),(i=this.autocapture)==null||i.startIfEnabled(),(s=this.heatmaps)==null||s.startIfEnabled(),(l=this.exceptionObserver)==null||l.startIfEnabledOrStop(),this.surveys.loadIfEnabled(),this._s(),(u=this.externalIntegrations)==null||u.startIfEnabledOrStop()}}startSessionRecording(e){var a=e===!0,r={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};if(Object.values(r).some(Boolean)){var n,o,i,s,l;(n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),r.sampling&&((o=this.sessionRecording)==null||o.overrideSampling()),r.linked_flag&&((i=this.sessionRecording)==null||i.overrideLinkedFlag()),r.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),r.event_trigger&&((l=this.sessionRecording)==null||l.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,a){var r=new Error("PostHog syntheticException"),n=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(j({},n,a))}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var a;return(a=this.persistence)==null?void 0:a.props[e]}getSessionProperty(e){var a;return(a=this.sessionPersistence)==null?void 0:a.props[e]}toString(){var e,a=(e=this.config.name)!==null&&e!==void 0?e:Ws;return a!==Ws&&(a=Ws+"."+a),a}_isIdentified(){var e,a;return((e=this.persistence)==null?void 0:e.get_property(pn))==="identified"||((a=this.sessionPersistence)==null?void 0:a.get_property(pn))==="identified"}fs(){var e,a;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&Xs(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[sc])&&((a=this.persistence)==null||(a=a.props)==null||!a[Xp]))}ds(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.fs()||this.ps("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.ps("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}ps(e){return this.config.person_profiles==="never"?($.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.gs(Xp,!0),!0)}Qr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),a=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!a}_s(){var e,a,r,n,o=this.Qr();return((e=this.persistence)==null?void 0:e.ki)!==o&&((r=this.persistence)==null||r.set_disabled(o)),((a=this.sessionPersistence)==null?void 0:a.ki)!==o&&((n=this.sessionPersistence)==null||n.set_disabled(o)),o}opt_in_capturing(e){var a;if(this.config.cookieless_mode!=="always"){var r,n,o;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(r=this.sessionManager)==null||r.destroy(),(n=this.pageViewManager)==null||n.destroy(),this.sessionManager=new lh(this),this.pageViewManager=new ah(this),this.persistence&&(this.sessionPropsManager=new sh(this,this.sessionManager,this.persistence)),this.sessionRecording=new uh(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this._s(),this.us(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(V(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((o=e?.captureEventName)!==null&&o!==void 0?o:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.hs()}else $.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,a,r;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this._s(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:Yu,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),(a=this.pageViewManager)==null||a.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(r=this.sessionRecording)==null||r.stopRecording(),this.sessionRecording=void 0,this.hs())):$.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===hn.GRANTED?"granted":e===hn.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this._s()}_is_bot(){return ka?ST(ka,this.config.custom_blocked_useragents):void 0}hs(){q&&(q.visibilityState==="visible"?this.Wr||(this.Wr=!0,this.capture("$pageview",{title:q.title},{send_instantly:!0}),this.Gr&&(q.removeEventListener("visibilitychange",this.Gr),this.Gr=null)):this.Gr||(this.Gr=this.hs.bind(this),ft(q,"visibilitychange",this.Gr)))}debug(e){e===!1?(T?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(T?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}M(){var e,a,r,n,o,i,s,l=this.Yr||{};return"advanced_disable_flags"in l?!!l.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?($.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(r="advanced_disable_decide",n=!1,o=$,i=(a="advanced_disable_flags")in(e=l)&&!ge(e[a]),s=r in e&&!ge(e[r]),i?e[a]:s?(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+a+"' instead. The old field will be removed in a future major version."),e[r]):n)}cs(e){if(ge(this.config.before_send))return e;var a=Ce(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var n of a){if(r=n(r),ge(r)){var o="Event '"+e.event+"' was rejected in beforeSend function";return VH(e.event)?$.warn(o+". This can cause unexpected behavior."):$.info(o),null}r.properties&&!Xs(r.properties)||$.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return r}getPageViewId(){var e;return(e=this.pageViewManager.Kt)==null?void 0:e.pageViewId}captureTraceFeedback(e,a){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:a})}captureTraceMetric(e,a,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:a,$ai_metric_value:String(r)})}Kr(e){var a=vn(e)&&!e,r=Ke.H()&&Ke.q("ph_debug")==="true";return!a&&(!!r||e)}};(function(t,e){for(var a=0;a<e.length;a++)t.prototype[e[a]]=m3(t.prototype[e[a]])})(ch,["identify"]);var gE;var CT=(gE=gc[Ws]=new ch,(function(){function t(){t.done||(t.done=!0,_T=!1,Be(gc,(function(e){e._dom_loaded()})))}q!=null&&q.addEventListener?q.readyState==="complete"?t():ft(q,"DOMContentLoaded",t,{capture:!1}):T&&$.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),gE);var Vb=class{constructor(e={}){this.options=e;B(this,"client");B(this,"featureFlagsCallback");B(this,"captureCallback");B(this,"rrwebCallback");if(this.client=e.client,this.featureFlagsCallback=e.onFeatureFlagsLoaded,this.captureCallback=e.onCapture,this.rrwebCallback=e.onRRWebEvent,!this.client&&e.consent&&e.requireExplicitConsent&&typeof window<"u"&&e.apiKey){let a=e.consent;a.getStatus()==="granted"&&this.initPostHog(),a.subscribe(n=>{n==="granted"?this.client?this.client.opt_in_capturing():this.initPostHog():n==="denied"&&this.client&&this.client.opt_out_capturing()});return}!this.client&&typeof window<"u"&&e.apiKey&&this.initPostHog()}initPostHog(){let e=this.options;if(!e.apiKey)return;let a=e.enableFeatureFlags??!0,r=`syntro_${e.apiKey.slice(-6)||"sdk"}`,n={api_host:e.apiHost??"https://telemetry.syntrologie.com",advanced_disable_feature_flags:!a,advanced_disable_feature_flags_on_first_load:!a,autocapture:e.autocapture??!0,capture_pageview:e.capturePageview??"history_change",capture_pageleave:e.capturePageleave??!0,disable_session_recording:!(e.sessionRecording??!0),opt_out_useragent_filter:!0,session_recording:{recordCrossDomainIFrames:!0},capture_performance:!0,enable_recording_console_log:!0},o=CT.init(e.apiKey,n,r);if(o&&(this.client=o),this.captureCallback&&this.client&&this.client.on("eventCaptured",(...i)=>{let s=i[0],l=typeof s=="string"?s:s?.event,u=typeof s=="string"?void 0:s?.properties;typeof l=="string"&&this.captureCallback?.(l,u)}),a&&this.featureFlagsCallback&&this.client){this.client.onFeatureFlags(()=>{let s=this.getAllFeatureFlags();s&&this.featureFlagsCallback&&this.featureFlagsCallback(s)});let i=this.getAllFeatureFlags();i&&Object.keys(i).length>0&&this.featureFlagsCallback(i)}this.rrwebCallback&&this.client&&this.setupRRWebIntercept()}setupRRWebIntercept(e=30){let a=this.client?.sessionRecording;if(!a){e>0&&setTimeout(()=>this.setupRRWebIntercept(e-1),500);return}let r=null,n=a;for(let i of Object.getOwnPropertyNames(n)){let s=n[i];if(s&&typeof s=="object"&&typeof s.onRRwebEmit=="function"&&typeof s.start=="function"&&s!==a){r=s;break}}if(!r){e>0&&setTimeout(()=>this.setupRRWebIntercept(e-1),500);return}let o=r.onRRwebEmit.bind(r);r.onRRwebEmit=i=>{this.rrwebCallback?.({kind:"rrweb",...i}),o(i)},typeof window<"u"&&(window.__RRWEB_INTERCEPT_READY__=!0)}getAllFeatureFlags(){return this.client?.featureFlags?.getFlagVariants()}getSegmentFlags(){let e=this.getAllFeatureFlags();if(!e)return{};let a={};for(let[r,n]of Object.entries(e))r.startsWith("in_segment_")&&(a[r]=n===!0);return a}identify(e,a){this.client?.identify(e,a)}alias(e,a){this.client?.alias(e,a)}track(e,a){this.client?.capture(e,a)}trackCanvasOpened(e){this.track("shadow_canvas_opened",{surface:e})}trackCanvasClosed(e){this.track("shadow_canvas_closed",{surface:e})}trackRectangleViewed(e,a){this.track("shadow_canvas_rectangle_viewed",{rectangleId:e,surface:a})}trackAction(e,a,r){this.track("shadow_canvas_action",{action:e,rectangleId:a,surface:r})}register(e){this.client?.register?.(e)}getSessionId(){return this.client?.get_session_id?.()}startSessionRecording(){this.client?.startSessionRecording?.()}trackExperiment(e,a,r){let n=`$experiment_${e}`;this.register({[n]:r??`variation_${a}`,[`${n}_id`]:a}),this.track("$experiment_started",{$experiment_key:e,$experiment_variation_id:a,$experiment_variation_name:r??`variation_${a}`})}setPersonProperties(e){this.client?.capture("$set",{$set:e})}setPersonPropertiesOnce(e){this.client?.capture("$set",{$set_once:e})}getDistinctId(){return this.client?.get_distinct_id?.()}};function $b(t={}){return new Vb(t)}var kc=class{constructor(e,a){B(this,"telemetry");B(this,"variantId");B(this,"seenSet",new Set);B(this,"triggeredSet",new Set);this.telemetry=e,this.variantId=a}trackServed(e,a){this.telemetry.track?.("syntro_config_served",{variant_id:this.variantId,tiles:e,actions:a})}trackSeen(e,a){this.seenSet.has(e)||(this.seenSet.add(e),this.telemetry.track?.("syntro_intervention_seen",{variant_id:this.variantId,intervention_id:e,intervention_kind:a}))}trackTriggered(e,a){this.triggeredSet.has(e)||(this.triggeredSet.add(e),this.telemetry.track?.("syntro_intervention_triggered",{variant_id:this.variantId,intervention_id:e,intervention_kind:a}))}trackInteracted(e,a,r){this.telemetry.track?.("syntro_intervention_interacted",{variant_id:this.variantId,intervention_id:e,intervention_kind:a,interaction_type:r})}resetPage(){this.seenSet.clear(),this.triggeredSet.clear()}};var jb=async(t,e)=>{let a=[];if(e.applyAction)for(let r of t.actions){let n=await e.applyAction(r);a.push(n)}return{cleanup:async()=>{for(let r=a.length-1;r>=0;r--)try{await a[r].revert()}catch{}}}},Gb=async(t,e)=>{let a=[];if(e.applyAction){let r=t.actions.map(n=>e.applyAction(n));if(t.waitFor==="any"){let n=await Promise.race(r);a.push(n);let o=await Promise.allSettled(r);for(let i of o)i.status==="fulfilled"&&i.value!==n&&a.push(i.value)}else{let n=await Promise.all(r);a.push(...n)}}return{cleanup:async()=>{for(let r of a)try{await r.revert()}catch{}}}},Wb=async(t,e)=>{let a,r,n=!1,o={cleanup:()=>{n=!0,r&&clearTimeout(r),a&&a()}};return t.event&&e.subscribeEvent?await new Promise(i=>{a=e.subscribeEvent(t.event,()=>{n||i()}),t.durationMs!==void 0&&(r=setTimeout(()=>{n||i()},t.durationMs))}):t.durationMs!==void 0&&await new Promise(i=>{r=setTimeout(()=>{n||i()},t.durationMs)}),o};var hh=class{constructor(){B(this,"executors",new Map);for(let{kind:e,executor:a}of xv)this.registerCore(e,a);for(let{kind:e,executor:a}of Rv)this.registerCore(e,a);this.registerCore("core:mountWidget",async()=>{throw new Error("core:mountWidget must be handled by ActionEngine")}),this.registerCore("core:sequence",jb),this.registerCore("core:parallel",Gb),this.registerCore("core:wait",Wb)}registerCore(e,a,r){this.executors.set(e,{kind:e,executor:a,schema:r,source:"core",isBuiltIn:!0})}register(e,a,r,n="custom",o=!1){if(this.executors.has(e)){if(this.executors.get(e).isBuiltIn)return;console.warn(`[ExecutorRegistry] Overriding executor for kind: ${e} (source: ${n})`)}console.log(`[ExecutorRegistry] Registered executor: ${e} (source: ${n})`),this.executors.set(e,{kind:e,executor:a,schema:r,source:n,isBuiltIn:o})}unregister(e){let a=this.executors.get(e);return a?a.isBuiltIn?(console.warn(`[ExecutorRegistry] Cannot unregister built-in executor: ${e}`),!1):(this.executors.delete(e),!0):!1}unregisterBySource(e){for(let[a,r]of this.executors.entries())r.source===e&&this.executors.delete(a)}get(e){return this.executors.get(e)?.executor}getRegistration(e){return this.executors.get(e)}has(e){return this.executors.has(e)}validate(e){let a=[];if(!e||typeof e!="object")return a.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:a,warnings:[]};let{kind:r}=e;if(!r||typeof r!="string")return a.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:a,warnings:[]};let n=this.executors.get(r);if(!n)return a.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${r}`,field:"kind"}),{valid:!1,errors:a,warnings:[]};if(n.schema){let o=n.schema.safeParse(e);if(!o.success){for(let i of o.error.issues)a.push({code:"SCHEMA_VALIDATION_ERROR",message:i.message,field:i.path.join(".")});return{valid:!1,errors:a,warnings:[]}}}return{valid:!0,errors:[],warnings:[]}}list(){return Array.from(this.executors.keys())}listRegistrations(){return Array.from(this.executors.values())}getBuiltInKinds(){return Array.from(this.executors.entries()).filter(([,e])=>e.isBuiltIn).map(([e])=>e)}getCustomKinds(){return Array.from(this.executors.entries()).filter(([,e])=>!e.isBuiltIn).map(([e])=>e)}},xn=new hh;function m4(t){return xn.get(t)}function Zb(t){return xn.has(t)}function Xb(t,e,a){!t.content||typeof t.content!="string"?e.push({code:"MISSING_CONTENT",message:"Badge action requires 'content' property",field:"content"}):t.content.length>100&&a.push({code:"LONG_BADGE_CONTENT",message:"Badge content is quite long",suggestion:"Keep badge content short (under 100 characters)"})}function Kb(t,e,a){if(!t.content||typeof t.content!="object"){e.push({code:"MISSING_CONTENT",message:"Tooltip action requires 'content' object",field:"content"});return}(!t.content.body||typeof t.content.body!="string")&&e.push({code:"MISSING_BODY",message:"Tooltip content requires 'body' property",field:"content.body"})}function Yb(t,e,a){!t.html||typeof t.html!="string"?e.push({code:"MISSING_HTML",message:"insertHtml action requires 'html' property",field:"html"}):t.html.length>mh&&e.push({code:"HTML_TOO_LONG",message:`HTML content exceeds maximum length of ${mh}`,field:"html"});let r=["before","after","prepend","append","replace"];(!t.position||!r.includes(t.position))&&e.push({code:"INVALID_POSITION",message:`Position must be one of: ${r.join(", ")}`,field:"position"})}function Qb(t,e,a){(t.text===void 0||t.text===null)&&e.push({code:"MISSING_TEXT",message:"setText action requires 'text' property",field:"text"})}function Jb(t,e,a){!t.attr||typeof t.attr!="string"?e.push({code:"MISSING_ATTR",message:"setAttr action requires 'attr' property",field:"attr"}):(u0.has(t.attr.toLowerCase())||t.attr.toLowerCase().startsWith("on"))&&e.push({code:"DANGEROUS_ATTR",message:`Event handler attributes are not allowed: ${t.attr}`,field:"attr"}),(t.value===void 0||t.value===null)&&e.push({code:"MISSING_VALUE",message:"setAttr action requires 'value' property",field:"value"})}function e0(t,e,a){!t.className||typeof t.className!="string"?e.push({code:"MISSING_CLASS_NAME",message:"Class action requires 'className' property",field:"className"}):/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t.className)||a.push({code:"INVALID_CLASS_NAME",message:"Class name contains unusual characters",suggestion:"Use alphanumeric characters, hyphens, and underscores"})}function t0(t,e,a){if(!t.styles||typeof t.styles!="object")e.push({code:"MISSING_STYLES",message:"setStyle action requires 'styles' object",field:"styles"});else{let r=Object.keys(t.styles).length;r>gh&&e.push({code:"TOO_MANY_STYLES",message:`Too many styles (${r}). Maximum is ${gh}`,field:"styles"});for(let[n,o]of Object.entries(t.styles))typeof o=="string"&&o.includes("expression(")&&e.push({code:"DANGEROUS_STYLE",message:`Style expressions are not allowed: ${n}`,field:`styles.${n}`})}}function a0(t,e,a){(!t.slot||typeof t.slot!="string")&&e.push({code:"MISSING_SLOT",message:"mountWidget action requires 'slot' property",field:"slot"}),!t.widget||typeof t.widget!="object"?e.push({code:"MISSING_WIDGET",message:"mountWidget action requires 'widget' object",field:"widget"}):(!t.widget.widgetId||typeof t.widget.widgetId!="string")&&e.push({code:"MISSING_WIDGET_ID",message:"Widget must have a 'widgetId' property",field:"widget.widgetId"})}function r0(t,e,a){t.durationMs===void 0&&!t.event&&e.push({code:"MISSING_WAIT_CONFIG",message:"wait action requires either 'durationMs' or 'event' property"}),t.durationMs!==void 0&&t.durationMs<0&&e.push({code:"INVALID_DURATION",message:"durationMs must be a positive number",field:"durationMs"}),t.event!==void 0&&typeof t.event!="string"&&e.push({code:"INVALID_EVENT",message:"event must be a string",field:"event"})}function n0(t,e,a){if(!t.actions||!Array.isArray(t.actions)){e.push({code:"MISSING_ACTIONS",message:"sequence action requires 'actions' array",field:"actions"});return}t.actions.length===0&&a.push({code:"EMPTY_SEQUENCE",message:"sequence has no actions",suggestion:"Add at least one action to the sequence"});for(let r=0;r<t.actions.length;r++){let n=Ar(t.actions[r]);for(let o of n.errors)e.push({...o,field:`actions[${r}]${o.field?`.${o.field}`:""}`});for(let o of n.warnings)a.push(o)}}function o0(t,e,a){if(!t.actions||!Array.isArray(t.actions)){e.push({code:"MISSING_ACTIONS",message:"parallel action requires 'actions' array",field:"actions"});return}t.actions.length===0&&a.push({code:"EMPTY_PARALLEL",message:"parallel has no actions",suggestion:"Add at least one action to the parallel group"}),t.waitFor&&!["all","any"].includes(t.waitFor)&&e.push({code:"INVALID_WAIT_FOR",message:"waitFor must be 'all' or 'any'",field:"waitFor"});for(let r=0;r<t.actions.length;r++){let n=Ar(t.actions[r]);for(let o of n.errors)e.push({...o,field:`actions[${r}]${o.field?`.${o.field}`:""}`});for(let o of n.warnings)a.push(o)}}function i0(t,e,a){if(!t.url||typeof t.url!="string")e.push({code:"MISSING_URL",message:"navigate action requires 'url' property",field:"url"});else{let r=t.url.trim().toLowerCase();r.startsWith("javascript:")&&e.push({code:"DANGEROUS_URL",message:"javascript: URLs are not allowed",field:"url"}),r.startsWith("data:")&&a.push({code:"DATA_URL",message:"data: URLs may have limited support",suggestion:"Consider using a regular URL instead"})}}function s0(t,e,a){if(!t.content||typeof t.content!="object"){e.push({code:"MISSING_CONTENT",message:"Modal action requires 'content' object",field:"content"});return}if((!t.content.body||typeof t.content.body!="string")&&e.push({code:"MISSING_BODY",message:"Modal content requires 'body' property",field:"content.body"}),t.size&&!["sm","md","lg"].includes(t.size)&&e.push({code:"INVALID_SIZE",message:"Modal size must be 'sm', 'md', or 'lg'",field:"size"}),t.ctaButtons)if(!Array.isArray(t.ctaButtons))e.push({code:"INVALID_CTA_BUTTONS",message:"ctaButtons must be an array",field:"ctaButtons"});else for(let r=0;r<t.ctaButtons.length;r++){let n=t.ctaButtons[r];(!n.label||typeof n.label!="string")&&e.push({code:"MISSING_BUTTON_LABEL",message:`CTA button at index ${r} requires 'label' property`,field:`ctaButtons[${r}].label`}),(!n.actionId||typeof n.actionId!="string")&&e.push({code:"MISSING_BUTTON_ACTION_ID",message:`CTA button at index ${r} requires 'actionId' property`,field:`ctaButtons[${r}].actionId`})}}function l0(t,e,a){if((!t.tourId||typeof t.tourId!="string")&&e.push({code:"MISSING_TOUR_ID",message:"Tour action requires 'tourId' property",field:"tourId"}),!t.steps||!Array.isArray(t.steps)){e.push({code:"MISSING_STEPS",message:"Tour action requires 'steps' array",field:"steps"});return}t.steps.length===0&&e.push({code:"EMPTY_STEPS",message:"Tour must have at least one step",field:"steps"});let r=new Set;for(let n=0;n<t.steps.length;n++){let o=t.steps[n];if(!o.id||typeof o.id!="string"?e.push({code:"MISSING_STEP_ID",message:`Step at index ${n} requires 'id' property`,field:`steps[${n}].id`}):(r.has(o.id)&&e.push({code:"DUPLICATE_STEP_ID",message:`Duplicate step ID: ${o.id}`,field:`steps[${n}].id`}),r.add(o.id)),!o.action)e.push({code:"MISSING_STEP_ACTION",message:`Step at index ${n} requires 'action' property`,field:`steps[${n}].action`});else{let i=Ar(o.action);for(let s of i.errors)e.push({...s,field:`steps[${n}].action${s.field?`.${s.field}`:""}`});for(let s of i.warnings)a.push(s)}if(o.onAction)for(let[i,s]of Object.entries(o.onAction))s!=="end"&&!t.steps.some(l=>l.id===s)&&a.push({code:"UNKNOWN_TARGET_STEP",message:`Step "${o.id}" references unknown target step: ${s}`,suggestion:`Make sure step "${s}" exists in the tour`})}}var u0=new Set(["onclick","onerror","onload","onmouseover","onfocus","onblur","onchange","onsubmit","onkeydown","onkeyup","onkeypress"]),mh=5e4,gh=50;function Ar(t){let e=[],a=[];if(!t||typeof t!="object")return e.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:e,warnings:a};let{kind:r}=t;if(!r||typeof r!="string")return e.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:e,warnings:a};if(!Zb(r)&&r!=="core:mountWidget"){let n=xn.list();return console.error(`[ActionValidation] Unknown action kind: "${r}". Registered kinds (${n.length}): [${n.join(", ")}]. This usually means the app that provides "${r}" hasn't been activated yet, or the executor was never registered in ExecutorRegistry.`),e.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${r}`,field:"kind"}),{valid:!1,errors:e,warnings:a}}switch(r){case"overlays:highlight":case"overlays:pulse":case"navigation:scrollTo":bn(t,e,a);break;case"overlays:badge":bn(t,e,a),Xb(t,e,a);break;case"overlays:tooltip":bn(t,e,a),Kb(t,e,a);break;case"overlays:modal":s0(t,e,a);break;case"content:insertHtml":bn(t,e,a),Yb(t,e,a);break;case"content:setText":bn(t,e,a),Qb(t,e,a);break;case"content:setAttr":bn(t,e,a),Jb(t,e,a);break;case"content:addClass":case"content:removeClass":bn(t,e,a),e0(t,e,a);break;case"content:setStyle":bn(t,e,a),t0(t,e,a);break;case"core:mountWidget":a0(t,e,a);break;case"core:wait":r0(t,e,a);break;case"core:sequence":n0(t,e,a);break;case"core:parallel":o0(t,e,a);break;case"overlays:tour":l0(t,e,a);break;case"navigation:navigate":i0(t,e,a);break}return{valid:e.length===0,errors:e,warnings:a}}function bn(t,e,a){let r=t.anchorId;if(!r||typeof r!="object"){e.push({code:"MISSING_ANCHOR_ID",message:"Action requires an 'anchorId' object with a 'selector' string",field:"anchorId"});return}if(!r.selector||typeof r.selector!="string"?e.push({code:"MISSING_ANCHOR_SELECTOR",message:"anchorId requires a 'selector' string",field:"anchorId.selector"}):r.selector.length>200&&a.push({code:"LONG_ANCHOR_ID",message:"Anchor selector is unusually long",suggestion:"Consider using a shorter, more descriptive selector"}),r.route===void 0||r.route===null)e.push({code:"MISSING_ANCHOR_ROUTE",message:`anchorId requires a 'route' (string or array of strings). Use "**" for all routes.`,field:"anchorId.route"});else{let n=Array.isArray(r.route)?r.route:[r.route];for(let o of n)if(typeof o!="string"){e.push({code:"INVALID_ANCHOR_ROUTE",message:"anchorId.route must be a string or array of strings",field:"anchorId.route"});break}}}function vh(t){let e=[],a=[];if(!Array.isArray(t))return console.error("[ActionValidation] validateActions called with non-array:",typeof t),e.push({code:"INVALID_ACTIONS",message:"Actions must be an array"}),{valid:!1,errors:e,warnings:a};for(let r=0;r<t.length;r++){let n=Ar(t[r]);if(!n.valid){let o=t[r];console.error(`[ActionValidation] Action [${r}] failed validation:`,`kind="${o?.kind??"undefined"}"`,n.errors.map(i=>`${i.code}: ${i.message}`).join("; "),o)}for(let o of n.errors)e.push({...o,field:o.field?`[${r}].${o.field}`:`[${r}]`});for(let o of n.warnings)a.push({...o,suggestion:o.suggestion?`Action ${r}: ${o.suggestion}`:void 0})}return e.length>0&&console.error(`[ActionValidation] Batch validation failed: ${e.length} error(s) in ${t.length} action(s).`,e.map(r=>`${r.field??"?"}: ${r.message}`).join(" | ")),{valid:e.length===0,errors:e,warnings:a}}var g4=0;function c0(t){let{overlayRoot:e,eventBus:a,surfaces:r,anchorResolver:n,waitForAnchor:o,adaptiveId:i,executorRegistry:s=xn,subscribeNavigation:l,runtime:u}=t,c=new Map,d=new Map;function f(){return`action-${++g4}`}function h(_,L){a&&a.publish(_,L)}function S(){return{overlayRoot:e,resolveAnchor:n,waitForAnchor:o,generateId:f,publishEvent:h,adaptiveId:i,applyAction:m,subscribeEvent:a?(_,L)=>a.subscribe({names:[_]},A=>L(A.props)):void 0,subscribeNavigation:l}}async function x(_,L){if(!r)throw new Error("Surfaces provider required for core:mountWidget actions");let A=r.mount(_.slot,{type:"widget",widgetId:_.widget.widgetId,config:_.widget.props},{priority:_.widget.priority});return L.publishEvent("action.applied",{id:L.generateId(),kind:"core:mountWidget",slot:_.slot,widgetId:_.widget.widgetId}),{cleanup:()=>{A.unmount()},updateFn:I=>{if("widget"in I&&I.widget){let O=I.widget;O.props&&A.update({type:"widget",widgetId:_.widget.widgetId,config:O.props})}}}}async function b(_,L){if(_.kind==="core:mountWidget")return x(_,L);let A=s.get(_.kind);if(!A){let I="list"in s?s.list():"(list unavailable)";throw console.error(`[ActionEngine] No executor for kind="${_.kind}".`,`Registered: [${I}]`),new Error(`No executor for action kind: ${_.kind}`)}return A(_,L)}function g(_,L,A,I){if(!u)return;let O=[],H=async()=>{let E=c.get(_);if(!E)return;let M=u.evaluateSync(A).value;if(E.state==="applied"&&!M){try{await E.cleanup()}catch(F){console.error(`[ActionEngine] Error reverting conditional action ${_}:`,F)}E.state="deferred",E.cleanup=()=>{},E.updateFn=void 0,h("action.deferred",{id:_,kind:L.kind})}else if(E.state==="deferred"&&M)try{let F=S(),Z=await b(L,F);E.state="applied",E.cleanup=Z.cleanup,E.updateFn=Z.updateFn,E.appliedTs=Date.now(),h("action.applied",{id:_,kind:L.kind,anchorId:"anchorId"in L?L.anchorId:void 0})}catch(F){console.error(`[ActionEngine] Error applying deferred action ${_}:`,F),E.state="failed"}};u.context&&O.push(u.context.subscribe(H)),u.accumulator&&O.push(u.accumulator.subscribe(H)),d.set(_,O)}async function m(_){let L=Ar(_);if(!L.valid){let M=L.errors.map(F=>F.message).join("; ");throw console.error(`[ActionEngine] Validation failed for action kind="${_?.kind}":`,M,_),new Error(`Action validation failed: ${M}`)}let A=f(),I=_.triggerWhen;if(I&&u&&!u.evaluateSync(I).value){let F={id:A,action:_,adaptiveId:i,appliedTs:Date.now(),state:"deferred",cleanup:()=>{}};c.set(A,F);let Z={id:A,action:_,async revert(){let U=c.get(A);if(!U)return;let W=d.get(A);if(W){for(let ce of W)ce();d.delete(A)}U.state="reverted",c.delete(A)},isApplied(){return c.get(A)?.state==="applied"},async update(U){let W=c.get(A);if(!W||W.state!=="applied")throw new Error("Cannot update action that is not applied");if(W.updateFn)await W.updateFn(U);else throw new Error(`Action kind ${_.kind} does not support updates`)},getState(){return c.get(A)?.state??"reverted"}};return g(A,_,I,Z),Z}let O=S(),H=await b(_,O),E={id:A,action:_,adaptiveId:i,appliedTs:Date.now(),state:"applied",cleanup:H.cleanup,updateFn:H.updateFn};c.set(A,E),h("action.applied",{id:A,kind:_.kind,anchorId:"anchorId"in _?_.anchorId:void 0});let R={id:A,action:_,async revert(){let M=c.get(A);if(!M||M.state!=="applied")return;let F=d.get(A);if(F){for(let Z of F)Z();d.delete(A)}try{await M.cleanup(),M.state="reverted",h("action.reverted",{id:A,kind:_.kind})}catch(Z){console.warn(`[ActionEngine] Cleanup error for ${_.kind} (${A}), ignoring:`,Z),M.state="reverted",h("action.reverted",{id:A,kind:_.kind})}finally{c.delete(A)}},isApplied(){return c.get(A)?.state==="applied"},async update(M){let F=c.get(A);if(!F||F.state!=="applied")throw new Error("Cannot update action that is not applied");if(F.updateFn)await F.updateFn(M);else throw new Error(`Action kind ${_.kind} does not support updates`)},getState(){return c.get(A)?.state??"reverted"}};return I&&u&&g(A,_,I,R),R}async function y(_){console.log(`[ActionEngine] applyBatch: ${_.length} action(s)`,_.map(E=>E.kind).join(", "));let L=vh(_);if(!L.valid){let E=L.errors.map(R=>R.message).join("; ");throw console.error(`[ActionEngine] Batch validation FAILED for ${_.length} action(s):`,E,`
502
502
  Actions:`,_.map((R,M)=>` [${M}] ${R.kind} ${R.anchorId?`anchor="${R.anchorId.selector}"`:""} ${R.label?`label="${R.label}"`:""}`).join(`
503
- `)),new Error(`Batch validation failed: ${E}`)}let A=f(),I=[],O=[];try{let E=await Promise.allSettled(_.map(M=>m(M))),R=[];for(let M of E)M.status==="fulfilled"?(I.push(M.value),O.push(M.value)):R.push(M.reason instanceof Error?M.reason:new Error(String(M.reason)));if(R.length>0&&O.length===0)throw R[0];R.length>0&&console.warn(`[ActionEngine] ${R.length}/${_.length} action(s) failed in batch:`,R.map(M=>M.message).join("; "))}catch(E){console.error(`[ActionEngine] Batch apply FAILED. Successfully applied: ${O.length}. Rolling back...`,E);for(let R of O)try{await R.revert()}catch{}throw E}return{id:A,handles:I,async revertAll(){for(let E=I.length-1;E>=0;E--)try{await I[E].revert()}catch(R){console.error(`[ActionEngine] Error reverting action ${I[E].id}:`,R)}},isApplied(){return I.every(E=>E.isApplied())}}}function v(_){return Ar(_)}function C(){return Array.from(c.values()).map(_=>({id:_.id,action:_.action,adaptiveId:_.adaptiveId,appliedTs:_.appliedTs,state:_.state}))}function w(){for(let _ of d.values())for(let L of _)try{L()}catch{}d.clear();for(let _ of c.values())if(_.state==="applied")try{_.cleanup()}catch(L){console.error("[ActionEngine] Error during cleanup:",L)}c.clear()}return{apply:m,applyBatch:y,validate:v,getActive:C,destroy:w}}var v4=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),wT=["ui.click","ui.scroll","ui.input","ui.change","ui.submit","ui.hover","ui.idle","ui.scroll_thrash","ui.focus_bounce","nav.page_view","nav.page_leave","behavior.rage_click","behavior.hesitation","behavior.confusion"],LT=p.enum(wT).describe("Event name to count. ui.* = user interactions and behavioral detectors, nav.* = page navigation, behavior.* = derived behavioral signals."),kT=["time_on_page","page_views","scroll_depth"],IT=p.enum(kT).describe("Session metric key. time_on_page = seconds on current page, page_views = pages visited this session, scroll_depth = 0-100 percentage.");var d0=p.object({type:p.literal("page_url"),url:p.string().describe('URL path to match (e.g. "/pricing", "/dashboard")')}).describe('Fires when the current page URL matches. Use for page-specific actions. Example: {"type": "page_url", "url": "/pricing"}'),f0=p.object({type:p.literal("route"),routeId:p.string().describe("Named route ID from the route filter")}).describe("Fires when the current route matches a named route ID."),p0=p.object({type:p.literal("anchor_visible"),anchorId:p.string().describe("CSS selector of the anchor element"),state:p.enum(["visible","present","absent"]).describe('"visible" = in viewport, "present" = in DOM, "absent" = not in DOM')}).describe(`Fires based on a DOM element's visibility state. Example: {"type": "anchor_visible", "anchorId": "#cta-button", "state": "visible"}`),h0=p.object({type:p.literal("event_occurred"),eventName:p.string().describe('Event name (e.g. "ui.click", "$pageview")'),withinMs:p.number().optional().describe("Time window in ms. Omit = any time this session.")}).describe('Fires when a specific event has occurred during this session. Example: {"type": "event_occurred", "eventName": "ui.click", "withinMs": 5000}'),m0=p.object({type:p.literal("state_equals"),key:p.string().describe("Key in the SDK persistent state store (localStorage). Only valid for keys the host app explicitly sets via syntro.state.set()."),value:p.unknown().describe("Expected value to match against")}).describe("Checks the SDK persistent state store (localStorage). ONLY for host-app state set via syntro.state.set() \u2014 NOT for user attributes like region, device, or UTM params (those are handled by segment targeting). Do NOT use this for targeting. If you do not know the valid state keys, do not use this condition type."),g0=p.object({type:p.literal("viewport"),minWidth:p.number().optional().describe("Minimum viewport width in pixels"),maxWidth:p.number().optional().describe("Maximum viewport width in pixels"),minHeight:p.number().optional().describe("Minimum viewport height in pixels"),maxHeight:p.number().optional().describe("Maximum viewport height in pixels")}).describe('Fires based on viewport (screen) size. Use for responsive behavior. Example: {"type": "viewport", "minWidth": 768} \u2014 fires on tablet and larger.'),v0=p.object({type:p.literal("session_metric"),key:IT,operator:p.enum(["gte","lte","eq","gt","lt"]),threshold:p.number().describe("Numeric threshold to compare against")}).describe('Fires when a session metric crosses a threshold. Valid keys: "time_on_page" (seconds), "page_views" (count), "scroll_depth" (0-100). Example: {"type": "session_metric", "key": "time_on_page", "operator": "gte", "threshold": 30}'),y0=p.object({type:p.literal("dismissed"),key:p.string().describe("Dismissal key (usually a tile or action ID)"),inverted:p.boolean().optional().describe("When true, fires if NOT dismissed (default behavior)")}).describe("Checks if an item has been dismissed by the user. Use with inverted: true to show only if not dismissed."),x0=p.object({type:p.literal("cooldown_active"),key:p.string().describe("Cooldown key"),inverted:p.boolean().optional().describe("When true, fires if cooldown is NOT active")}).describe("Checks if a cooldown timer is currently active. Use to prevent showing the same intervention too frequently."),b0=p.object({type:p.literal("frequency_limit"),key:p.string().describe("Frequency counter key"),limit:p.number().describe("Maximum allowed count"),inverted:p.boolean().optional().describe("When true, fires if limit NOT reached")}).describe("Checks if a frequency limit has been reached. Use to cap how many times an action fires per session."),Ic=p.object({equals:p.union([p.string(),p.number(),p.boolean()]).optional(),contains:p.string().optional()}).describe("Match operator for counter filters. Exactly one of equals or contains must be specified."),Ac=p.object({events:p.array(LT).min(1).describe("Event names to count. Use values from the countable events enum."),match:p.record(p.string(),Ic).optional().describe("Property filters. Keys are event prop names or element-chain fields (tag_name, $el_text, attr__*). All entries AND together.")}).describe("Defines what events to count. Registered as an accumulator predicate at config-load time."),S0=p.object({type:p.literal("event_count"),key:p.string().describe("Unique key for this counter (used for accumulator registration)"),operator:p.enum(["gte","lte","eq","gt","lt"]),count:p.number().int().min(0).describe("Target count threshold"),withinMs:p.number().positive().optional().describe("Time window in ms. Omit = count across entire session."),counter:Ac.optional().describe("Inline counter definition. Defines what events to count.")}).describe('Fires when accumulated event count crosses a threshold. Most powerful trigger type. Example: {"type": "event_count", "key": "pricing-clicks", "operator": "gte", "count": 3, "counter": {"events": ["ui.click"], "match": {"attr__data-cta": {"contains": "pricing"}}}}'),Lo=p.discriminatedUnion("type",[d0,f0,p0,h0,m0,g0,v0,y0,x0,b0,S0]),Ec=p.object({conditions:p.array(Lo).describe("Array of conditions \u2014 ALL must match (AND logic) for this rule to fire."),value:p.unknown().describe("Value returned when all conditions match. For triggerWhen: true = fire the action.")}).describe("A single rule. ALL conditions must match (AND logic). Rules in a strategy are evaluated top-to-bottom \u2014 first rule where all conditions match wins and returns its value."),Tc=p.object({type:p.literal("rules"),rules:p.array(Ec).describe("Ordered list of rules. Evaluated top-to-bottom \u2014 first match wins."),default:p.unknown().describe("Fallback value when no rule matches. For triggerWhen: false = do not fire by default.")}).describe("Rule-based strategy. Evaluates rules top-to-bottom. First rule where ALL conditions match returns its value. If no rule matches, returns default. For triggerWhen: set value=true on matching rules, default=false."),Rc=p.object({type:p.literal("score"),field:p.string(),threshold:p.number(),above:p.unknown(),below:p.unknown()}).describe("Score-based strategy. Compares a field value against a threshold."),Mc=p.object({type:p.literal("model"),modelId:p.string(),inputs:p.array(p.string()),outputMapping:p.record(p.string(),p.unknown()),default:p.unknown()}).describe("ML model strategy. Sends inputs to a model and maps outputs."),Oc=p.object({type:p.literal("external"),endpoint:p.string(),method:p.enum(["GET","POST"]).optional(),default:p.unknown(),timeoutMs:p.number().optional()}).describe("External API strategy. Calls an endpoint to determine the value."),Dc=p.discriminatedUnion("type",[Tc,Rc,Mc,Oc]),yh=Dc.nullable().optional();var y4=p.object({events:p.array(p.string()),urlContains:p.string().optional(),props:p.record(p.union([p.string(),p.number(),p.boolean()])).optional()}),x4=p.object({title:p.string().optional(),body:p.string().optional(),icon:p.string().optional()}).nullable().optional();var AT=p.object({include:p.array(p.string()).optional().describe("URL patterns where this tile appears. Supports *, **, :param wildcards. Use sparingly \u2014 mostly to isolate to specific webapp functionality. Omit to appear on all routes."),exclude:p.array(p.string()).optional().describe("URL patterns where this tile should NOT appear. Evaluated before include.")}),xh=p.object({routes:AT,onlyIfPopulated:p.boolean().optional().describe("When true, tile is hidden if none of its props.actions[] have an active triggerWhen. Useful for tiles with all-deferred FAQ questions or nav tips. Default: false.")});function b9(t){return Lo.safeParse(t)}function S9(t){return Dc.safeParse(t)}function _9(t){return xh.safeParse(t)}var C9=[{defName:"matchOp",schema:Ic},{defName:"counterDef",schema:Ac},{defName:"activationConfig",schema:xh},{defName:"routeFilter",schema:AT},{defName:"ruleStrategy",schema:Tc},{defName:"scoreStrategy",schema:Rc},{defName:"modelStrategy",schema:Mc},{defName:"externalStrategy",schema:Oc},{defName:"rule",schema:Ec},{defName:"condition",schema:Lo}];var _0=p.object({tileId:p.string(),itemId:p.string().optional()}).strict(),b4=p.object({on:p.string(),title:p.string(),body:p.string().optional(),icon:p.string().optional(),ttl:p.number().optional(),cooldown:p.number().optional(),deepLink:_0.optional()}).strict(),S4=p.object({id:p.string(),title:p.string().optional(),subtitle:p.string().optional(),icon:p.string().optional(),priority:p.number().optional(),widget:p.string(),props:p.record(p.unknown()).optional(),activation:xh.optional(),notifications:p.array(b4).optional()}).strict(),_4=p.object({position:p.enum(["left","right"]).optional(),layout:p.enum(["overlay","push"]).optional(),background:p.string().optional(),blur:p.string().optional(),border:p.string().optional(),width:p.string().optional(),transitionDuration:p.string().optional(),transitionEasing:p.string().optional(),transitionFade:p.string().optional()}),C4=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),color:p.string().optional(),size:p.string().optional(),shadow:p.string().optional(),borderRadius:p.string().optional(),icon:p.string().optional()}),w4=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),shadow:p.string().optional(),titleColor:p.string().optional(),textColor:p.string().optional(),iconBackground:p.string().optional(),iconShadow:p.string().optional(),headerPadding:p.string().optional(),bodyPadding:p.string().optional(),gap:p.string().optional()}),L4=p.object({background:p.string().optional(),textColor:p.string().optional(),titleColor:p.string().optional(),arrowColor:p.string().optional(),arrowSize:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),scrimOpacity:p.string().optional(),highlightRing:p.string().optional()}),k4=p.object({background:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),successColor:p.string().optional(),warningColor:p.string().optional(),errorColor:p.string().optional(),iconBackground:p.string().optional(),progressGradient:p.string().optional()}),I4=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),itemDivider:p.string().optional(),itemGap:p.string().optional(),itemPadding:p.string().optional(),itemFontSize:p.string().optional(),bodyPadding:p.string().optional(),bodyFontSize:p.string().optional(),categoryPadding:p.string().optional(),categoryGap:p.string().optional(),categoryFontSize:p.string().optional(),searchBackground:p.string().optional(),searchColor:p.string().optional(),chevronColor:p.string().optional()}),A4=p.object({mode:p.enum(["dark","light"]).optional(),fontFamily:p.string().optional(),colorPrimary:p.string().optional(),colorPrimaryHover:p.string().optional(),borderRadius:p.string().optional(),canvas:_4.optional(),launcher:C4.optional(),tile:w4.optional(),overlay:L4.optional(),notification:k4.optional(),content:I4.optional()}).strict(),E4=p.object({enabled:p.boolean().optional(),label:p.string().optional(),position:p.string().optional(),animate:p.boolean().optional(),animationStyle:p.enum(["pulse","bounce","glow"]).optional(),notificationCount:p.number().optional()}).strict(),A9=p.object({schemaVersion:p.string().optional(),fetchedAt:p.string().datetime(),configVersion:p.string().optional(),canvasTitle:p.string().optional(),tiles:p.array(S4),actions:p.array(p.any()),theme:A4.optional(),launcher:E4.optional(),meta:p.object({verificationSteps:p.array(p.union([p.string(),p.object({text:p.string(),check:Lo.optional()})])).optional()}).passthrough().optional()}).strict();var Ct={triggerWhen:yh},Ga=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),ET=p.object({color:p.string().optional(),scrimOpacity:p.number().min(0).max(1).optional(),paddingPx:p.number().optional(),radiusPx:p.number().optional()}).strict(),TT=p.enum(["top-left","top-right","bottom-left","bottom-right"]),RT=p.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),w0=p.object({label:p.string(),actionId:p.string(),primary:p.boolean().optional()}).strict(),MT=p.object({title:p.string().optional(),body:p.string(),ctaButtons:p.array(w0).optional()}).strict(),OT=p.object({title:p.string().optional(),body:p.string()}).strict(),DT=p.enum(["before","after","prepend","append","replace"]),BT=p.enum(["immediate","hover","click"]),PT=p.object({widgetId:p.string(),props:p.record(p.unknown()).optional(),priority:p.number().optional()}).strict(),NT=p.object({id:p.string(),action:p.any(),route:p.string().optional(),onAction:p.record(p.string()).optional()}).passthrough(),FT=p.enum(["auto","smooth","instant"]),C0=p.enum(["start","center","end","nearest"]),HT=p.object({kind:p.literal("content:setText"),anchorId:Ga,text:p.string(),label:p.string().optional()}).extend(Ct).strict(),UT=p.object({kind:p.literal("content:setAttr"),anchorId:Ga,attr:p.string(),value:p.string(),label:p.string().optional()}).extend(Ct).strict(),zT=p.object({kind:p.literal("content:addClass"),anchorId:Ga,className:p.string(),label:p.string().optional()}).extend(Ct).strict(),qT=p.object({kind:p.literal("content:removeClass"),anchorId:Ga,className:p.string(),label:p.string().optional()}).extend(Ct).strict(),VT=p.object({kind:p.literal("content:setStyle"),anchorId:Ga,styles:p.record(p.string()),label:p.string().optional()}).extend(Ct).strict(),$T=p.object({kind:p.literal("content:insertHtml"),anchorId:Ga,html:p.string(),position:DT,deepLink:_0.optional(),label:p.string().optional()}).extend(Ct).strict(),jT=p.object({kind:p.literal("overlays:highlight"),anchorId:Ga,style:ET.optional(),duration:p.number().optional(),label:p.string().optional()}).extend(Ct).strict(),GT=p.object({kind:p.literal("overlays:pulse"),anchorId:Ga,duration:p.number().optional(),label:p.string().optional()}).extend(Ct).strict(),WT=p.object({kind:p.literal("overlays:badge"),anchorId:Ga,content:p.string(),position:TT.optional(),label:p.string().optional()}).extend(Ct).strict(),ZT=p.object({kind:p.literal("overlays:tooltip"),anchorId:Ga,content:MT,trigger:BT.optional(),placement:RT.optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(Ct).strict(),XT=p.object({kind:p.literal("overlays:modal"),content:OT,size:p.enum(["sm","md","lg"]).optional(),blocking:p.boolean().optional(),scrim:p.object({opacity:p.number().min(0).max(1).optional()}).strict().optional(),dismiss:p.object({onEsc:p.boolean().optional(),closeButton:p.boolean().optional(),timeoutMs:p.number().min(0).optional()}).strict().optional(),ctaButtons:p.array(w0).optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(Ct).strict(),KT=p.object({kind:p.literal("navigation:scrollTo"),anchorId:Ga,behavior:FT.optional(),block:C0.optional(),inline:C0.optional(),label:p.string().optional()}).extend(Ct).strict(),YT=p.object({kind:p.literal("navigation:navigate"),url:p.string(),target:p.enum(["_self","_blank"]).optional(),label:p.string().optional()}).extend(Ct).strict(),QT=p.object({kind:p.literal("core:mountWidget"),slot:p.string(),widget:PT,label:p.string().optional()}).extend(Ct).strict(),JT=p.object({kind:p.literal("core:wait"),durationMs:p.number().min(0).optional(),event:p.string().optional(),label:p.string().optional()}).extend(Ct).strict(),eR=p.object({kind:p.literal("core:sequence"),actions:p.array(p.any()),label:p.string().optional()}).extend(Ct).strict(),tR=p.object({kind:p.literal("core:parallel"),actions:p.array(p.any()),waitFor:p.enum(["all","any"]).optional(),label:p.string().optional()}).extend(Ct).strict(),aR=p.object({kind:p.literal("overlays:tour"),tourId:p.string(),steps:p.array(NT).min(1),startStep:p.string().optional(),autoStart:p.boolean().optional(),label:p.string().optional()}).extend(Ct).passthrough(),T4=[{defName:"setText",schema:HT},{defName:"setAttr",schema:UT},{defName:"addClass",schema:zT},{defName:"removeClass",schema:qT},{defName:"setStyle",schema:VT},{defName:"insertHtml",schema:$T},{defName:"highlight",schema:jT},{defName:"pulse",schema:GT},{defName:"badge",schema:WT},{defName:"tooltip",schema:ZT},{defName:"modal",schema:XT},{defName:"scrollTo",schema:KT},{defName:"navigate",schema:YT},{defName:"mountWidget",schema:QT},{defName:"wait",schema:JT},{defName:"sequence",schema:eR},{defName:"parallel",schema:tR},{defName:"tour",schema:aR}];function L0(t){let e=t?.root??(typeof document<"u"?document.body:null),a=t?.defaultTimeoutMs??5e3,r=new Map,n=new Map,o=null,i=!1;function s(b){if(!e)return null;try{return e.matches(b)?e:e.querySelector(b)}catch{return null}}function l(){for(let[b,g]of r){let m=s(b);if(m){for(let y of g)clearTimeout(y.timer),y.resolve(m);r.delete(b)}}for(let[b,g]of n){let m=s(b);if(m){for(let y of g)y.cancelled||y.cb(m);n.delete(b)}}r.size===0&&n.size===0&&c()}function u(){o||i||typeof MutationObserver>"u"||!e||(o=new MutationObserver(()=>{l()}),o.observe(e,{childList:!0,subtree:!0}))}function c(){o&&(o.disconnect(),o=null)}function d(b,g){let m=r.get(b);m&&(m.delete(g),m.size===0&&r.delete(b)),r.size===0&&n.size===0&&c()}function f(b,g){if(i)return Promise.reject(new Error("AnchorResolver destroyed"));let m=s(b);if(m)return Promise.resolve(m);let y=g??a;return new Promise((v,C)=>{let w={resolve:v,reject:C,timer:setTimeout(()=>{d(b,w),C(new Error(`waitFor("${b}") timed out after ${y}ms`))},y)},_=r.get(b);_||(_=new Set,r.set(b,_)),_.add(w),u()})}function h(b,g){if(i)return()=>{};let m=s(b);if(m)return g(m),()=>{};let y={cb:g,cancelled:!1},v=n.get(b);return v||(v=new Set,n.set(b,v)),v.add(y),u(),()=>{y.cancelled=!0;let C=n.get(b);C&&(C.delete(y),C.size===0&&n.delete(b)),r.size===0&&n.size===0&&c()}}function S(){let b=0;for(let g of r.values())b+=g.size;return b}function x(){i=!0,c();let b=new Error("AnchorResolver destroyed");for(let g of r.values())for(let m of g)clearTimeout(m.timer),m.reject(b);r.clear(),n.clear()}return{resolve:s,waitFor:f,onAppear:h,pendingCount:S,destroy:x}}function R4(){let t=Date.now();return{page:{url:typeof window<"u"?window.location.href:"",title:typeof document<"u"?document.title:void 0},session:{sessionId:"",startTs:t,pageHistory:[]},viewport:{width:typeof window<"u"?window.innerWidth:0,height:typeof window<"u"?window.innerHeight:0}}}function k0(t,e){if(!e)return;let a;try{a=new URL(t).pathname}catch{a=t}if(e.exclude){for(let r of e.exclude)if(rR(a,r))return}if(e.include){for(let r of e.include)if(rR(a,r))return r;return}return a}function rR(t,e){let a=t.replace(/\/$/,"")||"/",r=e.replace(/\/$/,"")||"/";if(a===r)return!0;let n=r.replace(/:[^/]+/g,"[^/]+").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(a)}var bh=class{constructor(e){B(this,"context");B(this,"previousContext");B(this,"listeners",new Set);B(this,"telemetry");B(this,"routes");B(this,"navigation");B(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=R4(),this.previousContext={...this.context},e.telemetry?.getSessionId){let a=e.telemetry.getSessionId();a&&(this.context.session.sessionId=a)}e.initialPageHistory&&(this.context.session.pageHistory=e.initialPageHistory),this.context.page.routeId=k0(this.context.page.url,this.routes),this.addPageToHistory(this.context.page.url),typeof window<"u"&&this.setupBrowserListeners()}get(){return{...this.context}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setRoutes(e){this.routes=e;let a=k0(this.context.page.url,this.routes);a!==this.context.page.routeId&&this.updateContext({page:{...this.context.page,routeId:a}})}setAnchors(e){this.updateContext({anchors:e})}setSessionId(e){e!==this.context.session.sessionId&&this.updateContext({session:{...this.context.session,sessionId:e}})}destroy(){for(let e of this.cleanupFns)e();this.cleanupFns=[],this.listeners.clear()}setupBrowserListeners(){let e,a=()=>{clearTimeout(e),e=setTimeout(()=>{this.updateViewport()},100)};window.addEventListener("resize",a),this.cleanupFns.push(()=>window.removeEventListener("resize",a));let r=this.navigation.subscribe(()=>this.updatePage());this.cleanupFns.push(r)}updateViewport(){let e={width:window.innerWidth,height:window.innerHeight};(e.width!==this.context.viewport.width||e.height!==this.context.viewport.height)&&this.updateContext({viewport:e})}updatePage(){let e=window.location.href,{title:a}=document,r=k0(e,this.routes),n={url:e,title:a,routeId:r};(n.url!==this.context.page.url||n.title!==this.context.page.title||n.routeId!==this.context.page.routeId)&&(n.url!==this.context.page.url&&this.addPageToHistory(n.url),this.updateContext({page:n}))}addPageToHistory(e){let a={url:e,ts:Date.now()},r=[...this.context.session.pageHistory||[],a];r.length>50&&r.shift(),this.context.session.pageHistory=r}updateContext(e){this.previousContext={...this.context},this.context={...this.context,...e},this.notifyListeners()}notifyListeners(){for(let e of this.listeners)try{e(this.context,this.previousContext)}catch(a){console.error("[ContextManager] Listener error:",a)}}};function I0(t){return new bh(t)}var M4=p.object({url:p.string(),routeId:p.string().optional(),title:p.string().optional(),locale:p.string().optional()}),O4=p.object({url:p.string(),ts:p.number()}),D4=p.object({sessionId:p.string(),startTs:p.number(),pageHistory:p.array(O4).optional()}),B4=p.object({width:p.number(),height:p.number()}),P4=p.object({x:p.number(),y:p.number(),w:p.number(),h:p.number()}),N4=p.object({anchorId:p.string(),present:p.boolean(),visible:p.boolean().optional(),boundingBox:P4.optional()}),F4=p.record(p.string(),p.union([p.number(),p.string(),p.boolean(),p.undefined()])),H4=p.object({page:M4,session:D4,viewport:B4,anchors:p.array(N4).optional(),augmented:F4.optional()});function j9(t){return H4.safeParse(t)}function nR(t,e){let{context:a,state:r,events:n}=e;switch(t.type){case"page_url":{let{url:o}=t,i=a.page.url.split("?")[0].split("#")[0],s=o.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*");return new RegExp(`^${s}$`).test(i)}case"route":return a.page.routeId===t.routeId;case"anchor_visible":{let o=a.anchors?.find(i=>i.anchorId===t.anchorId);switch(t.state){case"visible":return o?.visible===!0;case"present":return o?.present===!0;case"absent":return!o?.present;default:return!1}}case"event_occurred":{if(!n)return!1;let o=t.withinMs??6e4;return n.hasRecentEvent(t.eventName,o)}case"state_equals":return r?.getValue?r.getValue(t.key)===t.value:!1;case"viewport":{let{width:o,height:i}=a.viewport;return!(t.minWidth!==void 0&&o<t.minWidth||t.maxWidth!==void 0&&o>t.maxWidth||t.minHeight!==void 0&&i<t.minHeight||t.maxHeight!==void 0&&i>t.maxHeight)}case"session_metric":{if(!r)return!1;let o=r.getSessionMetric(t.key),{operator:i,threshold:s}=t;switch(i){case"gte":return o>=s;case"lte":return o<=s;case"eq":return o===s;case"gt":return o>s;case"lt":return o<s;default:return!1}}case"dismissed":{if(!r)return t.inverted??!1;let o=r.isDismissed(t.key);return t.inverted?!o:o}case"cooldown_active":{if(!r)return t.inverted??!1;let o=r.isCooldownActive(t.key);return t.inverted?!o:o}case"frequency_limit":{if(!r)return t.inverted??!1;let i=r.getFrequencyCount(t.key)>=t.limit;return t.inverted?!i:i}case"event_count":{if(!e.accumulator)return!1;let o=t,i=e.accumulator.getCount(o.key,o.withinMs);switch(o.operator){case"gte":return i>=o.count;case"lte":return i<=o.count;case"eq":return i===o.count;case"gt":return i>o.count;case"lt":return i<o.count;default:return!1}}default:return console.warn("[RuleStrategy] Unknown condition type:",t.type),!1}}function oR(t,e){let a=[];for(let r of t.conditions){let n=nR(r,e);if(a.push({condition:r,result:n}),!n)return{matched:!1,conditionResults:a}}return{matched:!0,conditionResults:a}}function Sh(t,e){for(let a=0;a<t.rules.length;a++){let r=t.rules[a],{matched:n,conditionResults:o}=oR(r,e);if(n)return{value:r.value,isFallback:!1,matchInfo:{strategyType:"rules",matchedRuleIndex:a,evaluatedConditions:o}}}return{value:t.default,isFallback:!0,matchInfo:{strategyType:"rules"}}}function _h(t,e){let{context:a}=e,r=a.augmented?.[t.field];return r===void 0||typeof r!="number"?{value:t.below,isFallback:!0,matchInfo:{strategyType:"score"}}:{value:r>=t.threshold?t.above:t.below,isFallback:!1,matchInfo:{strategyType:"score"}}}function iR(t,e){let{state:a,events:r,sessionMetrics:n,accumulator:o}=e;return{context:t,state:a?{isDismissed:i=>a.dismissals.isDismissed(i),isCooldownActive:i=>a.cooldowns.isActive(i),getFrequencyCount:i=>a.frequency.count(i),getSessionMetric:i=>n?.get(i)??0,getValue:i=>a.session.get(i)??a.user.get(i)}:void 0,events:r?{hasRecentEvent:(i,s)=>r.hasRecentEvent(i,s)}:void 0,accumulator:o?{getCount:(i,s)=>o.getCount(i,s)}:void 0}}async function sR(t,e,a={}){let r=iR(e,a);switch(t.type){case"rules":return Sh(t,r);case"score":return _h(t,r);case"model":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"model"}};case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"external"}};default:return console.warn("[DecisionEngine] Unknown strategy type:",t.type),{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function lR(t,e,a={}){let r=iR(e,a);switch(t.type){case"rules":return Sh(t,r);case"score":return _h(t,r);case"model":case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:t.type}};default:return{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function A0(t){return{evaluate:(e,a)=>sR(e,a,t),evaluateSync:(e,a)=>lR(e,a,t)}}function E0(t){let{eventBus:e,stateStore:a}=t,r=new Map,n=new Set,o=null,i=a.ns("accumulator");function s(u){let c=!1;for(let d of r.values()){if(!d.predicate(u))continue;let f=i.get(d.stateKey)||{count:0};f.count++,d.needsTimestamps&&(f.timestamps||(f.timestamps=[]),f.timestamps.push(u.ts),f.timestamps.length>200&&(f.timestamps=f.timestamps.slice(-200))),i.set(d.stateKey,f),c=!0}if(c)for(let d of n)try{d()}catch(f){console.error("[EventAccumulator] Subscriber error:",f)}}function l(){o||r.size===0||(o=e.subscribe(s))}return{register(u,c,d=!1){let f=`ev:${u}`,h=r.get(f);if(h){d&&!h.needsTimestamps&&(h.needsTimestamps=!0);return}r.set(f,{stateKey:f,needsTimestamps:d,predicate:c}),l()},getCount(u,c){let d=`ev:${u}`,f=i.get(d);if(!f)return 0;if(c===void 0||!f.timestamps)return f.count;let h=Date.now()-c;return f.timestamps.filter(S=>S>=h).length},subscribe(u){return n.add(u),()=>{n.delete(u)}},destroy(){o&&(o(),o=null),r.clear(),n.clear()}}}var uR="app:",U4="syntro:",z4=/^[a-z][a-z0-9_]*$/;function T0(t){if(!t)return{valid:!1,reason:"Event name cannot be empty"};if(t.startsWith(U4))return{valid:!1,reason:'"syntro:" prefix is reserved for internal SDK events'};if(!t.startsWith(uR))return{valid:!1,reason:`Custom events must start with "app:" prefix. Got: "${t}"`};let e=t.slice(uR.length).split(":");if(e.length<2)return{valid:!1,reason:`Event name must have at least 2 segments after "app:" (app:{category}:{action}). Got: "${t}"`};for(let a of e)if(!z4.test(a))return{valid:!1,reason:`Segment "${a}" must be lowercase alphanumeric + underscores. Got: "${t}"`};return{valid:!0}}function q4(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t===null}function cR(t,e,a=0){if(a>=e)return!1;for(let r of Object.values(t))if(r!==null&&typeof r=="object"&&!Array.isArray(r)&&!cR(r,e,a+1))return!1;return!0}function R0(t){if(t===void 0)return{valid:!0};if(t===null||typeof t!="object"||Array.isArray(t))return{valid:!1,reason:"Props must be a plain object"};if(!cR(t,2))return{valid:!1,reason:"Props nesting depth exceeds 2 levels"};let e=[];for(let[a,r]of Object.entries(t))r!==null&&typeof r=="object"||q4(r)||e.push(a);return e.length>0?{valid:!0,stripped:e}:{valid:!0}}function Ch(t,e){return e?!(e.names&&e.names.length>0&&!e.names.includes(t.name)||e.patterns&&e.patterns.length>0&&!e.patterns.some(r=>{try{return new RegExp(r).test(t.name)}catch{return!1}})||e.sources&&e.sources.length>0&&!e.sources.includes(t.source)):!0}var wh=class{constructor(e={}){B(this,"subscriptions",new Set);B(this,"history",[]);B(this,"maxHistorySize");B(this,"debug");B(this,"emitHistory");B(this,"posthogCapture");B(this,"testMode");this.maxHistorySize=e.maxHistorySize??100,this.debug=e.debug??!1,this.emitHistory=e.history??null,this.posthogCapture=e.posthogCapture??null,this.testMode=e.testMode??!1}subscribe(e,a){let r,n;typeof e=="function"?(r=void 0,n=e):(r=e,n=a);let o={filter:r,callback:n};return this.subscriptions.add(o),()=>{this.subscriptions.delete(o)}}publish(e,a,r="canvas"){let n={ts:Date.now(),name:e,source:r,props:a,schemaVersion:rt};this.publishEvent(n)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let a of this.subscriptions)if(Ch(e,a.filter))try{a.callback(e)}catch(r){console.error("[EventBus] Subscriber error:",r)}}emit(e,a){let r=T0(e);if(!r.valid)return console.warn(`[EventBus] emit() rejected: ${r.reason}`),this.debug?{delivered:!1,matchedRules:[],posthogCaptured:!1,listenersNotified:0}:void 0;let n=R0(a);if(!n.valid)return console.warn(`[EventBus] emit() rejected props: ${n.reason}`),this.debug?{delivered:!1,matchedRules:[],posthogCaptured:!1,listenersNotified:0}:void 0;let o={ts:Date.now(),name:e,source:"custom",props:a,schemaVersion:rt};this.history.push(o),this.history.length>this.maxHistorySize&&this.history.shift();let i=0;for(let l of this.subscriptions)if(Ch(o,l.filter))try{l.callback(o),i++}catch(u){console.error("[EventBus] Subscriber error:",u),i++}let s=!1;if(this.posthogCapture&&!this.testMode)try{this.posthogCapture(e,a),s=!0}catch(l){console.error("[EventBus] PostHog capture error:",l)}if(this.emitHistory&&this.emitHistory.record({name:e,props:a,source:"custom",timestamp:o.ts,matchedRules:[]}),this.debug)return console.debug("[EventBus] emit()",{name:e,props:a,listenersNotified:i,posthogCaptured:s}),{delivered:!0,matchedRules:[],posthogCaptured:s,listenersNotified:i}}setPosthogCapture(e){this.posthogCapture=e}getRecent(e,a){let r=this.history;return e&&(r=r.filter(n=>Ch(n,e))),a&&a>0&&(r=r.slice(-a)),r}hasRecentEvent(e,a,r){let n=Date.now()-a;return this.history.some(o=>o.name===e&&o.ts>=n&&(r===void 0||o.source===r))}countRecentEvents(e,a){let r=this.history.filter(n=>Ch(n,e));if(a!==void 0){let n=Date.now()-a;r=r.filter(o=>o.ts>=n)}return r.length}clearHistory(){this.history=[]}getSubscriberCount(){return this.subscriptions.size}};function Bc(t={}){return new wh(t)}var Pc=class{constructor(e=100){B(this,"entries",[]);B(this,"maxSize");this.maxSize=e}record(e){this.entries.push(e),this.maxSize>0&&this.entries.length>this.maxSize&&this.entries.shift()}getAll(){return[...this.entries]}clear(){this.entries=[]}};var dR=p.enum(["posthog","canvas","derived"]),V4=p.object({ts:p.number(),name:p.string(),source:dR,props:p.record(p.string(),p.unknown()).optional(),schemaVersion:p.string()}),$4=p.object({names:p.array(p.string()).optional(),patterns:p.array(p.string()).optional(),sources:p.array(dR).optional()});function xj(t){return V4.safeParse(t)}function bj(t){return $4.safeParse(t)}var Nc=class{constructor(){B(this,"listeners",new Set);B(this,"capturedPushState");B(this,"capturedReplaceState");B(this,"wasNative");B(this,"destroyed",!1);B(this,"onPopState",()=>{this.notify(window.location.href,"popstate")});this.wasNative=this.isNativeFunction(history.pushState),this.capturedPushState=history.pushState,this.capturedReplaceState=history.replaceState,history.pushState=(...e)=>{this.capturedPushState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"pushState"))},history.replaceState=(...e)=>{this.capturedReplaceState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"replaceState"))},window.addEventListener("popstate",this.onPopState)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}diagnose(){return{isNative:this.wasNative,subscriberCount:this.listeners.size}}destroy(){this.destroyed||(this.destroyed=!0,history.pushState=this.capturedPushState,history.replaceState=this.capturedReplaceState,window.removeEventListener("popstate",this.onPopState),this.listeners.clear())}notify(e,a){if(!this.destroyed)for(let r of this.listeners)try{r(e,a)}catch{}}isNativeFunction(e){try{return Function.prototype.toString.call(e).includes("[native code]")}catch{return!1}}};var M0="cooldown:";function fR(t){return{set(e,a){let r=M0+e,n=Date.now()+a;t.set(r,n)},isActive(e){return this.remaining(e)>0},remaining(e){let a=M0+e,r=t.get(a);if(r===void 0)return 0;let n=r-Date.now();return n<=0?(t.remove(a),0):n},clear(e){let a=M0+e;t.remove(a)}}}var Fc="dismissed:";function pR(t,e){return{mark(a,r=!1){let n=Fc+a;(r?e:t).set(n,!0)},isDismissed(a){let r=Fc+a;return t.has(r)||e.has(r)},clear(a){let r=Fc+a;t.remove(r),e.remove(r)},clearAll(){for(let a of t.keys())a.startsWith(Fc)&&t.remove(a);for(let a of e.keys())a.startsWith(Fc)&&e.remove(a)}}}var O0="freq:";function hR(t){function e(a){let r=O0+a,n=t.get(r);if(n){if(n.resetAt&&Date.now()>=n.resetAt){t.remove(r);return}return n}}return{increment(a,r){let n=O0+a,o=e(a),i=(o?.count??0)+1,s={count:i,resetAt:o?.resetAt??(r?Date.now()+r:void 0)};return t.set(n,s),i},count(a){return e(a)?.count??0},reset(a){let r=O0+a;t.remove(r)},hasReachedLimit(a,r){return this.count(a)>=r}}}var j4="syntro";function D0(t,e){let a=`${e}:`;return{get(r){if(t)try{let n=t.getItem(a+r);if(!n)return;let o=JSON.parse(n);if(o.expiresAt&&Date.now()>=o.expiresAt){t.removeItem(a+r);return}return o.value}catch{return}},set(r,n,o){if(t)try{let i={value:n,expiresAt:o?Date.now()+o:void 0};t.setItem(a+r,JSON.stringify(i))}catch(i){console.warn("[StateStore] Failed to save:",i)}},remove(r){t&&t.removeItem(a+r)},has(r){return t?this.get(r)!==void 0:!1},keys(){if(!t)return[];let r=[];for(let n=0;n<t.length;n++){let o=t.key(n);o?.startsWith(a)&&r.push(o.slice(a.length))}return r},clear(){if(!t)return;let r=this.keys();for(let n of r)t.removeItem(a+n)}}}function Hc(t){let e=new Map,a=`${t}:`;return{get(r){let n=e.get(a+r);if(n){if(n.expiresAt&&Date.now()>=n.expiresAt){e.delete(a+r);return}return n.value}},set(r,n,o){e.set(a+r,{value:n,expiresAt:o?Date.now()+o:void 0})},remove(r){e.delete(a+r)},has(r){return this.get(r)!==void 0},keys(){let r=[];for(let n of e.keys())n.startsWith(a)&&r.push(n.slice(a.length));return r},clear(){for(let r of e.keys())r.startsWith(a)&&e.delete(r)}}}var Lh=class{constructor(e={}){B(this,"session");B(this,"user");B(this,"dismissals");B(this,"cooldowns");B(this,"frequency");B(this,"namespace");B(this,"namespacedStorages",new Map);this.namespace=e.namespace??j4;let a=r=>typeof r=="object"&&r!==null&&typeof r.setItem=="function";typeof window<"u"?(this.session=a(window.sessionStorage)?D0(window.sessionStorage,this.namespace):Hc(this.namespace),this.user=a(window.localStorage)?D0(window.localStorage,this.namespace):Hc(this.namespace)):(this.session=Hc(this.namespace),this.user=Hc(this.namespace)),this.dismissals=pR(this.session,this.user),this.cooldowns=fR(this.user),this.frequency=hR(this.session)}ns(e){let a=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(a)){let r=typeof window<"u"&&typeof sessionStorage<"u"?D0(sessionStorage,a):Hc(a);this.namespacedStorages.set(a,r)}return this.namespacedStorages.get(a)}};function B0(t={}){return new Lh(t)}function Uc(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function kh(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var mR={drawer_right:{position:"fixed",top:"0",right:"0",bottom:"0",width:"360px",maxWidth:"90vw"},drawer_left:{position:"fixed",top:"0",left:"0",bottom:"0",width:"360px",maxWidth:"90vw"},drawer_bottom:{position:"fixed",left:"0",right:"0",bottom:"0",maxHeight:"50vh"},overlay_center:{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)",maxWidth:"90vw",maxHeight:"90vh"},overlay_corner_br:{position:"fixed",bottom:"16px",right:"16px",maxWidth:"400px",maxHeight:"80vh"},overlay_corner_bl:{position:"fixed",bottom:"16px",left:"16px",maxWidth:"400px",maxHeight:"80vh"},toast_top:{position:"fixed",top:"16px",left:"50%",transform:"translateX(-50%)",maxWidth:"90vw"},toast_bottom:{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",maxWidth:"90vw"}},zc={fade:[{opacity:0},{opacity:1}],slide:[{opacity:0,transform:"translateY(10px)"},{opacity:1,transform:"translateY(0)"}],scale:[{opacity:0,transform:"scale(0.95)"},{opacity:1,transform:"scale(1)"}],none:[]},gR={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function P0(t,e,a){let r=mR[e];Object.assign(t.style,r),a&&(a.maxWidth&&(t.style.maxWidth=a.maxWidth),a.maxHeight&&(t.style.maxHeight=a.maxHeight),a.minWidth&&(t.style.minWidth=a.minWidth),a.minHeight&&(t.style.minHeight=a.minHeight))}function N0(t,e,a){let r=a.placement==="auto"?"bottom":a.placement,n=[Df(a.offset?{mainAxis:a.offset.y,crossAxis:a.offset.x}:8)];return a.flip!==!1&&n.push(Pf()),a.shift!==!1&&n.push(Bf({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",Of(e,t,async()=>{let{x:i,y:s,strategy:l}=await Nf(e,t,{placement:r,middleware:n});Object.assign(t.style,{position:l,left:`${i}px`,top:`${s}px`})})}function F0(t,e,a="append"){return t.style.position="relative",t.style.display="inline-block",a==="prepend"?e.insertBefore(t,e.firstChild):e.appendChild(t),()=>{t.remove()}}function H0(t,e){return e==="none"||zc[e].length===0?null:t.animate(zc[e],gR)}function U0(t,e){if(e==="none"||zc[e].length===0)return Promise.resolve();let a=[...zc[e]].reverse(),r=t.animate(a,gR);return new Promise(n=>{r.onfinish=()=>n(),r.oncancel=()=>n()})}function z0(t,e){let a=document.createElement("div");return a.setAttribute("data-syntro-surface",t),a.setAttribute("data-syntro-mount-id",e),a.className="syntro-surface",Object.assign(a.style,{pointerEvents:"auto",boxSizing:"border-box",overflow:"auto"}),a}function q0(t){switch(Uc(t)){case"static":return t.startsWith("drawer")?2147483640:t.startsWith("overlay")?2147483642:t.startsWith("toast")?2147483644:2147483640;case"inline":return 1;case"adjacent":return 2147483638;default:return 2147483640}}function vR(t){if(typeof window.Sanitizer=="function")try{let l=new window.Sanitizer({}).sanitizeToFragment(t),u=document.createElement("div");return u.append(l),u.innerHTML}catch{}let a=document.createElement("template");a.innerHTML=t;let r=a.content,n=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=new Set(["b","strong","i","em","u","span","div","p","br","ul","ol","li","code","pre","small","sup","sub","a","button"]),i=[];for(;n.nextNode();){let s=n.currentNode,l=s.tagName.toLowerCase();if(!o.has(l)){i.push(s);continue}for(let u of Array.from(s.attributes)){let c=u.name.toLowerCase(),d=u.value.trim().toLowerCase(),f=c.startsWith("on"),h=(c==="href"||c==="src")&&d.startsWith("javascript:");(f||h)&&s.removeAttribute(u.name)}}for(let s of i){for(;s.firstChild;)s.parentNode?.insertBefore(s.firstChild,s);s.remove()}return a.innerHTML=(r.firstChild,a.innerHTML)}var G4=0;function V0(t){let{overlayRoot:e,eventBus:a,anchorResolver:r,defaultAnimation:n="fade",widgetRegistry:o}=t,i=new Map,s=new Map,l=new Map;function u(){return`mount-${++G4}`}function c(v,C){a&&a.publish(v,C)}function d(v){let C=l.get(v);if(C){let w=b(v);for(let _ of C)try{_(w)}catch(L){console.error("[Surfaces] State callback error:",L)}}}let f=new Map;function h(v,C,w){switch(C.type){case"html":v.innerHTML=vR(C.content);return;case"widget":{if(o?.has(C.widgetId)){let _=o.mount(C.widgetId,v,C.config);return w&&f.set(w,_),()=>{_.unmount(),w&&f.delete(w)}}console.warn(`[Surfaces] Widget not found: ${C.widgetId}`),v.innerHTML=`<div data-widget-id="${C.widgetId}" data-widget-missing="true">Widget: ${C.widgetId}</div>`;return}case"custom":return C.mount(v);case"react":v.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function S(v,C,w){let _=u(),L=Uc(v),A=w?.priority??0,I=w?.animation??n,O=w?.exclusive??!0,H=i.get(v);if(H&&O){if(H.options.priority>A)throw new Error(`Slot ${v} is occupied by higher priority content (${H.options.priority} > ${A})`);x(H)}let E=z0(v,_);E.style.zIndex=String(q0(v));let R;if(L==="static")P0(E,v,w?.constraints),e.appendChild(E);else if(L==="inline"){let U=kh(v);if(!U)throw new Error(`Invalid inline slot: ${v}`);if(!r)throw new Error("Anchor resolver required for inline slots");let W=r({selector:U,route:"**"});if(!W)throw new Error(`Anchor not found for inline slot: ${U}`);R=F0(E,W)}else if(L==="adjacent"){let U=kh(v);if(!U)throw new Error(`Invalid adjacent slot: ${v}`);if(!r)throw new Error("Anchor resolver required for adjacent slots");let W=r({selector:U,route:"**"});if(!W)throw new Error(`Anchor not found for adjacent slot: ${U}`);e.appendChild(E),R=N0(E,W,w?.position??{placement:"bottom"})}let M=h(E,C,_);H0(E,I);let F={id:_,slot:v,content:C,options:{priority:A,exclusive:O,animation:I,position:w?.position??{placement:"auto"},constraints:w?.constraints??{},adaptiveId:w?.adaptiveId,autoUnmountOnRouteChange:w?.autoUnmountOnRouteChange??!0},container:E,cleanup:()=>{R?.(),M?.()},mountedAt:Date.now()};return i.set(v,F),s.set(v,(s.get(v)??0)+1),c("surface.mounted",{slot:v,id:_,adaptiveId:w?.adaptiveId}),d(v),{id:_,update(U){let W=i.get(v);if(!W||W.id!==_)throw new Error("Mount no longer active");let ce=f.get(_);if(ce){if(U.type==="widget"){ce.update(U.config),W.content=U;return}ce.unmount(),f.delete(_)}W.container.innerHTML="";let Xt=h(W.container,U,_);if(W.content=U,Xt){let it=W.cleanup;W.cleanup=()=>{it?.(),Xt()}}},setOptions(U){let W=i.get(v);if(!W||W.id!==_)throw new Error("Mount no longer active");U.priority!==void 0&&(W.options.priority=U.priority),U.animation!==void 0&&(W.options.animation=U.animation),U.constraints&&L==="static"&&(U.constraints.maxWidth&&(W.container.style.maxWidth=U.constraints.maxWidth),U.constraints.maxHeight&&(W.container.style.maxHeight=U.constraints.maxHeight),U.constraints.minWidth&&(W.container.style.minWidth=U.constraints.minWidth),U.constraints.minHeight&&(W.container.style.minHeight=U.constraints.minHeight)),d(v)},async unmount(){let U=i.get(v);!U||U.id!==_||await x(U)},isMounted(){return i.get(v)?.id===_},getContainer(){let U=i.get(v);return U?.id===_?U.container:null}}}async function x(v){v.container.isConnected&&await U0(v.container,v.options.animation);try{v.cleanup?.()}catch(C){console.warn("[Surfaces] Cleanup error during unmount, ignoring:",C)}try{v.container.remove()}catch{}i.delete(v.slot),c("surface.unmounted",{slot:v.slot,id:v.id}),d(v.slot)}function b(v){let C=i.get(v);return{slot:v,occupied:!!C,currentPriority:C?.options.priority,currentAdaptiveId:C?.options.adaptiveId,mountCount:s.get(v)??0,currentMountId:C?.id}}function g(v,C){let w=l.get(v);return w||(w=new Set,l.set(v,w)),w.add(C),()=>{w?.delete(C),w?.size===0&&l.delete(v)}}function m(v,C){let w=i.get(v);return w?C!==void 0?C>=w.options.priority:!1:!0}function y(){for(let v of i.values())try{v.cleanup?.(),v.container.remove()}catch(C){console.error("[Surfaces] Error during cleanup:",C)}i.clear(),l.clear()}return{mount:S,getState:b,onStateChange:g,canMount:m,destroy:y}}var Ih=class{constructor(){B(this,"widgets",new Map);B(this,"mountedWidgets",new Map);B(this,"mountIdCounter",0);B(this,"runtimeRef");B(this,"listeners",new Set)}bindRuntime(e){this.runtimeRef=e}register(e,a,r="custom",n){if(this.widgets.has(e)){if(this.widgets.get(e).source==="built-in")throw new Error(`Cannot override built-in widget: ${e}`);console.warn(`[WidgetRegistry] Overriding widget: ${e}`)}this.widgets.set(e,{id:e,widget:a,source:r,metadata:n}),this.notify({type:"registered",widgetId:e})}unregister(e){let a=this.widgets.get(e);return a?a.source==="built-in"?(console.warn(`[WidgetRegistry] Cannot unregister built-in widget: ${e}`),!1):(this.widgets.delete(e),this.notify({type:"unregistered",widgetId:e}),!0):!1}unregisterBySource(e){for(let[a,r]of this.widgets.entries())r.source===e&&this.widgets.delete(a)}get(e){return this.widgets.get(e)?.widget}getRegistration(e){return this.widgets.get(e)}has(e){return this.widgets.has(e)}mount(e,a,r){let n=this.widgets.get(e);if(!n)throw new Error(`Widget not found: ${e}`);let o=`widget-mount-${++this.mountIdCounter}`;a.setAttribute("data-widget-mount-id",o),a.setAttribute("data-widget-id",e);let i={...r,runtime:this.runtimeRef},s=n.widget.mount(a,i);return this.mountedWidgets.set(o,{cleanup:s??void 0,container:a}),{widgetId:e,container:a,unmount:()=>{let u=this.mountedWidgets.get(o);u&&(a.isConnected&&u.cleanup?.(),this.mountedWidgets.delete(o),a.removeAttribute("data-widget-mount-id"),a.removeAttribute("data-widget-id"),a.innerHTML="")},update:u=>{if(n.widget.update)n.widget.update(a,u);else{let c=this.mountedWidgets.get(o);if(c){c.cleanup?.(),a.innerHTML="";let d={...u,runtime:this.runtimeRef},f=n.widget.mount(a,d);c.cleanup=f??void 0}}}}}list(){return Array.from(this.widgets.keys())}listRegistrations(){return Array.from(this.widgets.values())}getBySource(e){return Array.from(this.widgets.values()).filter(a=>a.source===e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(let a of this.listeners)try{a(e)}catch(r){console.error("[WidgetRegistry] Listener error:",r)}}destroy(){for(let[e,a]of this.mountedWidgets.entries())a.cleanup?.(),a.container.innerHTML="";this.mountedWidgets.clear()}},$0=new Ih;var xR="2.0.0";function W4(t,e){if(!e)return!0;let a;try{a=new URL(t).pathname}catch{a=t}let r=a.replace(/\/$/,"")||"/";if(e.exclude){for(let n of e.exclude)if(j0(r,n))return!1}if(e.include&&e.include.length>0){for(let n of e.include)if(j0(r,n))return!0;return!1}return!0}function j0(t,e){let a=e.replace(/\/$/,"")||"/";if(t===a)return!0;let r=a.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*").replace(/:[^/]+/g,"[^/]+");return new RegExp(`^${r}$`).test(t)}function yR(t){let a=(typeof window<"u"?window.location.pathname:"/").replace(/\/$/,"")||"/";return(Array.isArray(t.route)?t.route:[t.route]).some(n=>{let o=n;if(/^https?:\/\//.test(o))try{o=new URL(o).pathname}catch{}return j0(a,o)})}function G0(t={}){let{telemetry:e,sessionMetrics:a,routes:r,mode:n="production",namespace:o}=t,i=t.widgets??$0,s=t.executors??xn,l=t.apps??hu,u=new Nc,c=I0({telemetry:e,routes:r,navigation:u}),d=t.events??Bc(),f=B0({namespace:o}),h=E0({eventBus:d,stateStore:f}),S=A0({state:f,events:d,sessionMetrics:a,accumulator:h}),x=W1(),b=L0(),g=_=>yR(_)?b.resolve(_.selector):null,m=async(_,L)=>{if(!yR(_))return null;try{return await b.waitFor(_.selector,L)}catch{return null}},y=V0({overlayRoot:x,eventBus:d,anchorResolver:g,widgetRegistry:i}),v=c0({overlayRoot:x,eventBus:d,surfaces:y,anchorResolver:g,waitForAnchor:m,executorRegistry:s,subscribeNavigation:_=>u.subscribe(_),runtime:{evaluateSync:_=>S.evaluateSync(_,c.get()),context:c,accumulator:h}}),C;if(a){a.increment("page_views");let _=typeof window<"u"?window.location.pathname:"/";C=u.subscribe((L,A)=>{if(A!=="replaceState")try{let I=new URL(L).pathname;I!==_&&(_=I,a.increment("page_views"))}catch{}})}let w={telemetry:e,context:c,events:d,state:f,sessionMetrics:a,actions:v,surfaces:y,widgets:i,executors:s,apps:l,accumulator:h,anchorResolver:b,navigation:u,version:xR,mode:n,async evaluate(_){return S.evaluate(_,c.get())},evaluateSync(_){return S.evaluateSync(_,c.get())},async filterTiles(_){let L=c.get().page.url,A=[];for(let I of _){let O=I.activation;if(!O){A.push(I);continue}if(W4(L,O.routes)){if(O.onlyIfPopulated){let H=I.props?.actions??[];if(H.length>0&&!H.some(R=>R.triggerWhen?S.evaluateSync(R.triggerWhen,c.get()).value:!0))continue}A.push(I)}}return A},setRoutes(_){c.setRoutes(_)},destroy(){l.unbind().catch(_=>{console.error("[Runtime] Error unbinding apps registry:",_)}),C?.(),b.destroy(),h.destroy(),u.destroy(),c.destroy(),v.destroy(),y.destroy()}};return l.bind(w),i.bindRuntime(w),w}var Z4=p.object({value:p.unknown(),expiresAt:p.number().optional()}),X4=p.object({count:p.number(),resetAt:p.number().optional()});function LG(t){return Z4.safeParse(t)}function kG(t){return X4.safeParse(t)}var W0="syn_";function qc(t){if(!t.startsWith(W0))throw new Error("Invalid Syntro token: must start with 'syn_'");let a=t.slice(W0.length).replace(/-/g,"+").replace(/_/g,"/"),r=atob(a),n=JSON.parse(r);if(n.v!==1)throw new Error(`Unsupported token version: ${n.v}`);return n}function Z0(t){let e=JSON.stringify(t),a=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return W0+a}function Wa(t){if(typeof process<"u"&&process.env)return process.env[t];try{let e=(0,eval)("import.meta");if(e?.env)return e.env[t]}catch{}}var SR="syntro_segment_attributes";function _R(){if(typeof window>"u")return{};try{let t=localStorage.getItem(SR);if(t){let e=JSON.parse(t);return K("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){na("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function CR(t){if(!(typeof window>"u"))try{localStorage.setItem(SR,JSON.stringify(t)),K("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){na("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function wR(t){if(!t)return{};let e={};for(let[a,r]of Object.entries(t))a.startsWith("in_segment_")&&(e[a]=r===!0);return e}function X0(){if(typeof window>"u")return{};let t={};try{let e=new URLSearchParams(window.location.search);for(let a of["utm_source","utm_medium","utm_campaign","utm_content","utm_term"]){let r=e.get(a);r&&(t[a]=r)}}catch{}try{navigator.language&&(t.browser_language=navigator.language),navigator.languages?.length&&(t.browser_languages=[...navigator.languages])}catch{}try{let e=window.innerWidth;t.device_type=e<768?"mobile":e<1024?"tablet":"desktop"}catch{}try{if(document.referrer){t.referrer=document.referrer;try{t.referrer_hostname=new URL(document.referrer).hostname}catch{}}}catch{}try{let e=navigator.userAgent;e.includes("Edg/")?t.browser="Edge":e.includes("OPR/")||e.includes("Opera")?t.browser="Opera":e.includes("Chrome/")&&!e.includes("Chromium")?t.browser="Chrome":e.includes("Safari/")&&!e.includes("Chrome")?t.browser="Safari":e.includes("Firefox/")&&(t.browser="Firefox"),e.includes("Windows")?t.os="Windows":e.includes("iPhone")||e.includes("iPad")?t.os="iOS":e.includes("Mac OS X")||e.includes("Macintosh")?t.os="macOS":e.includes("Android")?t.os="Android":e.includes("Linux")&&(t.os="Linux")}catch{}try{t.page_url=window.location.href,t.page_path=window.location.pathname,t.page_host=window.location.hostname,window.location.search&&(t.page_query=window.location.search)}catch{}return t}var bR="syntro_geo",LR="https://geo.syntrologie.com";async function K0(t){if(typeof window>"u")return{};try{let e=localStorage.getItem(bR);if(e){let a=JSON.parse(e);return K("Syntro Bootstrap","Geo: using cached data:",a),a}}catch{}try{let e=await fetch(t,{signal:AbortSignal.timeout(2e3)});if(e.ok){let a=await e.json(),r={};for(let[n,o]of Object.entries(a))typeof o=="string"&&o&&(r[n]=o);try{localStorage.setItem(bR,JSON.stringify(r))}catch{}return K("Syntro Bootstrap","Geo: fetched from worker:",r),r}}catch{}return{}}var kR={growthbook:t=>Xy({...t,autoInit:!0})};function IR(t,e){let a=kR[t];if(!a)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys(kR).join(", ")}`);return a(e)}var K4=["cdn.syntrologie.com","localhost","127.0.0.1"];function Y4(t){try{let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(console.warn("[SmartCanvas] CDN URL must use HTTPS:",t),!1):K4.some(n=>e.hostname===n)?!0:(console.warn("[SmartCanvas] CDN host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid CDN URL:",t),!1}}var Y0=class{constructor(e){B(this,"name","cdn");B(this,"url");B(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!Y4(this.url))throw new Error(`[SmartCanvas] CDN URL not allowed: ${this.url}`)}async fetch(){let e=performance.now(),a=await fetch(this.url,{credentials:"omit",cache:"default"});if(!a.ok)throw new Error(`[SmartCanvas] Failed to fetch config from CDN (${a.status})`);let r=await a.text();if(this.integrity){let l=await Q4(r),u=this.integrity.replace("sha384-","");if(l!==u)throw new Error(`[SmartCanvas] Config integrity check failed. Expected ${u}, got ${l}`)}let n=JSON.parse(r),o=performance.now()-e,i=a.headers.get("cache-control"),s=a.headers.get("age");return{config:n,meta:{source:"cdn",fetchTimeMs:o,cached:i?.includes("public")??!1,cacheAge:s?parseInt(s,10):void 0}}}};async function Q4(t){let a=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-384",a),n=new Uint8Array(r);return btoa(String.fromCharCode(...n))}function AR(t){return new Y0(t)}var J4="syntro_exp",eU="syntro_var",Q0=class{constructor(e){B(this,"name","experiments");B(this,"client");B(this,"featureKey");B(this,"manifestKey");B(this,"variantFlagPrefix");this.client=e.client,this.featureKey=e.featureKey,this.manifestKey=e.manifestKey,this.variantFlagPrefix=e.variantFlagPrefix}async fetch(){let e=performance.now();if(typeof window<"u"){let n=new URLSearchParams(window.location.search),o=n.get(J4),i=n.get(eU);if(o&&i!==null&&this.client.setForcedVariations){let s=parseInt(i,10);Number.isNaN(s)||(console.log(`[SmartCanvas] Preview mode: forcing "${o}" to variation ${s}`),this.client.setForcedVariations({[o]:s}))}}if(this.manifestKey||this.variantFlagPrefix||this.client.getAllFeatures){let n=this.fetchMultiFlag();if(n){let o=performance.now()-e;return{config:n,meta:{source:"experiments",fetchTimeMs:o,cached:!0}}}}if(!this.featureKey)throw new Error("[SmartCanvas] No featureKey configured and no variant flags found. Ensure at least one config feature flag exists in your experiment platform.");let a=this.client.getFeatureValue?.(this.featureKey,null);if(!a||typeof a!="object")throw new Error(`[SmartCanvas] Feature "${this.featureKey}" not found or invalid. Ensure the feature is configured in your experiment platform.`);let r=performance.now()-e;return{config:a,meta:{source:"experiments",fetchTimeMs:r,cached:!0}}}fetchMultiFlag(){let e=this.getVariantFlagKeys();return!e||e.length===0?null:Zf(this.client,e)}getVariantFlagKeys(){if(this.manifestKey){let e=this.client.getFeatureValue?.(this.manifestKey,null);if(e&&typeof e=="object"){let a=e.variant_flags;if(a&&a.length>0)return a}}if(this.client.getAllFeatures){let e=this.client.getAllFeatures();return this.variantFlagPrefix?Object.keys(e).filter(a=>a.startsWith(this.variantFlagPrefix)):Object.keys(e)}return[]}};function ER(t){return new Q0(t)}var tU="https://cdn.syntrologie.com/configs",TR={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return AR({baseUrl:t.baseUrl??tU,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return ER({featureKey:t.featureKey})}};function RR(t,e={}){let a=TR[t];if(!a)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys(TR).join(", ")}`);return a(e)}var MR={posthog:t=>$b(t),noop:()=>ax()};function OR(t,e){let a=MR[t];if(!a)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(MR).join(", ")}`);return a(e)}async function DR(t){ay(),K("Syntro Bootstrap","====== INIT ======"),K("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=Yf();if(console.log(`[DIAG] Mode detection: sdkMode=${e}`),console.log("[DIAG] editorSource:",Su()),console.log("[DIAG] editorConf:",Kf()),K("Syntro Bootstrap","SDK mode:",e??"normal"),!e&&typeof window<"u"){let E=!!window.__SYNTRO_EDITOR_PARAMS__,R=!!window.__SYNTRO_AUDIT_LEGEND__,M=!!window.__SYNTRO_REVIEW_DATA__;if(E||R||M){let F=[E&&"__SYNTRO_EDITOR_PARAMS__",R&&"__SYNTRO_AUDIT_LEGEND__",M&&"__SYNTRO_REVIEW_DATA__"].filter(Boolean);console.warn(`[Syntro Bootstrap] \u26A0 Mode detection returned null but mode-specific globals found: ${F.join(", ")}. This suggests URL params were lost (redirect?) but the service worker injected mode data. Check if replaceState failed or if page JS changed the URL before init().`)}}console.log(`[DIAG] Token resolution: options.token=${t.token?t.token.slice(0,15)+"...":"null"}`);let a=t.token;if(!a&&e){let R=Kf()?.syntro_token;R?.startsWith("syn_")&&(a=R,K("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${e} mode)`))}let r;if(a)if(a.startsWith("syn_"))K("Syntro Bootstrap","Token starts with syn_, decoding..."),r=qc(a),ay(r.d);else if(e)K("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${e} mode)`);else throw Xf("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),Xf("Syntro Bootstrap","Token received:",a),new Error("Invalid Syntro token: must start with 'syn_'");else if(e)K("Syntro Bootstrap",`\u2713 No token, but ${e} mode - proceeding`);else throw Xf("Syntro Bootstrap","\u274C No token provided and NOT in editor/audit/review mode!"),new Error("Syntro token is required (unless in editor, audit, or review mode)");let n=Wa("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||Wa("VITE_SYNTRO_EXPERIMENT_HOST")||r?.eh,o=Wa("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||Wa("VITE_SYNTRO_TELEMETRY_HOST")||r?.th,i=Wa("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||Wa("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,s=r?.g||Wa("NEXT_PUBLIC_SYNTRO_GEO_HOST")||Wa("VITE_SYNTRO_GEO_HOST")||LR,l=_R(),u=X0(),c={...u,...l};K("Syntro Bootstrap","Phase 1: Browser metadata:",u),K("Syntro Bootstrap","Phase 1: Cached segment attributes:",l);let d=K0(s),f,h=t.debug||t.testMode,S=Bc({debug:t.debug,history:h?new Pc(t.testMode?0:100):void 0,testMode:t.testMode});console.log("[Syntro Bootstrap] EventBus created");let x=sy({elementResolver:typeof window<"u"?(E,R)=>{let M=document.elementFromPoint(E,R);if(!M)return null;let F={tag_name:M.tagName.toLowerCase()};M.id&&(F.attr__id=M.id),M.className&&typeof M.className=="string"&&(F.classes=M.className.split(" ").filter(Boolean));for(let Z of M.attributes)Z.name.startsWith("data-")&&(F[`attr__${Z.name}`]=Z.value);return F}:void 0});x.onEvent(E=>S.publishEvent(E)),typeof window<"u"&&(setInterval(()=>x.tick(Date.now()),1e3),document.addEventListener("click",E=>{let R=[],M=E.target;for(;M&&M!==document.body;){let F={tag_name:M.tagName.toLowerCase()};for(let Z of M.attributes)(Z.name.startsWith("data-")||Z.name==="id"||Z.name==="class"||Z.name==="aria-label")&&(F[`attr__${Z.name}`]=Z.value);R.push(F),M=M.parentElement}x.enrichClickAttributes(Date.now(),R)},!0));let b=E=>{K("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let R=wR(E);if(K("Syntro Bootstrap","Segment flags from PostHog:",R),CR(R),f){let M=m?.getAll?.()??{},F={...u,...M,...R};K("Syntro Bootstrap","Updating GrowthBook with attributes:",F),f.setAttributes?.(F)}},g;if(r?.t){let E=r.t==="noop"?"noop":"posthog";g=OR(E,{apiKey:r.t,apiHost:o,enableFeatureFlags:!0,sessionRecording:!r.d,onFeatureFlagsLoaded:b,onCapture:(M,F)=>{x.ingest({kind:"posthog",event:M,properties:F,timestamp:Date.now()})},onRRWebEvent:M=>{x.ingest(M)}}),console.log(`[Syntro Bootstrap] Telemetry client created (${E}) with EventBus wiring`);let R=g;S.setPosthogCapture((M,F)=>{R.track?.(M,F)})}let m;r?.e&&(f=IR("growthbook",{clientKey:r.e,apiHost:n,attributes:c,onExperimentViewed:g?.trackExperiment?(E,R,M)=>{g.trackExperiment(E,R,M)}:void 0})),m=Ky({experiments:f,onMetricChange:(E,R)=>{K("Syntro Bootstrap",`Session metric changed: ${E} = ${R}`)}}),K("Syntro Bootstrap","SessionMetricTracker created");let y="production";e==="editor"?y="editor":e==="audit"?y="audit":Wa("NODE_ENV")==="development"&&(y="development");let v=G0({telemetry:g,sessionMetrics:m,mode:y,events:S});K("Syntro Bootstrap","Runtime created:",{version:v.version,mode:v.mode,hasContext:!!v.context,hasEvents:!!v.events,hasState:!!v.state}),K("Syntro Bootstrap","Core app executors already registered");let C=t.cdnBase||Wa("NEXT_PUBLIC_SYNTRO_CDN_BASE")||Wa("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",w=Pv({cdnBase:C,registry:v.apps,onLoadStart:E=>{K("Syntro Bootstrap",`Loading app from CDN: ${E}`)},onLoadEnd:(E,R,M)=>{R?K("Syntro Bootstrap",`App loaded successfully: ${E}`):na("Syntro Bootstrap",`Failed to load app: ${E}`,M)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:v.apps,runtime:v,version:v.version},K("Syntro Bootstrap","Global SynOS object exposed"));let _=v.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${_.length} apps in registry:`,_.map(E=>`${E.manifest.id}(${E.state})`).join(", "));for(let E of _)if(E.state==="registered")try{await v.apps.activate(E.manifest.id),console.log(`[DIAG] Activated: ${E.manifest.id} \u2192 widgets: [${v.widgets.list().join(", ")}]`)}catch(R){console.error(`[DIAG] FAILED to activate: ${E.manifest.id}`,R),na("Syntro Bootstrap",`Failed to auto-activate built-in app: ${E.manifest.id}`,R)}if(console.log(`[DIAG] Activation complete. Total widgets: [${v.widgets.list().join(", ")}]`),f?.refreshFeatures)try{await f.refreshFeatures(),K("Syntro Bootstrap","GrowthBook features loaded")}catch(E){na("Syntro Bootstrap","Failed to load GrowthBook features:",E)}let L=await d;if(f&&Object.keys(L).length>0){let E={...u,...L};K("Syntro Bootstrap","Merging geo data into GrowthBook attributes:",L),f.setAttributes?.(E)}let A;if(t.fetcher)A=t.fetcher;else if(r?.f){let E=RR(r.f,r.o??{});A=async()=>{let R=await E.fetch();return{...R.config,tiles:R.config.tiles??[]}}}else f&&(A=Cs({experiments:f}));let I=new Set,O=A?async()=>{let E=await A(),R=E.tiles?.length??0,M=E.actions?.length??0,F=E.meta?.variant_id;if((R>0||M>0)&&(F||console.warn("[Syntro] Config has content but no meta.variant_id \u2014 intervention tracking disabled")),g&&F){let W=new kc(g,F);W.trackServed(R,M),typeof window<"u"&&(window.SynOS.interventionTracker=W),v.navigation.subscribe(()=>{W.resetPage()})}console.log("[Syntro Bootstrap] Config fetched:",`tiles=${E.tiles?.length??0},`,`actions=${E.actions?.length??0},`,`theme=${E.theme?.name??"none"}`),E.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",E.actions.map((W,ce)=>`[${ce}] ${W.kind}${W.anchorId?` anchor="${W.anchorId.selector}"`:""}${W.label?` "${W.label}"`:""}`).join(", "));let Z=E,U=w.getRequiredApps(Z);return U.length>0?console.log("[Syntro Bootstrap] Required external apps:",U.join(", ")):K("Syntro Bootstrap","No external apps required (all executors are built-in)"),U.length>0&&await w.loadAppsForConfig(Z).then(async ce=>{let Xt=ce.filter(N=>N.success),it=ce.filter(N=>!N.success);Xt.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${Xt.map(N=>N.appId).join(", ")}`);let yt=it.filter(N=>!I.has(N.appId));yt.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",yt.map(N=>`${N.appId} (${N.error})`).join(", ")),yt.forEach(N=>I.add(N.appId)));for(let N of U)if(v.apps.has(N))try{await v.apps.activate(N),console.log(`[Syntro Bootstrap] App activated: ${N}`)}catch(te){console.error(`[Syntro Bootstrap] Failed to activate app: ${N}`,te)}else console.error(`[Syntro Bootstrap] App "${N}" required by config but NOT registered.`,`Available apps: [${Array.from(v.apps.list?.()??[]).join(", ")}]`)}),E}:void 0;return{canvas:await Ty({...t.canvas,fetcher:O,integrations:{experiments:f,telemetry:g},editorUrl:i,runtime:v}),runtime:v,experiments:f,telemetry:g,sessionMetrics:m,appLoader:w}}async function aU(t){try{return await DR(t)}catch(e){let a=e instanceof Error?e.message:String(e);console.warn("[Syntrologie] SDK initialization failed:",a),typeof document<"u"&&document.getElementById("syntrologie-anti-flicker")?.remove();return}}function rU(t,e={}){if(typeof window>"u")return;let a=window.SynOS?.runtime;a?.events?.publish&&a.events.publish({name:t,source:"custom",props:e})}var BR={init:aU,encodeToken:Z0,decodeToken:qc,events:{emit:rU}};typeof window<"u"&&(window.Syntro=BR);var PR="2026-04-14T23:18:39.787Z (e8c5fd43a3a)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${PR}`);let t=window.SynOS,e=t?.appRegistry||hu;window.SynOS={...t,appRegistry:e,_runtimeBuild:PR,React:NR.default,ReactDOM:{...nU,createPortal:Ah.createPortal,flushSync:Ah.flushSync}},D1(e)}export{zc as ANIMATION_KEYFRAMES,xh as ActivationConfigZ,zT as AddClassZ,Ga as AnchorIdZ,N4 as AnchorStateZ,p0 as AnchorVisibleConditionZ,Hf as AppRegistry,F4 as AugmentationZ,TT as BadgePositionZ,WT as BadgeZ,P4 as BoundingBoxZ,Lu as CanvasEvents,ex as CanvasRecipeZ,Lo as ConditionZ,bh as ContextManager,x0 as CooldownActiveConditionZ,Ac as CounterDefZ,w0 as CtaButtonZ,py as DEFAULT_COOLDOWN,fy as DEFAULT_TTL,Dc as DecisionStrategyZ,y0 as DismissedConditionZ,rt as EVENT_SCHEMA_VERSION,wh as EventBus,S0 as EventCountConditionZ,$4 as EventFilterZ,Pc as EventHistory,h0 as EventOccurredConditionZ,dR as EventSourceZ,hh as ExecutorRegistry,Oc as ExternalStrategyZ,X4 as FrequencyEntryZ,b0 as FrequencyLimitConditionZ,NH as HighlightStepZ,ET as HighlightStyleZ,jT as HighlightZ,$T as InsertHtmlZ,DT as InsertPositionZ,kc as InterventionTracker,dy as MAX_VISIBLE_TOASTS,Ic as MatchOpZ,OT as ModalContentZ,XT as ModalZ,Mc as ModelStrategyZ,QT as MountWidgetZ,YT as NavigateZ,Nc as NavigationMonitor,V4 as NormalizedEventZ,cy as NotificationToastStack,M4 as PageContextZ,O4 as PageHistoryEntryZ,d0 as PageUrlConditionZ,tR as ParallelZ,RT as PlacementZ,GT as PulseZ,PR as RUNTIME_SDK_BUILD,xR as RUNTIME_VERSION,qT as RemoveClassZ,f0 as RouteConditionZ,AT as RouteFilterZ,Tc as RuleStrategyZ,Ec as RuleZ,H4 as RuntimeContextZ,yy as RuntimeProvider,eo as SDK_SCHEMA_VERSION,ry as SDK_VERSION,mR as STATIC_SLOT_STYLES,Rc as ScoreStrategyZ,FT as ScrollBehaviorZ,C0 as ScrollLogicalPositionZ,KT as ScrollToZ,bA as SelectorZ,eR as SequenceZ,D4 as SessionContextZ,v0 as SessionMetricConditionZ,Ep as SessionMetricTracker,UT as SetAttrZ,VT as SetStyleZ,HT as SetTextZ,hI as ShadowCanvasOverlay,K1 as ShadowRootProvider,xI as SmartCanvasApp,oy as SmartCanvasController,Ay as SmartCanvasElement,L8 as SmartCanvasPortal,Mt as StandardEvents,m0 as StateEqualsConditionZ,Lh as StateStore,Z4 as StoredValueZ,BR as Syntro,Uu as TileCard,h$ as TileWheel,MT as TooltipContentZ,PH as TooltipStepZ,BT as TooltipTriggerZ,ZT as TooltipZ,NT as TourStepForSchemaZ,aR as TourZ,yh as TriggerWhenZ,g0 as ViewportConditionZ,B4 as ViewportContextZ,JT as WaitZ,PT as WidgetConfigZ,Ih as WidgetRegistry,hu as appRegistry,P0 as applyStaticSlotStyles,Dv as cleanupAppContext,bv as contentRuntime,T4 as coreActionStepSchemas,c0 as createActionEngine,L0 as createAnchorResolver,Ov as createAppContext,Pv as createAppLoader,Cs as createCanvasConfigFetcher,I0 as createContextManager,A0 as createDecisionEngine,E0 as createEventAccumulator,Bc as createEventBus,Xy as createGrowthBookClient,ax as createNoopClient,C8 as createOverlayRecipeFetcher,$b as createPostHogClient,tI as createPostHogNormalizer,Ky as createSessionMetricTracker,Ty as createSmartCanvas,Z1 as createSmartCanvasController,G0 as createSmartCanvasRuntime,B0 as createStateStore,z0 as createSurfaceContainer,V0 as createSurfaces,C9 as decisionSchemas,qc as decodeToken,Z0 as encodeToken,sR as evaluate,nR as evaluateCondition,oR as evaluateRule,Sh as evaluateRuleStrategy,_h as evaluateScoreStrategy,lR as evaluateSync,xn as executorRegistry,iP as getAntiFlickerSnippet,e1 as getAppIdFromActionKind,Bv as getAppIdFromWidgetId,m4 as getExecutor,kh as getSlotAnchorId,Uc as getSlotType,q0 as getSlotZIndex,Zb as hasExecutor,up as interpolateTemplate,Jk as isCoreActionKind,hy as matchEvent,y$ as needsMigration,Cu as normalizePostHogEvent,Mv as overlaysRuntime,zu as parseVersion,H0 as playEnterAnimation,U0 as playExitAnimation,Qf as registerConfigPredicates,CI as registerSmartCanvasElement,ny as resolveConfigUri,N0 as setupAdjacentPositioning,F0 as setupInlinePositioning,wu as shouldNormalizeEvent,mN as useDecision,my as useNotifications,gy as useNotifyWatcher,xy as usePageContext,Jr as useRuntime,dp as useRuntimeContext,pN as useRuntimeEvents,hN as useRuntimeState,dN as useSessionContext,vI as useShadowCanvasConfig,ks as useShadowRoot,fN as useViewportContext,Ar as validateAction,vh as validateActions,_9 as validateActivationConfig,b9 as validateCondition,v$ as validateConfig,bj as validateEventFilter,T0 as validateEventName,kG as validateFrequencyEntry,xj as validateNormalizedEvent,R0 as validateProps,x8 as validateRecipe,j9 as validateRuntimeContext,LG as validateStoredValue,S9 as validateStrategy,$0 as widgetRegistry};
503
+ `)),new Error(`Batch validation failed: ${E}`)}let A=f(),I=[],O=[];try{let E=await Promise.allSettled(_.map(M=>m(M))),R=[];for(let M of E)M.status==="fulfilled"?(I.push(M.value),O.push(M.value)):R.push(M.reason instanceof Error?M.reason:new Error(String(M.reason)));if(R.length>0&&O.length===0)throw R[0];R.length>0&&console.warn(`[ActionEngine] ${R.length}/${_.length} action(s) failed in batch:`,R.map(M=>M.message).join("; "))}catch(E){console.error(`[ActionEngine] Batch apply FAILED. Successfully applied: ${O.length}. Rolling back...`,E);for(let R of O)try{await R.revert()}catch{}throw E}return{id:A,handles:I,async revertAll(){for(let E=I.length-1;E>=0;E--)try{await I[E].revert()}catch(R){console.error(`[ActionEngine] Error reverting action ${I[E].id}:`,R)}},isApplied(){return I.every(E=>E.isApplied())}}}function v(_){return Ar(_)}function C(){return Array.from(c.values()).map(_=>({id:_.id,action:_.action,adaptiveId:_.adaptiveId,appliedTs:_.appliedTs,state:_.state}))}function w(){for(let _ of d.values())for(let L of _)try{L()}catch{}d.clear();for(let _ of c.values())if(_.state==="applied")try{_.cleanup()}catch(L){console.error("[ActionEngine] Error during cleanup:",L)}c.clear()}return{apply:m,applyBatch:y,validate:v,getActive:C,destroy:w}}var v4=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),wT=["ui.click","ui.scroll","ui.input","ui.change","ui.submit","ui.hover","ui.idle","ui.scroll_thrash","ui.focus_bounce","nav.page_view","nav.page_leave","behavior.rage_click","behavior.hesitation","behavior.confusion"],LT=p.enum(wT).describe("Event name to count. ui.* = user interactions and behavioral detectors, nav.* = page navigation, behavior.* = derived behavioral signals."),kT=["time_on_page","page_views","scroll_depth"],IT=p.enum(kT).describe("Session metric key. time_on_page = seconds on current page, page_views = pages visited this session, scroll_depth = 0-100 percentage.");var d0=p.object({type:p.literal("page_url"),url:p.string().describe('URL path to match (e.g. "/pricing", "/dashboard")')}).describe('Fires when the current page URL matches. Use for page-specific actions. Example: {"type": "page_url", "url": "/pricing"}'),f0=p.object({type:p.literal("route"),routeId:p.string().describe("Named route ID from the route filter")}).describe("Fires when the current route matches a named route ID."),p0=p.object({type:p.literal("anchor_visible"),anchorId:p.string().describe("CSS selector of the anchor element"),state:p.enum(["visible","present","absent"]).describe('"visible" = in viewport, "present" = in DOM, "absent" = not in DOM')}).describe(`Fires based on a DOM element's visibility state. Example: {"type": "anchor_visible", "anchorId": "#cta-button", "state": "visible"}`),h0=p.object({type:p.literal("event_occurred"),eventName:p.string().describe('Event name (e.g. "ui.click", "$pageview")'),withinMs:p.number().optional().describe("Time window in ms. Omit = any time this session.")}).describe('Fires when a specific event has occurred during this session. Example: {"type": "event_occurred", "eventName": "ui.click", "withinMs": 5000}'),m0=p.object({type:p.literal("state_equals"),key:p.string().describe("Key in the SDK persistent state store (localStorage). Only valid for keys the host app explicitly sets via syntro.state.set()."),value:p.unknown().describe("Expected value to match against")}).describe("Checks the SDK persistent state store (localStorage). ONLY for host-app state set via syntro.state.set() \u2014 NOT for user attributes like region, device, or UTM params (those are handled by segment targeting). Do NOT use this for targeting. If you do not know the valid state keys, do not use this condition type."),g0=p.object({type:p.literal("viewport"),minWidth:p.number().optional().describe("Minimum viewport width in pixels"),maxWidth:p.number().optional().describe("Maximum viewport width in pixels"),minHeight:p.number().optional().describe("Minimum viewport height in pixels"),maxHeight:p.number().optional().describe("Maximum viewport height in pixels")}).describe('Fires based on viewport (screen) size. Use for responsive behavior. Example: {"type": "viewport", "minWidth": 768} \u2014 fires on tablet and larger.'),v0=p.object({type:p.literal("session_metric"),key:IT,operator:p.enum(["gte","lte","eq","gt","lt"]),threshold:p.number().describe("Numeric threshold to compare against")}).describe('Fires when a session metric crosses a threshold. Valid keys: "time_on_page" (seconds), "page_views" (count), "scroll_depth" (0-100). Example: {"type": "session_metric", "key": "time_on_page", "operator": "gte", "threshold": 30}'),y0=p.object({type:p.literal("dismissed"),key:p.string().describe("Dismissal key (usually a tile or action ID)"),inverted:p.boolean().optional().describe("When true, fires if NOT dismissed (default behavior)")}).describe("Checks if an item has been dismissed by the user. Use with inverted: true to show only if not dismissed."),x0=p.object({type:p.literal("cooldown_active"),key:p.string().describe("Cooldown key"),inverted:p.boolean().optional().describe("When true, fires if cooldown is NOT active")}).describe("Checks if a cooldown timer is currently active. Use to prevent showing the same intervention too frequently."),b0=p.object({type:p.literal("frequency_limit"),key:p.string().describe("Frequency counter key"),limit:p.number().describe("Maximum allowed count"),inverted:p.boolean().optional().describe("When true, fires if limit NOT reached")}).describe("Checks if a frequency limit has been reached. Use to cap how many times an action fires per session."),Ic=p.object({equals:p.union([p.string(),p.number(),p.boolean()]).optional(),contains:p.string().optional()}).describe("Match operator for counter filters. Exactly one of equals or contains must be specified."),Ac=p.object({events:p.array(LT).min(1).describe("Event names to count. Use values from the countable events enum."),match:p.record(p.string(),Ic).optional().describe("Property filters. Keys are event prop names or element-chain fields (tag_name, $el_text, attr__*). All entries AND together.")}).describe("Defines what events to count. Registered as an accumulator predicate at config-load time."),S0=p.object({type:p.literal("event_count"),key:p.string().describe("Unique key for this counter (used for accumulator registration)"),operator:p.enum(["gte","lte","eq","gt","lt"]),count:p.number().int().min(0).describe("Target count threshold"),withinMs:p.number().positive().optional().describe("Time window in ms. Omit = count across entire session."),counter:Ac.optional().describe("Inline counter definition. Defines what events to count.")}).describe('Fires when accumulated event count crosses a threshold. Most powerful trigger type. Example: {"type": "event_count", "key": "pricing-clicks", "operator": "gte", "count": 3, "counter": {"events": ["ui.click"], "match": {"attr__data-cta": {"contains": "pricing"}}}}'),Lo=p.discriminatedUnion("type",[d0,f0,p0,h0,m0,g0,v0,y0,x0,b0,S0]),Ec=p.object({conditions:p.array(Lo).describe("Array of conditions \u2014 ALL must match (AND logic) for this rule to fire."),value:p.unknown().describe("Value returned when all conditions match. For triggerWhen: true = fire the action.")}).describe("A single rule. ALL conditions must match (AND logic). Rules in a strategy are evaluated top-to-bottom \u2014 first rule where all conditions match wins and returns its value."),Tc=p.object({type:p.literal("rules"),rules:p.array(Ec).describe("Ordered list of rules. Evaluated top-to-bottom \u2014 first match wins."),default:p.unknown().describe("Fallback value when no rule matches. For triggerWhen: false = do not fire by default.")}).describe("Rule-based strategy. Evaluates rules top-to-bottom. First rule where ALL conditions match returns its value. If no rule matches, returns default. For triggerWhen: set value=true on matching rules, default=false."),Rc=p.object({type:p.literal("score"),field:p.string(),threshold:p.number(),above:p.unknown(),below:p.unknown()}).describe("Score-based strategy. Compares a field value against a threshold."),Mc=p.object({type:p.literal("model"),modelId:p.string(),inputs:p.array(p.string()),outputMapping:p.record(p.string(),p.unknown()),default:p.unknown()}).describe("ML model strategy. Sends inputs to a model and maps outputs."),Oc=p.object({type:p.literal("external"),endpoint:p.string(),method:p.enum(["GET","POST"]).optional(),default:p.unknown(),timeoutMs:p.number().optional()}).describe("External API strategy. Calls an endpoint to determine the value."),Dc=p.discriminatedUnion("type",[Tc,Rc,Mc,Oc]),yh=Dc.nullable().optional();var y4=p.object({events:p.array(p.string()),urlContains:p.string().optional(),props:p.record(p.union([p.string(),p.number(),p.boolean()])).optional()}),x4=p.object({title:p.string().optional(),body:p.string().optional(),icon:p.string().optional()}).nullable().optional();var AT=p.object({include:p.array(p.string()).optional().describe("URL patterns where this tile appears. Supports *, **, :param wildcards. Use sparingly \u2014 mostly to isolate to specific webapp functionality. Omit to appear on all routes."),exclude:p.array(p.string()).optional().describe("URL patterns where this tile should NOT appear. Evaluated before include.")}),xh=p.object({routes:AT,onlyIfPopulated:p.boolean().optional().describe("When true, tile is hidden if none of its props.actions[] have an active triggerWhen. Useful for tiles with all-deferred FAQ questions or nav tips. Default: false.")});function b9(t){return Lo.safeParse(t)}function S9(t){return Dc.safeParse(t)}function _9(t){return xh.safeParse(t)}var C9=[{defName:"matchOp",schema:Ic},{defName:"counterDef",schema:Ac},{defName:"activationConfig",schema:xh},{defName:"routeFilter",schema:AT},{defName:"ruleStrategy",schema:Tc},{defName:"scoreStrategy",schema:Rc},{defName:"modelStrategy",schema:Mc},{defName:"externalStrategy",schema:Oc},{defName:"rule",schema:Ec},{defName:"condition",schema:Lo}];var _0=p.object({tileId:p.string(),itemId:p.string().optional()}).strict(),b4=p.object({on:p.string(),title:p.string(),body:p.string().optional(),icon:p.string().optional(),ttl:p.number().optional(),cooldown:p.number().optional(),deepLink:_0.optional()}).strict(),S4=p.object({id:p.string(),title:p.string().optional(),subtitle:p.string().optional(),icon:p.string().optional(),priority:p.number().optional(),widget:p.string(),props:p.record(p.unknown()).optional(),activation:xh.optional(),notifications:p.array(b4).optional()}).strict(),_4=p.object({position:p.enum(["left","right"]).optional(),layout:p.enum(["overlay","push"]).optional(),background:p.string().optional(),blur:p.string().optional(),border:p.string().optional(),width:p.string().optional(),transitionDuration:p.string().optional(),transitionEasing:p.string().optional(),transitionFade:p.string().optional()}),C4=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),color:p.string().optional(),size:p.string().optional(),shadow:p.string().optional(),borderRadius:p.string().optional(),icon:p.string().optional()}),w4=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),shadow:p.string().optional(),titleColor:p.string().optional(),textColor:p.string().optional(),iconBackground:p.string().optional(),iconShadow:p.string().optional(),headerPadding:p.string().optional(),bodyPadding:p.string().optional(),gap:p.string().optional()}),L4=p.object({background:p.string().optional(),textColor:p.string().optional(),titleColor:p.string().optional(),arrowColor:p.string().optional(),arrowSize:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),scrimOpacity:p.string().optional(),highlightRing:p.string().optional()}),k4=p.object({background:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),successColor:p.string().optional(),warningColor:p.string().optional(),errorColor:p.string().optional(),iconBackground:p.string().optional(),progressGradient:p.string().optional()}),I4=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),itemDivider:p.string().optional(),itemGap:p.string().optional(),itemPadding:p.string().optional(),itemFontSize:p.string().optional(),bodyPadding:p.string().optional(),bodyFontSize:p.string().optional(),categoryPadding:p.string().optional(),categoryGap:p.string().optional(),categoryFontSize:p.string().optional(),searchBackground:p.string().optional(),searchColor:p.string().optional(),chevronColor:p.string().optional()}),A4=p.object({mode:p.enum(["dark","light"]).optional(),fontFamily:p.string().optional(),colorPrimary:p.string().optional(),colorPrimaryHover:p.string().optional(),borderRadius:p.string().optional(),canvas:_4.optional(),launcher:C4.optional(),tile:w4.optional(),overlay:L4.optional(),notification:k4.optional(),content:I4.optional()}).strict(),E4=p.object({enabled:p.boolean().optional(),label:p.string().optional(),position:p.string().optional(),animate:p.boolean().optional(),animationStyle:p.enum(["pulse","bounce","glow"]).optional(),notificationCount:p.number().optional()}).strict(),A9=p.object({schemaVersion:p.string().optional(),fetchedAt:p.string().datetime(),configVersion:p.string().optional(),canvasTitle:p.string().optional(),tiles:p.array(S4),actions:p.array(p.any()),theme:A4.optional(),launcher:E4.optional(),meta:p.object({verificationSteps:p.array(p.union([p.string(),p.object({text:p.string(),check:Lo.optional()})])).optional()}).passthrough().optional()}).strict();var Ct={triggerWhen:yh},Ga=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),ET=p.object({color:p.string().optional(),scrimOpacity:p.number().min(0).max(1).optional(),paddingPx:p.number().optional(),radiusPx:p.number().optional()}).strict(),TT=p.enum(["top-left","top-right","bottom-left","bottom-right"]),RT=p.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),w0=p.object({label:p.string(),actionId:p.string(),primary:p.boolean().optional()}).strict(),MT=p.object({title:p.string().optional(),body:p.string(),ctaButtons:p.array(w0).optional()}).strict(),OT=p.object({title:p.string().optional(),body:p.string()}).strict(),DT=p.enum(["before","after","prepend","append","replace"]),BT=p.enum(["immediate","hover","click"]),PT=p.object({widgetId:p.string(),props:p.record(p.unknown()).optional(),priority:p.number().optional()}).strict(),NT=p.object({id:p.string(),action:p.any(),route:p.string().optional(),onAction:p.record(p.string()).optional()}).passthrough(),FT=p.enum(["auto","smooth","instant"]),C0=p.enum(["start","center","end","nearest"]),HT=p.object({kind:p.literal("content:setText"),anchorId:Ga,text:p.string(),label:p.string().optional()}).extend(Ct).strict(),UT=p.object({kind:p.literal("content:setAttr"),anchorId:Ga,attr:p.string(),value:p.string(),label:p.string().optional()}).extend(Ct).strict(),zT=p.object({kind:p.literal("content:addClass"),anchorId:Ga,className:p.string(),label:p.string().optional()}).extend(Ct).strict(),qT=p.object({kind:p.literal("content:removeClass"),anchorId:Ga,className:p.string(),label:p.string().optional()}).extend(Ct).strict(),VT=p.object({kind:p.literal("content:setStyle"),anchorId:Ga,styles:p.record(p.string()),label:p.string().optional()}).extend(Ct).strict(),$T=p.object({kind:p.literal("content:insertHtml"),anchorId:Ga,html:p.string(),position:DT,deepLink:_0.optional(),label:p.string().optional()}).extend(Ct).strict(),jT=p.object({kind:p.literal("overlays:highlight"),anchorId:Ga,style:ET.optional(),duration:p.number().optional(),label:p.string().optional()}).extend(Ct).strict(),GT=p.object({kind:p.literal("overlays:pulse"),anchorId:Ga,duration:p.number().optional(),label:p.string().optional()}).extend(Ct).strict(),WT=p.object({kind:p.literal("overlays:badge"),anchorId:Ga,content:p.string(),position:TT.optional(),label:p.string().optional()}).extend(Ct).strict(),ZT=p.object({kind:p.literal("overlays:tooltip"),anchorId:Ga,content:MT,trigger:BT.optional(),placement:RT.optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(Ct).strict(),XT=p.object({kind:p.literal("overlays:modal"),content:OT,size:p.enum(["sm","md","lg"]).optional(),blocking:p.boolean().optional(),scrim:p.object({opacity:p.number().min(0).max(1).optional()}).strict().optional(),dismiss:p.object({onEsc:p.boolean().optional(),closeButton:p.boolean().optional(),timeoutMs:p.number().min(0).optional()}).strict().optional(),ctaButtons:p.array(w0).optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(Ct).strict(),KT=p.object({kind:p.literal("navigation:scrollTo"),anchorId:Ga,behavior:FT.optional(),block:C0.optional(),inline:C0.optional(),label:p.string().optional()}).extend(Ct).strict(),YT=p.object({kind:p.literal("navigation:navigate"),url:p.string(),target:p.enum(["_self","_blank"]).optional(),label:p.string().optional()}).extend(Ct).strict(),QT=p.object({kind:p.literal("core:mountWidget"),slot:p.string(),widget:PT,label:p.string().optional()}).extend(Ct).strict(),JT=p.object({kind:p.literal("core:wait"),durationMs:p.number().min(0).optional(),event:p.string().optional(),label:p.string().optional()}).extend(Ct).strict(),eR=p.object({kind:p.literal("core:sequence"),actions:p.array(p.any()),label:p.string().optional()}).extend(Ct).strict(),tR=p.object({kind:p.literal("core:parallel"),actions:p.array(p.any()),waitFor:p.enum(["all","any"]).optional(),label:p.string().optional()}).extend(Ct).strict(),aR=p.object({kind:p.literal("overlays:tour"),tourId:p.string(),steps:p.array(NT).min(1),startStep:p.string().optional(),autoStart:p.boolean().optional(),label:p.string().optional()}).extend(Ct).passthrough(),T4=[{defName:"setText",schema:HT},{defName:"setAttr",schema:UT},{defName:"addClass",schema:zT},{defName:"removeClass",schema:qT},{defName:"setStyle",schema:VT},{defName:"insertHtml",schema:$T},{defName:"highlight",schema:jT},{defName:"pulse",schema:GT},{defName:"badge",schema:WT},{defName:"tooltip",schema:ZT},{defName:"modal",schema:XT},{defName:"scrollTo",schema:KT},{defName:"navigate",schema:YT},{defName:"mountWidget",schema:QT},{defName:"wait",schema:JT},{defName:"sequence",schema:eR},{defName:"parallel",schema:tR},{defName:"tour",schema:aR}];function L0(t){let e=t?.root??(typeof document<"u"?document.body:null),a=t?.defaultTimeoutMs??5e3,r=new Map,n=new Map,o=null,i=!1;function s(b){if(!e)return null;try{return e.matches(b)?e:e.querySelector(b)}catch{return null}}function l(){for(let[b,g]of r){let m=s(b);if(m){for(let y of g)clearTimeout(y.timer),y.resolve(m);r.delete(b)}}for(let[b,g]of n){let m=s(b);if(m){for(let y of g)y.cancelled||y.cb(m);n.delete(b)}}r.size===0&&n.size===0&&c()}function u(){o||i||typeof MutationObserver>"u"||!e||(o=new MutationObserver(()=>{l()}),o.observe(e,{childList:!0,subtree:!0}))}function c(){o&&(o.disconnect(),o=null)}function d(b,g){let m=r.get(b);m&&(m.delete(g),m.size===0&&r.delete(b)),r.size===0&&n.size===0&&c()}function f(b,g){if(i)return Promise.reject(new Error("AnchorResolver destroyed"));let m=s(b);if(m)return Promise.resolve(m);let y=g??a;return new Promise((v,C)=>{let w={resolve:v,reject:C,timer:setTimeout(()=>{d(b,w),C(new Error(`waitFor("${b}") timed out after ${y}ms`))},y)},_=r.get(b);_||(_=new Set,r.set(b,_)),_.add(w),u()})}function h(b,g){if(i)return()=>{};let m=s(b);if(m)return g(m),()=>{};let y={cb:g,cancelled:!1},v=n.get(b);return v||(v=new Set,n.set(b,v)),v.add(y),u(),()=>{y.cancelled=!0;let C=n.get(b);C&&(C.delete(y),C.size===0&&n.delete(b)),r.size===0&&n.size===0&&c()}}function S(){let b=0;for(let g of r.values())b+=g.size;return b}function x(){i=!0,c();let b=new Error("AnchorResolver destroyed");for(let g of r.values())for(let m of g)clearTimeout(m.timer),m.reject(b);r.clear(),n.clear()}return{resolve:s,waitFor:f,onAppear:h,pendingCount:S,destroy:x}}function R4(){let t=Date.now();return{page:{url:typeof window<"u"?window.location.href:"",title:typeof document<"u"?document.title:void 0},session:{sessionId:"",startTs:t,pageHistory:[]},viewport:{width:typeof window<"u"?window.innerWidth:0,height:typeof window<"u"?window.innerHeight:0}}}function k0(t,e){if(!e)return;let a;try{a=new URL(t).pathname}catch{a=t}if(e.exclude){for(let r of e.exclude)if(rR(a,r))return}if(e.include){for(let r of e.include)if(rR(a,r))return r;return}return a}function rR(t,e){let a=t.replace(/\/$/,"")||"/",r=e.replace(/\/$/,"")||"/";if(a===r)return!0;let n=r.replace(/:[^/]+/g,"[^/]+").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(a)}var bh=class{constructor(e){B(this,"context");B(this,"previousContext");B(this,"listeners",new Set);B(this,"telemetry");B(this,"routes");B(this,"navigation");B(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=R4(),this.previousContext={...this.context},e.telemetry?.getSessionId){let a=e.telemetry.getSessionId();a&&(this.context.session.sessionId=a)}e.initialPageHistory&&(this.context.session.pageHistory=e.initialPageHistory),this.context.page.routeId=k0(this.context.page.url,this.routes),this.addPageToHistory(this.context.page.url),typeof window<"u"&&this.setupBrowserListeners()}get(){return{...this.context}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setRoutes(e){this.routes=e;let a=k0(this.context.page.url,this.routes);a!==this.context.page.routeId&&this.updateContext({page:{...this.context.page,routeId:a}})}setAnchors(e){this.updateContext({anchors:e})}setSessionId(e){e!==this.context.session.sessionId&&this.updateContext({session:{...this.context.session,sessionId:e}})}destroy(){for(let e of this.cleanupFns)e();this.cleanupFns=[],this.listeners.clear()}setupBrowserListeners(){let e,a=()=>{clearTimeout(e),e=setTimeout(()=>{this.updateViewport()},100)};window.addEventListener("resize",a),this.cleanupFns.push(()=>window.removeEventListener("resize",a));let r=this.navigation.subscribe(()=>this.updatePage());this.cleanupFns.push(r)}updateViewport(){let e={width:window.innerWidth,height:window.innerHeight};(e.width!==this.context.viewport.width||e.height!==this.context.viewport.height)&&this.updateContext({viewport:e})}updatePage(){let e=window.location.href,{title:a}=document,r=k0(e,this.routes),n={url:e,title:a,routeId:r};(n.url!==this.context.page.url||n.title!==this.context.page.title||n.routeId!==this.context.page.routeId)&&(n.url!==this.context.page.url&&this.addPageToHistory(n.url),this.updateContext({page:n}))}addPageToHistory(e){let a={url:e,ts:Date.now()},r=[...this.context.session.pageHistory||[],a];r.length>50&&r.shift(),this.context.session.pageHistory=r}updateContext(e){this.previousContext={...this.context},this.context={...this.context,...e},this.notifyListeners()}notifyListeners(){for(let e of this.listeners)try{e(this.context,this.previousContext)}catch(a){console.error("[ContextManager] Listener error:",a)}}};function I0(t){return new bh(t)}var M4=p.object({url:p.string(),routeId:p.string().optional(),title:p.string().optional(),locale:p.string().optional()}),O4=p.object({url:p.string(),ts:p.number()}),D4=p.object({sessionId:p.string(),startTs:p.number(),pageHistory:p.array(O4).optional()}),B4=p.object({width:p.number(),height:p.number()}),P4=p.object({x:p.number(),y:p.number(),w:p.number(),h:p.number()}),N4=p.object({anchorId:p.string(),present:p.boolean(),visible:p.boolean().optional(),boundingBox:P4.optional()}),F4=p.record(p.string(),p.union([p.number(),p.string(),p.boolean(),p.undefined()])),H4=p.object({page:M4,session:D4,viewport:B4,anchors:p.array(N4).optional(),augmented:F4.optional()});function j9(t){return H4.safeParse(t)}function nR(t,e){let{context:a,state:r,events:n}=e;switch(t.type){case"page_url":{let{url:o}=t,i=a.page.url.split("?")[0].split("#")[0],s=o.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*");return new RegExp(`^${s}$`).test(i)}case"route":return a.page.routeId===t.routeId;case"anchor_visible":{let o=a.anchors?.find(i=>i.anchorId===t.anchorId);switch(t.state){case"visible":return o?.visible===!0;case"present":return o?.present===!0;case"absent":return!o?.present;default:return!1}}case"event_occurred":{if(!n)return!1;let o=t.withinMs??6e4;return n.hasRecentEvent(t.eventName,o)}case"state_equals":return r?.getValue?r.getValue(t.key)===t.value:!1;case"viewport":{let{width:o,height:i}=a.viewport;return!(t.minWidth!==void 0&&o<t.minWidth||t.maxWidth!==void 0&&o>t.maxWidth||t.minHeight!==void 0&&i<t.minHeight||t.maxHeight!==void 0&&i>t.maxHeight)}case"session_metric":{if(!r)return!1;let o=r.getSessionMetric(t.key),{operator:i,threshold:s}=t;switch(i){case"gte":return o>=s;case"lte":return o<=s;case"eq":return o===s;case"gt":return o>s;case"lt":return o<s;default:return!1}}case"dismissed":{if(!r)return t.inverted??!1;let o=r.isDismissed(t.key);return t.inverted?!o:o}case"cooldown_active":{if(!r)return t.inverted??!1;let o=r.isCooldownActive(t.key);return t.inverted?!o:o}case"frequency_limit":{if(!r)return t.inverted??!1;let i=r.getFrequencyCount(t.key)>=t.limit;return t.inverted?!i:i}case"event_count":{if(!e.accumulator)return!1;let o=t,i=e.accumulator.getCount(o.key,o.withinMs);switch(o.operator){case"gte":return i>=o.count;case"lte":return i<=o.count;case"eq":return i===o.count;case"gt":return i>o.count;case"lt":return i<o.count;default:return!1}}default:return console.warn("[RuleStrategy] Unknown condition type:",t.type),!1}}function oR(t,e){let a=[];for(let r of t.conditions){let n=nR(r,e);if(a.push({condition:r,result:n}),!n)return{matched:!1,conditionResults:a}}return{matched:!0,conditionResults:a}}function Sh(t,e){for(let a=0;a<t.rules.length;a++){let r=t.rules[a],{matched:n,conditionResults:o}=oR(r,e);if(n)return{value:r.value,isFallback:!1,matchInfo:{strategyType:"rules",matchedRuleIndex:a,evaluatedConditions:o}}}return{value:t.default,isFallback:!0,matchInfo:{strategyType:"rules"}}}function _h(t,e){let{context:a}=e,r=a.augmented?.[t.field];return r===void 0||typeof r!="number"?{value:t.below,isFallback:!0,matchInfo:{strategyType:"score"}}:{value:r>=t.threshold?t.above:t.below,isFallback:!1,matchInfo:{strategyType:"score"}}}function iR(t,e){let{state:a,events:r,sessionMetrics:n,accumulator:o}=e;return{context:t,state:a?{isDismissed:i=>a.dismissals.isDismissed(i),isCooldownActive:i=>a.cooldowns.isActive(i),getFrequencyCount:i=>a.frequency.count(i),getSessionMetric:i=>n?.get(i)??0,getValue:i=>a.session.get(i)??a.user.get(i)}:void 0,events:r?{hasRecentEvent:(i,s)=>r.hasRecentEvent(i,s)}:void 0,accumulator:o?{getCount:(i,s)=>o.getCount(i,s)}:void 0}}async function sR(t,e,a={}){let r=iR(e,a);switch(t.type){case"rules":return Sh(t,r);case"score":return _h(t,r);case"model":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"model"}};case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"external"}};default:return console.warn("[DecisionEngine] Unknown strategy type:",t.type),{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function lR(t,e,a={}){let r=iR(e,a);switch(t.type){case"rules":return Sh(t,r);case"score":return _h(t,r);case"model":case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:t.type}};default:return{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function A0(t){return{evaluate:(e,a)=>sR(e,a,t),evaluateSync:(e,a)=>lR(e,a,t)}}function E0(t){let{eventBus:e,stateStore:a}=t,r=new Map,n=new Set,o=null,i=a.ns("accumulator");function s(u){let c=!1;for(let d of r.values()){if(!d.predicate(u))continue;let f=i.get(d.stateKey)||{count:0};f.count++,d.needsTimestamps&&(f.timestamps||(f.timestamps=[]),f.timestamps.push(u.ts),f.timestamps.length>200&&(f.timestamps=f.timestamps.slice(-200))),i.set(d.stateKey,f),c=!0}if(c)for(let d of n)try{d()}catch(f){console.error("[EventAccumulator] Subscriber error:",f)}}function l(){o||r.size===0||(o=e.subscribe(s))}return{register(u,c,d=!1){let f=`ev:${u}`,h=r.get(f);if(h){d&&!h.needsTimestamps&&(h.needsTimestamps=!0);return}r.set(f,{stateKey:f,needsTimestamps:d,predicate:c}),l()},getCount(u,c){let d=`ev:${u}`,f=i.get(d);if(!f)return 0;if(c===void 0||!f.timestamps)return f.count;let h=Date.now()-c;return f.timestamps.filter(S=>S>=h).length},subscribe(u){return n.add(u),()=>{n.delete(u)}},destroy(){o&&(o(),o=null),r.clear(),n.clear()}}}var uR="app:",U4="syntro:",z4=/^[a-z][a-z0-9_]*$/;function T0(t){if(!t)return{valid:!1,reason:"Event name cannot be empty"};if(t.startsWith(U4))return{valid:!1,reason:'"syntro:" prefix is reserved for internal SDK events'};if(!t.startsWith(uR))return{valid:!1,reason:`Custom events must start with "app:" prefix. Got: "${t}"`};let e=t.slice(uR.length).split(":");if(e.length<2)return{valid:!1,reason:`Event name must have at least 2 segments after "app:" (app:{category}:{action}). Got: "${t}"`};for(let a of e)if(!z4.test(a))return{valid:!1,reason:`Segment "${a}" must be lowercase alphanumeric + underscores. Got: "${t}"`};return{valid:!0}}function q4(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t===null}function cR(t,e,a=0){if(a>=e)return!1;for(let r of Object.values(t))if(r!==null&&typeof r=="object"&&!Array.isArray(r)&&!cR(r,e,a+1))return!1;return!0}function R0(t){if(t===void 0)return{valid:!0};if(t===null||typeof t!="object"||Array.isArray(t))return{valid:!1,reason:"Props must be a plain object"};if(!cR(t,2))return{valid:!1,reason:"Props nesting depth exceeds 2 levels"};let e=[];for(let[a,r]of Object.entries(t))r!==null&&typeof r=="object"||q4(r)||e.push(a);return e.length>0?{valid:!0,stripped:e}:{valid:!0}}function Ch(t,e){return e?!(e.names&&e.names.length>0&&!e.names.includes(t.name)||e.patterns&&e.patterns.length>0&&!e.patterns.some(r=>{try{return new RegExp(r).test(t.name)}catch{return!1}})||e.sources&&e.sources.length>0&&!e.sources.includes(t.source)):!0}var wh=class{constructor(e={}){B(this,"subscriptions",new Set);B(this,"history",[]);B(this,"maxHistorySize");B(this,"debug");B(this,"emitHistory");B(this,"posthogCapture");B(this,"testMode");this.maxHistorySize=e.maxHistorySize??100,this.debug=e.debug??!1,this.emitHistory=e.history??null,this.posthogCapture=e.posthogCapture??null,this.testMode=e.testMode??!1}subscribe(e,a){let r,n;typeof e=="function"?(r=void 0,n=e):(r=e,n=a);let o={filter:r,callback:n};return this.subscriptions.add(o),()=>{this.subscriptions.delete(o)}}publish(e,a,r="canvas"){let n={ts:Date.now(),name:e,source:r,props:a,schemaVersion:rt};this.publishEvent(n)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let a of this.subscriptions)if(Ch(e,a.filter))try{a.callback(e)}catch(r){console.error("[EventBus] Subscriber error:",r)}}emit(e,a){let r=T0(e);if(!r.valid)return console.warn(`[EventBus] emit() rejected: ${r.reason}`),this.debug?{delivered:!1,matchedRules:[],posthogCaptured:!1,listenersNotified:0}:void 0;let n=R0(a);if(!n.valid)return console.warn(`[EventBus] emit() rejected props: ${n.reason}`),this.debug?{delivered:!1,matchedRules:[],posthogCaptured:!1,listenersNotified:0}:void 0;let o={ts:Date.now(),name:e,source:"custom",props:a,schemaVersion:rt};this.history.push(o),this.history.length>this.maxHistorySize&&this.history.shift();let i=0;for(let l of this.subscriptions)if(Ch(o,l.filter))try{l.callback(o),i++}catch(u){console.error("[EventBus] Subscriber error:",u),i++}let s=!1;if(this.posthogCapture&&!this.testMode)try{this.posthogCapture(e,a),s=!0}catch(l){console.error("[EventBus] PostHog capture error:",l)}if(this.emitHistory&&this.emitHistory.record({name:e,props:a,source:"custom",timestamp:o.ts,matchedRules:[]}),this.debug)return console.debug("[EventBus] emit()",{name:e,props:a,listenersNotified:i,posthogCaptured:s}),{delivered:!0,matchedRules:[],posthogCaptured:s,listenersNotified:i}}setPosthogCapture(e){this.posthogCapture=e}getRecent(e,a){let r=this.history;return e&&(r=r.filter(n=>Ch(n,e))),a&&a>0&&(r=r.slice(-a)),r}hasRecentEvent(e,a,r){let n=Date.now()-a;return this.history.some(o=>o.name===e&&o.ts>=n&&(r===void 0||o.source===r))}countRecentEvents(e,a){let r=this.history.filter(n=>Ch(n,e));if(a!==void 0){let n=Date.now()-a;r=r.filter(o=>o.ts>=n)}return r.length}clearHistory(){this.history=[]}getSubscriberCount(){return this.subscriptions.size}};function Bc(t={}){return new wh(t)}var Pc=class{constructor(e=100){B(this,"entries",[]);B(this,"maxSize");this.maxSize=e}record(e){this.entries.push(e),this.maxSize>0&&this.entries.length>this.maxSize&&this.entries.shift()}getAll(){return[...this.entries]}clear(){this.entries=[]}};var dR=p.enum(["posthog","canvas","derived"]),V4=p.object({ts:p.number(),name:p.string(),source:dR,props:p.record(p.string(),p.unknown()).optional(),schemaVersion:p.string()}),$4=p.object({names:p.array(p.string()).optional(),patterns:p.array(p.string()).optional(),sources:p.array(dR).optional()});function xj(t){return V4.safeParse(t)}function bj(t){return $4.safeParse(t)}var Nc=class{constructor(){B(this,"listeners",new Set);B(this,"capturedPushState");B(this,"capturedReplaceState");B(this,"wasNative");B(this,"destroyed",!1);B(this,"onPopState",()=>{this.notify(window.location.href,"popstate")});this.wasNative=this.isNativeFunction(history.pushState),this.capturedPushState=history.pushState,this.capturedReplaceState=history.replaceState,history.pushState=(...e)=>{this.capturedPushState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"pushState"))},history.replaceState=(...e)=>{this.capturedReplaceState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"replaceState"))},window.addEventListener("popstate",this.onPopState)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}diagnose(){return{isNative:this.wasNative,subscriberCount:this.listeners.size}}destroy(){this.destroyed||(this.destroyed=!0,history.pushState=this.capturedPushState,history.replaceState=this.capturedReplaceState,window.removeEventListener("popstate",this.onPopState),this.listeners.clear())}notify(e,a){if(!this.destroyed)for(let r of this.listeners)try{r(e,a)}catch{}}isNativeFunction(e){try{return Function.prototype.toString.call(e).includes("[native code]")}catch{return!1}}};var M0="cooldown:";function fR(t){return{set(e,a){let r=M0+e,n=Date.now()+a;t.set(r,n)},isActive(e){return this.remaining(e)>0},remaining(e){let a=M0+e,r=t.get(a);if(r===void 0)return 0;let n=r-Date.now();return n<=0?(t.remove(a),0):n},clear(e){let a=M0+e;t.remove(a)}}}var Fc="dismissed:";function pR(t,e){return{mark(a,r=!1){let n=Fc+a;(r?e:t).set(n,!0)},isDismissed(a){let r=Fc+a;return t.has(r)||e.has(r)},clear(a){let r=Fc+a;t.remove(r),e.remove(r)},clearAll(){for(let a of t.keys())a.startsWith(Fc)&&t.remove(a);for(let a of e.keys())a.startsWith(Fc)&&e.remove(a)}}}var O0="freq:";function hR(t){function e(a){let r=O0+a,n=t.get(r);if(n){if(n.resetAt&&Date.now()>=n.resetAt){t.remove(r);return}return n}}return{increment(a,r){let n=O0+a,o=e(a),i=(o?.count??0)+1,s={count:i,resetAt:o?.resetAt??(r?Date.now()+r:void 0)};return t.set(n,s),i},count(a){return e(a)?.count??0},reset(a){let r=O0+a;t.remove(r)},hasReachedLimit(a,r){return this.count(a)>=r}}}var j4="syntro";function D0(t,e){let a=`${e}:`;return{get(r){if(t)try{let n=t.getItem(a+r);if(!n)return;let o=JSON.parse(n);if(o.expiresAt&&Date.now()>=o.expiresAt){t.removeItem(a+r);return}return o.value}catch{return}},set(r,n,o){if(t)try{let i={value:n,expiresAt:o?Date.now()+o:void 0};t.setItem(a+r,JSON.stringify(i))}catch(i){console.warn("[StateStore] Failed to save:",i)}},remove(r){t&&t.removeItem(a+r)},has(r){return t?this.get(r)!==void 0:!1},keys(){if(!t)return[];let r=[];for(let n=0;n<t.length;n++){let o=t.key(n);o?.startsWith(a)&&r.push(o.slice(a.length))}return r},clear(){if(!t)return;let r=this.keys();for(let n of r)t.removeItem(a+n)}}}function Hc(t){let e=new Map,a=`${t}:`;return{get(r){let n=e.get(a+r);if(n){if(n.expiresAt&&Date.now()>=n.expiresAt){e.delete(a+r);return}return n.value}},set(r,n,o){e.set(a+r,{value:n,expiresAt:o?Date.now()+o:void 0})},remove(r){e.delete(a+r)},has(r){return this.get(r)!==void 0},keys(){let r=[];for(let n of e.keys())n.startsWith(a)&&r.push(n.slice(a.length));return r},clear(){for(let r of e.keys())r.startsWith(a)&&e.delete(r)}}}var Lh=class{constructor(e={}){B(this,"session");B(this,"user");B(this,"dismissals");B(this,"cooldowns");B(this,"frequency");B(this,"namespace");B(this,"namespacedStorages",new Map);this.namespace=e.namespace??j4;let a=r=>typeof r=="object"&&r!==null&&typeof r.setItem=="function";typeof window<"u"?(this.session=a(window.sessionStorage)?D0(window.sessionStorage,this.namespace):Hc(this.namespace),this.user=a(window.localStorage)?D0(window.localStorage,this.namespace):Hc(this.namespace)):(this.session=Hc(this.namespace),this.user=Hc(this.namespace)),this.dismissals=pR(this.session,this.user),this.cooldowns=fR(this.user),this.frequency=hR(this.session)}ns(e){let a=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(a)){let r=typeof window<"u"&&typeof sessionStorage<"u"?D0(sessionStorage,a):Hc(a);this.namespacedStorages.set(a,r)}return this.namespacedStorages.get(a)}};function B0(t={}){return new Lh(t)}function Uc(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function kh(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var mR={drawer_right:{position:"fixed",top:"0",right:"0",bottom:"0",width:"360px",maxWidth:"90vw"},drawer_left:{position:"fixed",top:"0",left:"0",bottom:"0",width:"360px",maxWidth:"90vw"},drawer_bottom:{position:"fixed",left:"0",right:"0",bottom:"0",maxHeight:"50vh"},overlay_center:{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)",maxWidth:"90vw",maxHeight:"90vh"},overlay_corner_br:{position:"fixed",bottom:"16px",right:"16px",maxWidth:"400px",maxHeight:"80vh"},overlay_corner_bl:{position:"fixed",bottom:"16px",left:"16px",maxWidth:"400px",maxHeight:"80vh"},toast_top:{position:"fixed",top:"16px",left:"50%",transform:"translateX(-50%)",maxWidth:"90vw"},toast_bottom:{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",maxWidth:"90vw"}},zc={fade:[{opacity:0},{opacity:1}],slide:[{opacity:0,transform:"translateY(10px)"},{opacity:1,transform:"translateY(0)"}],scale:[{opacity:0,transform:"scale(0.95)"},{opacity:1,transform:"scale(1)"}],none:[]},gR={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function P0(t,e,a){let r=mR[e];Object.assign(t.style,r),a&&(a.maxWidth&&(t.style.maxWidth=a.maxWidth),a.maxHeight&&(t.style.maxHeight=a.maxHeight),a.minWidth&&(t.style.minWidth=a.minWidth),a.minHeight&&(t.style.minHeight=a.minHeight))}function N0(t,e,a){let r=a.placement==="auto"?"bottom":a.placement,n=[Df(a.offset?{mainAxis:a.offset.y,crossAxis:a.offset.x}:8)];return a.flip!==!1&&n.push(Pf()),a.shift!==!1&&n.push(Bf({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",Of(e,t,async()=>{let{x:i,y:s,strategy:l}=await Nf(e,t,{placement:r,middleware:n});Object.assign(t.style,{position:l,left:`${i}px`,top:`${s}px`})})}function F0(t,e,a="append"){return t.style.position="relative",t.style.display="inline-block",a==="prepend"?e.insertBefore(t,e.firstChild):e.appendChild(t),()=>{t.remove()}}function H0(t,e){return e==="none"||zc[e].length===0?null:t.animate(zc[e],gR)}function U0(t,e){if(e==="none"||zc[e].length===0)return Promise.resolve();let a=[...zc[e]].reverse(),r=t.animate(a,gR);return new Promise(n=>{r.onfinish=()=>n(),r.oncancel=()=>n()})}function z0(t,e){let a=document.createElement("div");return a.setAttribute("data-syntro-surface",t),a.setAttribute("data-syntro-mount-id",e),a.className="syntro-surface",Object.assign(a.style,{pointerEvents:"auto",boxSizing:"border-box",overflow:"auto"}),a}function q0(t){switch(Uc(t)){case"static":return t.startsWith("drawer")?2147483640:t.startsWith("overlay")?2147483642:t.startsWith("toast")?2147483644:2147483640;case"inline":return 1;case"adjacent":return 2147483638;default:return 2147483640}}function vR(t){if(typeof window.Sanitizer=="function")try{let l=new window.Sanitizer({}).sanitizeToFragment(t),u=document.createElement("div");return u.append(l),u.innerHTML}catch{}let a=document.createElement("template");a.innerHTML=t;let r=a.content,n=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=new Set(["b","strong","i","em","u","span","div","p","br","ul","ol","li","code","pre","small","sup","sub","a","button"]),i=[];for(;n.nextNode();){let s=n.currentNode,l=s.tagName.toLowerCase();if(!o.has(l)){i.push(s);continue}for(let u of Array.from(s.attributes)){let c=u.name.toLowerCase(),d=u.value.trim().toLowerCase(),f=c.startsWith("on"),h=(c==="href"||c==="src")&&d.startsWith("javascript:");(f||h)&&s.removeAttribute(u.name)}}for(let s of i){for(;s.firstChild;)s.parentNode?.insertBefore(s.firstChild,s);s.remove()}return a.innerHTML=(r.firstChild,a.innerHTML)}var G4=0;function V0(t){let{overlayRoot:e,eventBus:a,anchorResolver:r,defaultAnimation:n="fade",widgetRegistry:o}=t,i=new Map,s=new Map,l=new Map;function u(){return`mount-${++G4}`}function c(v,C){a&&a.publish(v,C)}function d(v){let C=l.get(v);if(C){let w=b(v);for(let _ of C)try{_(w)}catch(L){console.error("[Surfaces] State callback error:",L)}}}let f=new Map;function h(v,C,w){switch(C.type){case"html":v.innerHTML=vR(C.content);return;case"widget":{if(o?.has(C.widgetId)){let _=o.mount(C.widgetId,v,C.config);return w&&f.set(w,_),()=>{_.unmount(),w&&f.delete(w)}}console.warn(`[Surfaces] Widget not found: ${C.widgetId}`),v.innerHTML=`<div data-widget-id="${C.widgetId}" data-widget-missing="true">Widget: ${C.widgetId}</div>`;return}case"custom":return C.mount(v);case"react":v.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function S(v,C,w){let _=u(),L=Uc(v),A=w?.priority??0,I=w?.animation??n,O=w?.exclusive??!0,H=i.get(v);if(H&&O){if(H.options.priority>A)throw new Error(`Slot ${v} is occupied by higher priority content (${H.options.priority} > ${A})`);x(H)}let E=z0(v,_);E.style.zIndex=String(q0(v));let R;if(L==="static")P0(E,v,w?.constraints),e.appendChild(E);else if(L==="inline"){let U=kh(v);if(!U)throw new Error(`Invalid inline slot: ${v}`);if(!r)throw new Error("Anchor resolver required for inline slots");let W=r({selector:U,route:"**"});if(!W)throw new Error(`Anchor not found for inline slot: ${U}`);R=F0(E,W)}else if(L==="adjacent"){let U=kh(v);if(!U)throw new Error(`Invalid adjacent slot: ${v}`);if(!r)throw new Error("Anchor resolver required for adjacent slots");let W=r({selector:U,route:"**"});if(!W)throw new Error(`Anchor not found for adjacent slot: ${U}`);e.appendChild(E),R=N0(E,W,w?.position??{placement:"bottom"})}let M=h(E,C,_);H0(E,I);let F={id:_,slot:v,content:C,options:{priority:A,exclusive:O,animation:I,position:w?.position??{placement:"auto"},constraints:w?.constraints??{},adaptiveId:w?.adaptiveId,autoUnmountOnRouteChange:w?.autoUnmountOnRouteChange??!0},container:E,cleanup:()=>{R?.(),M?.()},mountedAt:Date.now()};return i.set(v,F),s.set(v,(s.get(v)??0)+1),c("surface.mounted",{slot:v,id:_,adaptiveId:w?.adaptiveId}),d(v),{id:_,update(U){let W=i.get(v);if(!W||W.id!==_)throw new Error("Mount no longer active");let ce=f.get(_);if(ce){if(U.type==="widget"){ce.update(U.config),W.content=U;return}ce.unmount(),f.delete(_)}W.container.innerHTML="";let Xt=h(W.container,U,_);if(W.content=U,Xt){let it=W.cleanup;W.cleanup=()=>{it?.(),Xt()}}},setOptions(U){let W=i.get(v);if(!W||W.id!==_)throw new Error("Mount no longer active");U.priority!==void 0&&(W.options.priority=U.priority),U.animation!==void 0&&(W.options.animation=U.animation),U.constraints&&L==="static"&&(U.constraints.maxWidth&&(W.container.style.maxWidth=U.constraints.maxWidth),U.constraints.maxHeight&&(W.container.style.maxHeight=U.constraints.maxHeight),U.constraints.minWidth&&(W.container.style.minWidth=U.constraints.minWidth),U.constraints.minHeight&&(W.container.style.minHeight=U.constraints.minHeight)),d(v)},async unmount(){let U=i.get(v);!U||U.id!==_||await x(U)},isMounted(){return i.get(v)?.id===_},getContainer(){let U=i.get(v);return U?.id===_?U.container:null}}}async function x(v){v.container.isConnected&&await U0(v.container,v.options.animation);try{v.cleanup?.()}catch(C){console.warn("[Surfaces] Cleanup error during unmount, ignoring:",C)}try{v.container.remove()}catch{}i.delete(v.slot),c("surface.unmounted",{slot:v.slot,id:v.id}),d(v.slot)}function b(v){let C=i.get(v);return{slot:v,occupied:!!C,currentPriority:C?.options.priority,currentAdaptiveId:C?.options.adaptiveId,mountCount:s.get(v)??0,currentMountId:C?.id}}function g(v,C){let w=l.get(v);return w||(w=new Set,l.set(v,w)),w.add(C),()=>{w?.delete(C),w?.size===0&&l.delete(v)}}function m(v,C){let w=i.get(v);return w?C!==void 0?C>=w.options.priority:!1:!0}function y(){for(let v of i.values())try{v.cleanup?.(),v.container.remove()}catch(C){console.error("[Surfaces] Error during cleanup:",C)}i.clear(),l.clear()}return{mount:S,getState:b,onStateChange:g,canMount:m,destroy:y}}var Ih=class{constructor(){B(this,"widgets",new Map);B(this,"mountedWidgets",new Map);B(this,"mountIdCounter",0);B(this,"runtimeRef");B(this,"listeners",new Set)}bindRuntime(e){this.runtimeRef=e}register(e,a,r="custom",n){if(this.widgets.has(e)){if(this.widgets.get(e).source==="built-in")throw new Error(`Cannot override built-in widget: ${e}`);console.warn(`[WidgetRegistry] Overriding widget: ${e}`)}this.widgets.set(e,{id:e,widget:a,source:r,metadata:n}),this.notify({type:"registered",widgetId:e})}unregister(e){let a=this.widgets.get(e);return a?a.source==="built-in"?(console.warn(`[WidgetRegistry] Cannot unregister built-in widget: ${e}`),!1):(this.widgets.delete(e),this.notify({type:"unregistered",widgetId:e}),!0):!1}unregisterBySource(e){for(let[a,r]of this.widgets.entries())r.source===e&&this.widgets.delete(a)}get(e){return this.widgets.get(e)?.widget}getRegistration(e){return this.widgets.get(e)}has(e){return this.widgets.has(e)}mount(e,a,r){let n=this.widgets.get(e);if(!n)throw new Error(`Widget not found: ${e}`);let o=`widget-mount-${++this.mountIdCounter}`;a.setAttribute("data-widget-mount-id",o),a.setAttribute("data-widget-id",e);let i={...r,runtime:this.runtimeRef},s=n.widget.mount(a,i);return this.mountedWidgets.set(o,{cleanup:s??void 0,container:a}),{widgetId:e,container:a,unmount:()=>{let u=this.mountedWidgets.get(o);u&&(a.isConnected&&u.cleanup?.(),this.mountedWidgets.delete(o),a.removeAttribute("data-widget-mount-id"),a.removeAttribute("data-widget-id"),a.innerHTML="")},update:u=>{if(n.widget.update)n.widget.update(a,u);else{let c=this.mountedWidgets.get(o);if(c){c.cleanup?.(),a.innerHTML="";let d={...u,runtime:this.runtimeRef},f=n.widget.mount(a,d);c.cleanup=f??void 0}}}}}list(){return Array.from(this.widgets.keys())}listRegistrations(){return Array.from(this.widgets.values())}getBySource(e){return Array.from(this.widgets.values()).filter(a=>a.source===e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(let a of this.listeners)try{a(e)}catch(r){console.error("[WidgetRegistry] Listener error:",r)}}destroy(){for(let[e,a]of this.mountedWidgets.entries())a.cleanup?.(),a.container.innerHTML="";this.mountedWidgets.clear()}},$0=new Ih;var xR="2.0.0";function W4(t,e){if(!e)return!0;let a;try{a=new URL(t).pathname}catch{a=t}let r=a.replace(/\/$/,"")||"/";if(e.exclude){for(let n of e.exclude)if(j0(r,n))return!1}if(e.include&&e.include.length>0){for(let n of e.include)if(j0(r,n))return!0;return!1}return!0}function j0(t,e){let a=e.replace(/\/$/,"")||"/";if(t===a)return!0;let r=a.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*").replace(/:[^/]+/g,"[^/]+");return new RegExp(`^${r}$`).test(t)}function yR(t){let a=(typeof window<"u"?window.location.pathname:"/").replace(/\/$/,"")||"/";return(Array.isArray(t.route)?t.route:[t.route]).some(n=>{let o=n;if(/^https?:\/\//.test(o))try{o=new URL(o).pathname}catch{}return j0(a,o)})}function G0(t={}){let{telemetry:e,sessionMetrics:a,routes:r,mode:n="production",namespace:o}=t,i=t.widgets??$0,s=t.executors??xn,l=t.apps??hu,u=new Nc,c=I0({telemetry:e,routes:r,navigation:u}),d=t.events??Bc(),f=B0({namespace:o}),h=E0({eventBus:d,stateStore:f}),S=A0({state:f,events:d,sessionMetrics:a,accumulator:h}),x=W1(),b=L0(),g=_=>yR(_)?b.resolve(_.selector):null,m=async(_,L)=>{if(!yR(_))return null;try{return await b.waitFor(_.selector,L)}catch{return null}},y=V0({overlayRoot:x,eventBus:d,anchorResolver:g,widgetRegistry:i}),v=c0({overlayRoot:x,eventBus:d,surfaces:y,anchorResolver:g,waitForAnchor:m,executorRegistry:s,subscribeNavigation:_=>u.subscribe(_),runtime:{evaluateSync:_=>S.evaluateSync(_,c.get()),context:c,accumulator:h}}),C;if(a){a.increment("page_views");let _=typeof window<"u"?window.location.pathname:"/";C=u.subscribe((L,A)=>{if(A!=="replaceState")try{let I=new URL(L).pathname;I!==_&&(_=I,a.increment("page_views"))}catch{}})}let w={telemetry:e,context:c,events:d,state:f,sessionMetrics:a,actions:v,surfaces:y,widgets:i,executors:s,apps:l,accumulator:h,anchorResolver:b,navigation:u,version:xR,mode:n,async evaluate(_){return S.evaluate(_,c.get())},evaluateSync(_){return S.evaluateSync(_,c.get())},async filterTiles(_){let L=c.get().page.url,A=[];for(let I of _){let O=I.activation;if(!O){A.push(I);continue}if(W4(L,O.routes)){if(O.onlyIfPopulated){let H=I.props?.actions??[];if(H.length>0&&!H.some(R=>R.triggerWhen?S.evaluateSync(R.triggerWhen,c.get()).value:!0))continue}A.push(I)}}return A},setRoutes(_){c.setRoutes(_)},destroy(){l.unbind().catch(_=>{console.error("[Runtime] Error unbinding apps registry:",_)}),C?.(),b.destroy(),h.destroy(),u.destroy(),c.destroy(),v.destroy(),y.destroy()}};return l.bind(w),i.bindRuntime(w),w}var Z4=p.object({value:p.unknown(),expiresAt:p.number().optional()}),X4=p.object({count:p.number(),resetAt:p.number().optional()});function LG(t){return Z4.safeParse(t)}function kG(t){return X4.safeParse(t)}var W0="syn_";function qc(t){if(!t.startsWith(W0))throw new Error("Invalid Syntro token: must start with 'syn_'");let a=t.slice(W0.length).replace(/-/g,"+").replace(/_/g,"/"),r=atob(a),n=JSON.parse(r);if(n.v!==1)throw new Error(`Unsupported token version: ${n.v}`);return n}function Z0(t){let e=JSON.stringify(t),a=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return W0+a}function Wa(t){if(typeof process<"u"&&process.env)return process.env[t];try{let e=(0,eval)("import.meta");if(e?.env)return e.env[t]}catch{}}var SR="syntro_segment_attributes";function _R(){if(typeof window>"u")return{};try{let t=localStorage.getItem(SR);if(t){let e=JSON.parse(t);return K("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){na("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function CR(t){if(!(typeof window>"u"))try{localStorage.setItem(SR,JSON.stringify(t)),K("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){na("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function wR(t){if(!t)return{};let e={};for(let[a,r]of Object.entries(t))a.startsWith("in_segment_")&&(e[a]=r===!0);return e}function X0(){if(typeof window>"u")return{};let t={};try{let e=new URLSearchParams(window.location.search);for(let a of["utm_source","utm_medium","utm_campaign","utm_content","utm_term"]){let r=e.get(a);r&&(t[a]=r)}}catch{}try{navigator.language&&(t.browser_language=navigator.language),navigator.languages?.length&&(t.browser_languages=[...navigator.languages])}catch{}try{let e=window.innerWidth;t.device_type=e<768?"mobile":e<1024?"tablet":"desktop"}catch{}try{if(document.referrer){t.referrer=document.referrer;try{t.referrer_hostname=new URL(document.referrer).hostname}catch{}}}catch{}try{let e=navigator.userAgent;e.includes("Edg/")?t.browser="Edge":e.includes("OPR/")||e.includes("Opera")?t.browser="Opera":e.includes("Chrome/")&&!e.includes("Chromium")?t.browser="Chrome":e.includes("Safari/")&&!e.includes("Chrome")?t.browser="Safari":e.includes("Firefox/")&&(t.browser="Firefox"),e.includes("Windows")?t.os="Windows":e.includes("iPhone")||e.includes("iPad")?t.os="iOS":e.includes("Mac OS X")||e.includes("Macintosh")?t.os="macOS":e.includes("Android")?t.os="Android":e.includes("Linux")&&(t.os="Linux")}catch{}try{t.page_url=window.location.href,t.page_path=window.location.pathname,t.page_host=window.location.hostname,window.location.search&&(t.page_query=window.location.search)}catch{}return t}var bR="syntro_geo",LR="https://geo.syntrologie.com";async function K0(t){if(typeof window>"u")return{};try{let e=localStorage.getItem(bR);if(e){let a=JSON.parse(e);return K("Syntro Bootstrap","Geo: using cached data:",a),a}}catch{}try{let e=await fetch(t,{signal:AbortSignal.timeout(2e3)});if(e.ok){let a=await e.json(),r={};for(let[n,o]of Object.entries(a))typeof o=="string"&&o&&(r[n]=o);try{localStorage.setItem(bR,JSON.stringify(r))}catch{}return K("Syntro Bootstrap","Geo: fetched from worker:",r),r}}catch{}return{}}var kR={growthbook:t=>Xy({...t,autoInit:!0})};function IR(t,e){let a=kR[t];if(!a)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys(kR).join(", ")}`);return a(e)}var K4=["cdn.syntrologie.com","localhost","127.0.0.1"];function Y4(t){try{let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(console.warn("[SmartCanvas] CDN URL must use HTTPS:",t),!1):K4.some(n=>e.hostname===n)?!0:(console.warn("[SmartCanvas] CDN host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid CDN URL:",t),!1}}var Y0=class{constructor(e){B(this,"name","cdn");B(this,"url");B(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!Y4(this.url))throw new Error(`[SmartCanvas] CDN URL not allowed: ${this.url}`)}async fetch(){let e=performance.now(),a=await fetch(this.url,{credentials:"omit",cache:"default"});if(!a.ok)throw new Error(`[SmartCanvas] Failed to fetch config from CDN (${a.status})`);let r=await a.text();if(this.integrity){let l=await Q4(r),u=this.integrity.replace("sha384-","");if(l!==u)throw new Error(`[SmartCanvas] Config integrity check failed. Expected ${u}, got ${l}`)}let n=JSON.parse(r),o=performance.now()-e,i=a.headers.get("cache-control"),s=a.headers.get("age");return{config:n,meta:{source:"cdn",fetchTimeMs:o,cached:i?.includes("public")??!1,cacheAge:s?parseInt(s,10):void 0}}}};async function Q4(t){let a=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-384",a),n=new Uint8Array(r);return btoa(String.fromCharCode(...n))}function AR(t){return new Y0(t)}var J4="syntro_exp",eU="syntro_var",Q0=class{constructor(e){B(this,"name","experiments");B(this,"client");B(this,"featureKey");B(this,"manifestKey");B(this,"variantFlagPrefix");this.client=e.client,this.featureKey=e.featureKey,this.manifestKey=e.manifestKey,this.variantFlagPrefix=e.variantFlagPrefix}async fetch(){let e=performance.now();if(typeof window<"u"){let n=new URLSearchParams(window.location.search),o=n.get(J4),i=n.get(eU);if(o&&i!==null&&this.client.setForcedVariations){let s=parseInt(i,10);Number.isNaN(s)||(console.log(`[SmartCanvas] Preview mode: forcing "${o}" to variation ${s}`),this.client.setForcedVariations({[o]:s}))}}if(this.manifestKey||this.variantFlagPrefix||this.client.getAllFeatures){let n=this.fetchMultiFlag();if(n){let o=performance.now()-e;return{config:n,meta:{source:"experiments",fetchTimeMs:o,cached:!0}}}}if(!this.featureKey)throw new Error("[SmartCanvas] No featureKey configured and no variant flags found. Ensure at least one config feature flag exists in your experiment platform.");let a=this.client.getFeatureValue?.(this.featureKey,null);if(!a||typeof a!="object")throw new Error(`[SmartCanvas] Feature "${this.featureKey}" not found or invalid. Ensure the feature is configured in your experiment platform.`);let r=performance.now()-e;return{config:a,meta:{source:"experiments",fetchTimeMs:r,cached:!0}}}fetchMultiFlag(){let e=this.getVariantFlagKeys();return!e||e.length===0?null:Zf(this.client,e)}getVariantFlagKeys(){if(this.manifestKey){let e=this.client.getFeatureValue?.(this.manifestKey,null);if(e&&typeof e=="object"){let a=e.variant_flags;if(a&&a.length>0)return a}}if(this.client.getAllFeatures){let e=this.client.getAllFeatures();return this.variantFlagPrefix?Object.keys(e).filter(a=>a.startsWith(this.variantFlagPrefix)):Object.keys(e)}return[]}};function ER(t){return new Q0(t)}var tU="https://cdn.syntrologie.com/configs",TR={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return AR({baseUrl:t.baseUrl??tU,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return ER({featureKey:t.featureKey})}};function RR(t,e={}){let a=TR[t];if(!a)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys(TR).join(", ")}`);return a(e)}var MR={posthog:t=>$b(t),noop:()=>ax()};function OR(t,e){let a=MR[t];if(!a)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(MR).join(", ")}`);return a(e)}async function DR(t){ay(),K("Syntro Bootstrap","====== INIT ======"),K("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=Yf();if(console.log(`[DIAG] Mode detection: sdkMode=${e}`),console.log("[DIAG] editorSource:",Su()),console.log("[DIAG] editorConf:",Kf()),K("Syntro Bootstrap","SDK mode:",e??"normal"),!e&&typeof window<"u"){let E=!!window.__SYNTRO_EDITOR_PARAMS__,R=!!window.__SYNTRO_AUDIT_LEGEND__,M=!!window.__SYNTRO_REVIEW_DATA__;if(E||R||M){let F=[E&&"__SYNTRO_EDITOR_PARAMS__",R&&"__SYNTRO_AUDIT_LEGEND__",M&&"__SYNTRO_REVIEW_DATA__"].filter(Boolean);console.warn(`[Syntro Bootstrap] \u26A0 Mode detection returned null but mode-specific globals found: ${F.join(", ")}. This suggests URL params were lost (redirect?) but the service worker injected mode data. Check if replaceState failed or if page JS changed the URL before init().`)}}console.log(`[DIAG] Token resolution: options.token=${t.token?t.token.slice(0,15)+"...":"null"}`);let a=t.token;if(!a&&e){let R=Kf()?.syntro_token;R?.startsWith("syn_")&&(a=R,K("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${e} mode)`))}let r;if(a)if(a.startsWith("syn_"))K("Syntro Bootstrap","Token starts with syn_, decoding..."),r=qc(a),ay(r.d);else if(e)K("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${e} mode)`);else throw Xf("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),Xf("Syntro Bootstrap","Token received:",a),new Error("Invalid Syntro token: must start with 'syn_'");else if(e)K("Syntro Bootstrap",`\u2713 No token, but ${e} mode - proceeding`);else throw Xf("Syntro Bootstrap","\u274C No token provided and NOT in editor/audit/review mode!"),new Error("Syntro token is required (unless in editor, audit, or review mode)");let n=Wa("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||Wa("VITE_SYNTRO_EXPERIMENT_HOST")||r?.eh,o=Wa("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||Wa("VITE_SYNTRO_TELEMETRY_HOST")||r?.th,i=Wa("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||Wa("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,s=r?.g||Wa("NEXT_PUBLIC_SYNTRO_GEO_HOST")||Wa("VITE_SYNTRO_GEO_HOST")||LR,l=_R(),u=X0(),c={...u,...l};K("Syntro Bootstrap","Phase 1: Browser metadata:",u),K("Syntro Bootstrap","Phase 1: Cached segment attributes:",l);let d=K0(s),f,h=t.debug||t.testMode,S=Bc({debug:t.debug,history:h?new Pc(t.testMode?0:100):void 0,testMode:t.testMode});console.log("[Syntro Bootstrap] EventBus created");let x=sy({elementResolver:typeof window<"u"?(E,R)=>{let M=document.elementFromPoint(E,R);if(!M)return null;let F={tag_name:M.tagName.toLowerCase()};M.id&&(F.attr__id=M.id),M.className&&typeof M.className=="string"&&(F.classes=M.className.split(" ").filter(Boolean));for(let Z of M.attributes)Z.name.startsWith("data-")&&(F[`attr__${Z.name}`]=Z.value);return F}:void 0});x.onEvent(E=>S.publishEvent(E)),typeof window<"u"&&(setInterval(()=>x.tick(Date.now()),1e3),document.addEventListener("click",E=>{let R=[],M=E.target;for(;M&&M!==document.body;){let F={tag_name:M.tagName.toLowerCase()};for(let Z of M.attributes)(Z.name.startsWith("data-")||Z.name==="id"||Z.name==="class"||Z.name==="aria-label")&&(F[`attr__${Z.name}`]=Z.value);R.push(F),M=M.parentElement}x.enrichClickAttributes(Date.now(),R)},!0));let b=E=>{K("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let R=wR(E);if(K("Syntro Bootstrap","Segment flags from PostHog:",R),CR(R),f){let M=m?.getAll?.()??{},F={...u,...M,...R};K("Syntro Bootstrap","Updating GrowthBook with attributes:",F),f.setAttributes?.(F)}},g;if(r?.t){let E=r.t==="noop"?"noop":"posthog";g=OR(E,{apiKey:r.t,apiHost:o,enableFeatureFlags:!0,sessionRecording:!r.d,onFeatureFlagsLoaded:b,onCapture:(M,F)=>{x.ingest({kind:"posthog",event:M,properties:F,timestamp:Date.now()})},onRRWebEvent:M=>{x.ingest(M)}}),console.log(`[Syntro Bootstrap] Telemetry client created (${E}) with EventBus wiring`);let R=g;S.setPosthogCapture((M,F)=>{R.track?.(M,F)})}let m;r?.e&&(f=IR("growthbook",{clientKey:r.e,apiHost:n,attributes:c,onExperimentViewed:g?.trackExperiment?(E,R,M)=>{g.trackExperiment(E,R,M)}:void 0})),m=Ky({experiments:f,onMetricChange:(E,R)=>{K("Syntro Bootstrap",`Session metric changed: ${E} = ${R}`)}}),K("Syntro Bootstrap","SessionMetricTracker created");let y="production";e==="editor"?y="editor":e==="audit"?y="audit":Wa("NODE_ENV")==="development"&&(y="development");let v=G0({telemetry:g,sessionMetrics:m,mode:y,events:S});K("Syntro Bootstrap","Runtime created:",{version:v.version,mode:v.mode,hasContext:!!v.context,hasEvents:!!v.events,hasState:!!v.state}),K("Syntro Bootstrap","Core app executors already registered");let C=t.cdnBase||Wa("NEXT_PUBLIC_SYNTRO_CDN_BASE")||Wa("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",w=Pv({cdnBase:C,registry:v.apps,onLoadStart:E=>{K("Syntro Bootstrap",`Loading app from CDN: ${E}`)},onLoadEnd:(E,R,M)=>{R?K("Syntro Bootstrap",`App loaded successfully: ${E}`):na("Syntro Bootstrap",`Failed to load app: ${E}`,M)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:v.apps,runtime:v,version:v.version},K("Syntro Bootstrap","Global SynOS object exposed"));let _=v.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${_.length} apps in registry:`,_.map(E=>`${E.manifest.id}(${E.state})`).join(", "));for(let E of _)if(E.state==="registered")try{await v.apps.activate(E.manifest.id),console.log(`[DIAG] Activated: ${E.manifest.id} \u2192 widgets: [${v.widgets.list().join(", ")}]`)}catch(R){console.error(`[DIAG] FAILED to activate: ${E.manifest.id}`,R),na("Syntro Bootstrap",`Failed to auto-activate built-in app: ${E.manifest.id}`,R)}if(console.log(`[DIAG] Activation complete. Total widgets: [${v.widgets.list().join(", ")}]`),f?.refreshFeatures)try{await f.refreshFeatures(),K("Syntro Bootstrap","GrowthBook features loaded")}catch(E){na("Syntro Bootstrap","Failed to load GrowthBook features:",E)}let L=await d;if(f&&Object.keys(L).length>0){let E={...u,...L};K("Syntro Bootstrap","Merging geo data into GrowthBook attributes:",L),f.setAttributes?.(E)}let A;if(t.fetcher)A=t.fetcher;else if(r?.f){let E=RR(r.f,r.o??{});A=async()=>{let R=await E.fetch();return{...R.config,tiles:R.config.tiles??[]}}}else f&&(A=Cs({experiments:f}));let I=new Set,O=A?async()=>{let E=await A(),R=E.tiles?.length??0,M=E.actions?.length??0,F=E.meta?.variant_id;if((R>0||M>0)&&(F||console.warn("[Syntro] Config has content but no meta.variant_id \u2014 intervention tracking disabled")),g&&F){let W=new kc(g,F);W.trackServed(R,M),typeof window<"u"&&(window.SynOS.interventionTracker=W),v.navigation.subscribe(()=>{W.resetPage()})}console.log("[Syntro Bootstrap] Config fetched:",`tiles=${E.tiles?.length??0},`,`actions=${E.actions?.length??0},`,`theme=${E.theme?.name??"none"}`),E.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",E.actions.map((W,ce)=>`[${ce}] ${W.kind}${W.anchorId?` anchor="${W.anchorId.selector}"`:""}${W.label?` "${W.label}"`:""}`).join(", "));let Z=E,U=w.getRequiredApps(Z);return U.length>0?console.log("[Syntro Bootstrap] Required external apps:",U.join(", ")):K("Syntro Bootstrap","No external apps required (all executors are built-in)"),U.length>0&&await w.loadAppsForConfig(Z).then(async ce=>{let Xt=ce.filter(N=>N.success),it=ce.filter(N=>!N.success);Xt.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${Xt.map(N=>N.appId).join(", ")}`);let yt=it.filter(N=>!I.has(N.appId));yt.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",yt.map(N=>`${N.appId} (${N.error})`).join(", ")),yt.forEach(N=>I.add(N.appId)));for(let N of U)if(v.apps.has(N))try{await v.apps.activate(N),console.log(`[Syntro Bootstrap] App activated: ${N}`)}catch(te){console.error(`[Syntro Bootstrap] Failed to activate app: ${N}`,te)}else console.error(`[Syntro Bootstrap] App "${N}" required by config but NOT registered.`,`Available apps: [${Array.from(v.apps.list?.()??[]).join(", ")}]`)}),E}:void 0;return{canvas:await Ty({...t.canvas,fetcher:O,integrations:{experiments:f,telemetry:g},editorUrl:i,runtime:v}),runtime:v,experiments:f,telemetry:g,sessionMetrics:m,appLoader:w}}async function aU(t){try{return await DR(t)}catch(e){let a=e instanceof Error?e.message:String(e);console.warn("[Syntrologie] SDK initialization failed:",a),typeof document<"u"&&document.getElementById("syntrologie-anti-flicker")?.remove();return}}function rU(t,e={}){if(typeof window>"u")return;let a=window.SynOS?.runtime;a?.events?.publish&&a.events.publish({name:t,source:"custom",props:e})}var BR={init:aU,encodeToken:Z0,decodeToken:qc,events:{emit:rU}};typeof window<"u"&&(window.Syntro=BR);var PR="2026-04-15T02:43:01.632Z (27f62451254)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${PR}`);let t=window.SynOS,e=t?.appRegistry||hu;window.SynOS={...t,appRegistry:e,_runtimeBuild:PR,React:NR.default,ReactDOM:{...nU,createPortal:Ah.createPortal,flushSync:Ah.flushSync}},D1(e)}export{zc as ANIMATION_KEYFRAMES,xh as ActivationConfigZ,zT as AddClassZ,Ga as AnchorIdZ,N4 as AnchorStateZ,p0 as AnchorVisibleConditionZ,Hf as AppRegistry,F4 as AugmentationZ,TT as BadgePositionZ,WT as BadgeZ,P4 as BoundingBoxZ,Lu as CanvasEvents,ex as CanvasRecipeZ,Lo as ConditionZ,bh as ContextManager,x0 as CooldownActiveConditionZ,Ac as CounterDefZ,w0 as CtaButtonZ,py as DEFAULT_COOLDOWN,fy as DEFAULT_TTL,Dc as DecisionStrategyZ,y0 as DismissedConditionZ,rt as EVENT_SCHEMA_VERSION,wh as EventBus,S0 as EventCountConditionZ,$4 as EventFilterZ,Pc as EventHistory,h0 as EventOccurredConditionZ,dR as EventSourceZ,hh as ExecutorRegistry,Oc as ExternalStrategyZ,X4 as FrequencyEntryZ,b0 as FrequencyLimitConditionZ,NH as HighlightStepZ,ET as HighlightStyleZ,jT as HighlightZ,$T as InsertHtmlZ,DT as InsertPositionZ,kc as InterventionTracker,dy as MAX_VISIBLE_TOASTS,Ic as MatchOpZ,OT as ModalContentZ,XT as ModalZ,Mc as ModelStrategyZ,QT as MountWidgetZ,YT as NavigateZ,Nc as NavigationMonitor,V4 as NormalizedEventZ,cy as NotificationToastStack,M4 as PageContextZ,O4 as PageHistoryEntryZ,d0 as PageUrlConditionZ,tR as ParallelZ,RT as PlacementZ,GT as PulseZ,PR as RUNTIME_SDK_BUILD,xR as RUNTIME_VERSION,qT as RemoveClassZ,f0 as RouteConditionZ,AT as RouteFilterZ,Tc as RuleStrategyZ,Ec as RuleZ,H4 as RuntimeContextZ,yy as RuntimeProvider,eo as SDK_SCHEMA_VERSION,ry as SDK_VERSION,mR as STATIC_SLOT_STYLES,Rc as ScoreStrategyZ,FT as ScrollBehaviorZ,C0 as ScrollLogicalPositionZ,KT as ScrollToZ,bA as SelectorZ,eR as SequenceZ,D4 as SessionContextZ,v0 as SessionMetricConditionZ,Ep as SessionMetricTracker,UT as SetAttrZ,VT as SetStyleZ,HT as SetTextZ,hI as ShadowCanvasOverlay,K1 as ShadowRootProvider,xI as SmartCanvasApp,oy as SmartCanvasController,Ay as SmartCanvasElement,L8 as SmartCanvasPortal,Mt as StandardEvents,m0 as StateEqualsConditionZ,Lh as StateStore,Z4 as StoredValueZ,BR as Syntro,Uu as TileCard,h$ as TileWheel,MT as TooltipContentZ,PH as TooltipStepZ,BT as TooltipTriggerZ,ZT as TooltipZ,NT as TourStepForSchemaZ,aR as TourZ,yh as TriggerWhenZ,g0 as ViewportConditionZ,B4 as ViewportContextZ,JT as WaitZ,PT as WidgetConfigZ,Ih as WidgetRegistry,hu as appRegistry,P0 as applyStaticSlotStyles,Dv as cleanupAppContext,bv as contentRuntime,T4 as coreActionStepSchemas,c0 as createActionEngine,L0 as createAnchorResolver,Ov as createAppContext,Pv as createAppLoader,Cs as createCanvasConfigFetcher,I0 as createContextManager,A0 as createDecisionEngine,E0 as createEventAccumulator,Bc as createEventBus,Xy as createGrowthBookClient,ax as createNoopClient,C8 as createOverlayRecipeFetcher,$b as createPostHogClient,tI as createPostHogNormalizer,Ky as createSessionMetricTracker,Ty as createSmartCanvas,Z1 as createSmartCanvasController,G0 as createSmartCanvasRuntime,B0 as createStateStore,z0 as createSurfaceContainer,V0 as createSurfaces,C9 as decisionSchemas,qc as decodeToken,Z0 as encodeToken,sR as evaluate,nR as evaluateCondition,oR as evaluateRule,Sh as evaluateRuleStrategy,_h as evaluateScoreStrategy,lR as evaluateSync,xn as executorRegistry,iP as getAntiFlickerSnippet,e1 as getAppIdFromActionKind,Bv as getAppIdFromWidgetId,m4 as getExecutor,kh as getSlotAnchorId,Uc as getSlotType,q0 as getSlotZIndex,Zb as hasExecutor,up as interpolateTemplate,Jk as isCoreActionKind,hy as matchEvent,y$ as needsMigration,Cu as normalizePostHogEvent,Mv as overlaysRuntime,zu as parseVersion,H0 as playEnterAnimation,U0 as playExitAnimation,Qf as registerConfigPredicates,CI as registerSmartCanvasElement,ny as resolveConfigUri,N0 as setupAdjacentPositioning,F0 as setupInlinePositioning,wu as shouldNormalizeEvent,mN as useDecision,my as useNotifications,gy as useNotifyWatcher,xy as usePageContext,Jr as useRuntime,dp as useRuntimeContext,pN as useRuntimeEvents,hN as useRuntimeState,dN as useSessionContext,vI as useShadowCanvasConfig,ks as useShadowRoot,fN as useViewportContext,Ar as validateAction,vh as validateActions,_9 as validateActivationConfig,b9 as validateCondition,v$ as validateConfig,bj as validateEventFilter,T0 as validateEventName,kG as validateFrequencyEntry,xj as validateNormalizedEvent,R0 as validateProps,x8 as validateRecipe,j9 as validateRuntimeContext,LG as validateStoredValue,S9 as validateStrategy,$0 as widgetRegistry};
504
504
  /*! Bundled license information:
505
505
 
506
506
  react/cjs/react.production.js: