@syntrologie/runtime-sdk 2.4.0 → 2.4.1

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.
@@ -110,7 +110,7 @@ Error generating stack: `+i.message+`
110
110
  s.textContent = '.${e} { ${n} }';
111
111
  document.head.appendChild(s);
112
112
  document.documentElement.className += ' ${e}';
113
- })();`}function Ld(t,e,n="first-match"){for(let i of e){let r=t.getFeatureValue?.(i,null);if(!r||typeof r!="object")continue;let a=r,o=a.tiles&&a.tiles.length>0,s=a.actions&&a.actions.length>0;if(o||s)return{tiles:a.tiles??[],actions:a.actions??[],fetchedAt:a.fetchedAt??new Date().toISOString(),...a.schemaVersion&&{schemaVersion:a.schemaVersion},...a.configVersion&&{configVersion:a.configVersion},...a.canvasTitle&&{canvasTitle:a.canvasTitle},...a.theme&&{theme:a.theme},...a.launcher&&{launcher:a.launcher}}}return null}var cm=!1;function Mw(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function um(t){if(Mw()){cm=!0;return}cm=t??!1}function kM(){return Mw()?!0:cm}function G(t,e,n){kM()&&(n!==void 0?console.log(`[${t}]`,e,n):console.log(`[${t}]`,e))}function cn(t,e,n){n!==void 0?console.warn(`[${t}]`,e,n):console.warn(`[${t}]`,e)}function Hd(t,e,n){n!==void 0?console.error(`[${t}]`,e,n):console.error(`[${t}]`,e)}var dm="2.4.0";var Nr="2.0";var RM=["api.syntrologie.com","cdn.syntrologie.com","localhost","127.0.0.1"];function OM(t){try{let e=new URL(t),n=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!n?(console.warn("[SmartCanvas] Config URI must use HTTPS:",t),!1):RM.some(r=>e.hostname===r)?!0:(console.warn("[SmartCanvas] Config URI host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid config URI:",t),!1}}function MM(t){if(typeof window>"u")return!1;try{return new URL(t).origin===window.location.origin}catch{return!1}}var Nw="syntro_config_cache",NM=1440*60*1e3;function Dw(){try{return typeof localStorage<"u"&&localStorage!==null}catch{return!1}}function DM(t,e){if(Dw())try{let n={config:t,timestamp:Date.now(),sdkVersion:e};localStorage.setItem(Nw,JSON.stringify(n))}catch{}}function LM(t){if(!Dw())return null;try{let e=localStorage.getItem(Nw);if(!e)return null;let n=JSON.parse(e);return!n.config||typeof n.timestamp!="number"||!n.sdkVersion||n.sdkVersion!==t||Date.now()-n.timestamp>NM?null:n.config}catch{return null}}var fm=({configUri:t,experiments:e,featureKey:n="smart-canvas-config-uri"})=>{if(t)return t;let i=e?.getFeatureValue?.(n,null);if(i)return i};function HM(t,e,n){if(e){let i=t.getFeatureValue?.(e,null);if(i&&typeof i=="object"){let r=i.variant_flags;if(r&&r.length>0)return r}}if(n&&t.getAllFeatures){let i=t.getAllFeatures();return Object.keys(i).filter(r=>r.startsWith(n))}return[]}var es=({configUri:t,experiments:e,featureKey:n,credentials:i,configFeatureKey:r="smart-canvas-config",manifestKey:a,variantFlagPrefix:o,sdkVersion:s})=>async()=>{if(e&&r){let u=e.getFeatureValue?.(r,null);if(u&&typeof u=="object")return G("SmartCanvas Config","Resolved config directly from feature flag",u),u}if(e&&(a||o)){let u=HM(e,a,o);if(u.length>0){let f=Ld(e,u);if(f)return G("SmartCanvas Config","Resolved config from variant flags",f),f}}let l=fm({configUri:t,experiments:e,featureKey:n});if(!l)return G("SmartCanvas Config","No config available \u2014 returning empty config"),{tiles:[],actions:[],fetchedAt:new Date().toISOString()};if(!OM(l))throw new Error(`SmartCanvas: config URI not allowed: ${l}`);let c=i??(MM(l)?"include":"omit");try{let u=await fetch(l,{credentials:c,headers:{"X-SDK-Version":dm,"X-SDK-Schema-Version":Nr}});if(!u.ok)throw new Error(`SmartCanvas: failed to fetch config (${u.status})`);let f=await u.json();return G("SmartCanvas Config","Fetched config from URI",f),s&&DM(f,s),f}catch(u){if(s){let f=LM(s);if(f)return G("SmartCanvas Config","Serving config from offline cache"),f}throw u}};var IM=["cdn.syntrologie.com","api.syntrologie.com","dev-api.syntrologie.com","localhost","127.0.0.1",".syntrologie.com"];function Lw(t){if(typeof window>"u")return null;let n=new URLSearchParams(window.location.search).get(t);if(!n)return null;try{let i=n.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(i))}catch(i){return cn("Syntro Runtime",`Failed to decode ${t}:`,i),null}}var ts,ns;function Dr(){if(ts==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.token)ts={token:t.token,api_base:t.apiBase||""},console.log(`[DIAG] getEditorSource: from __SYNTRO_EDITOR_PARAMS__ (token=${ts.token.slice(0,15)}...)`);else{let e=Lw("editor_source");e&&(ts=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 ts??null}function Oa(){if(ns==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.mode)ns={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=${ns.mode})`);else{let e=Lw("editor_conf");e&&(ns=e),console.log(`[DIAG] getEditorConf: from URL param \u2192 ${e?`mode=${e.mode}`:"NULL"}`)}}return ns??null}function zM(t){G("Syntro Runtime","Validating editor URL:",t);try{if(t.startsWith("/"))return G("Syntro Runtime","\u2713 Relative URL allowed (same-origin):",t),!0;let e=new URL(t),n=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!n?(cn("Syntro Runtime","\u274C Editor URL must use HTTPS:",t),!1):IM.some(r=>r.startsWith(".")?e.hostname.endsWith(r)||e.hostname===r.slice(1):e.hostname===r)?(G("Syntro Runtime","\u2713 Editor URL validated"),!0):(cn("Syntro Runtime","\u274C Editor URL host not in allowlist:",e.hostname),!1)}catch(e){return cn("Syntro Runtime",`\u274C Invalid editor URL: ${t}`,e),!1}}var Hw=()=>{let t=Oa();return!Dr()?.token||!t?null:t.mode==="editor"||t.mode==="audit"||t.mode==="review"?t.mode:null};function BM(){return Dr()?.token??null}function $M(){return Dr()?.api_base??null}var ql=null,Iw=async t=>{if(G("Syntro Runtime","====== LOAD EDITOR SDK ======"),typeof window>"u"){G("Syntro Runtime","Not in browser - skipping editor SDK load");return}if(window.SyntroEditor){G("Syntro Runtime","Editor SDK already loaded (window.SyntroEditor exists)");return}if(ql)return G("Syntro Runtime","Editor SDK load already in progress, waiting..."),ql;let e=typeof t=="string"?{editorUrl:t}:t??{};if(e.editorUrl==="skip"){G("Syntro Runtime",'editorUrl="skip" \u2014 deferring to caller'),G("Syntro Runtime","================================");return}let n=$M(),r=(n?`${n}/api/editor/sdk/editor-sdk.js`:null)||e.editorUrl;if(!r){cn("Syntro Runtime","\u274C No editor SDK URL available (no api_base, no editorUrl option)"),G("Syntro Runtime","================================");return}let a=BM();if(!a){cn("Syntro Runtime","\u274C No token found in editor_source."),G("Syntro Runtime","================================");return}let o=`${r}?token=${encodeURIComponent(a)}`;if(G("Syntro Runtime","Editor URL:",o),G("Syntro Runtime","Options:",{hasIntegrity:!!e.integrity,hasEditorUrl:!!r,hasApiBase:!!n,tokenPrefix:`${a.slice(0,10)}...`}),!zM(r)){console.error("[Syntro Runtime] \u274C BLOCKED: Editor from untrusted URL:",r),G("Syntro Runtime","================================");return}return G("Syntro Runtime","\u2713 URL validated, injecting script tag..."),ql=new Promise((s,l)=>{let c=document.createElement("script");c.src=o,c.async=!0,e.integrity&&(c.integrity=e.integrity,c.crossOrigin="anonymous",G("Syntro Runtime","SRI integrity check enabled")),c.onload=()=>{G("Syntro Runtime","\u2713 Editor SDK script loaded successfully"),G("Syntro Runtime","================================"),s()},c.onerror=u=>{console.error("[Syntro Runtime] \u274C Failed to load Editor SDK:",u),console.error("[Syntro Runtime] URL attempted:",o),G("Syntro Runtime","================================"),ql=null,l(u)},document.head.appendChild(c),G("Syntro Runtime","Script tag appended to <head>")}),ql};function Pl(t,e){for(let n of t){let i=n.props;if(!i)continue;let r=i.scope;if(!r?.events)continue;let a=i.actions;if(!a)continue;let o=new Set;for(let u of a)if(u.showWhen?.type==="rules")for(let f of u.showWhen.rules)for(let h of f.conditions)h.type==="event_count"&&h.key&&o.add(h.key);if(o.size===0)continue;let{events:s,urlContains:l,props:c}=r;for(let u of o)e.register(u,f=>{if(!s.includes(f.name)||l&&!String(f.props?.pathname??"").includes(l))return!1;if(c){for(let[h,g]of Object.entries(c))if(f.props?.[h]!==g)return!1}return!0})}}var ii=null;function Bw(t){ii&&ii!==t?t.appendChild(ii):ii=t;let e=t.getRootNode();e instanceof ShadowRoot&&FM(e)}function $w(){return ii||(ii=document.createElement("div"),ii.id="syntro-overlays",Object.assign(ii.style,{position:"fixed",inset:"0",zIndex:"2147483647",pointerEvents:"none"}),document.body.appendChild(ii)),ii}var zw=!1;function FM(t){if(zw)return;let e=`
113
+ })();`}function Ld(t,e,n="first-match"){for(let i of e){let r=t.getFeatureValue?.(i,null);if(!r||typeof r!="object")continue;let a=r,o=a.tiles&&a.tiles.length>0,s=a.actions&&a.actions.length>0;if(o||s)return{tiles:a.tiles??[],actions:a.actions??[],fetchedAt:a.fetchedAt??new Date().toISOString(),...a.schemaVersion&&{schemaVersion:a.schemaVersion},...a.configVersion&&{configVersion:a.configVersion},...a.canvasTitle&&{canvasTitle:a.canvasTitle},...a.theme&&{theme:a.theme},...a.launcher&&{launcher:a.launcher}}}return null}var cm=!1;function Mw(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function um(t){if(Mw()){cm=!0;return}cm=t??!1}function kM(){return Mw()?!0:cm}function G(t,e,n){kM()&&(n!==void 0?console.log(`[${t}]`,e,n):console.log(`[${t}]`,e))}function cn(t,e,n){n!==void 0?console.warn(`[${t}]`,e,n):console.warn(`[${t}]`,e)}function Hd(t,e,n){n!==void 0?console.error(`[${t}]`,e,n):console.error(`[${t}]`,e)}var dm="2.4.1";var Nr="2.0";var RM=["api.syntrologie.com","cdn.syntrologie.com","localhost","127.0.0.1"];function OM(t){try{let e=new URL(t),n=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!n?(console.warn("[SmartCanvas] Config URI must use HTTPS:",t),!1):RM.some(r=>e.hostname===r)?!0:(console.warn("[SmartCanvas] Config URI host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid config URI:",t),!1}}function MM(t){if(typeof window>"u")return!1;try{return new URL(t).origin===window.location.origin}catch{return!1}}var Nw="syntro_config_cache",NM=1440*60*1e3;function Dw(){try{return typeof localStorage<"u"&&localStorage!==null}catch{return!1}}function DM(t,e){if(Dw())try{let n={config:t,timestamp:Date.now(),sdkVersion:e};localStorage.setItem(Nw,JSON.stringify(n))}catch{}}function LM(t){if(!Dw())return null;try{let e=localStorage.getItem(Nw);if(!e)return null;let n=JSON.parse(e);return!n.config||typeof n.timestamp!="number"||!n.sdkVersion||n.sdkVersion!==t||Date.now()-n.timestamp>NM?null:n.config}catch{return null}}var fm=({configUri:t,experiments:e,featureKey:n="smart-canvas-config-uri"})=>{if(t)return t;let i=e?.getFeatureValue?.(n,null);if(i)return i};function HM(t,e,n){if(e){let i=t.getFeatureValue?.(e,null);if(i&&typeof i=="object"){let r=i.variant_flags;if(r&&r.length>0)return r}}if(n&&t.getAllFeatures){let i=t.getAllFeatures();return Object.keys(i).filter(r=>r.startsWith(n))}return[]}var es=({configUri:t,experiments:e,featureKey:n,credentials:i,configFeatureKey:r="smart-canvas-config",manifestKey:a,variantFlagPrefix:o,sdkVersion:s})=>async()=>{if(e&&r){let u=e.getFeatureValue?.(r,null);if(u&&typeof u=="object")return G("SmartCanvas Config","Resolved config directly from feature flag",u),u}if(e&&(a||o)){let u=HM(e,a,o);if(u.length>0){let f=Ld(e,u);if(f)return G("SmartCanvas Config","Resolved config from variant flags",f),f}}let l=fm({configUri:t,experiments:e,featureKey:n});if(!l)return G("SmartCanvas Config","No config available \u2014 returning empty config"),{tiles:[],actions:[],fetchedAt:new Date().toISOString()};if(!OM(l))throw new Error(`SmartCanvas: config URI not allowed: ${l}`);let c=i??(MM(l)?"include":"omit");try{let u=await fetch(l,{credentials:c,headers:{"X-SDK-Version":dm,"X-SDK-Schema-Version":Nr}});if(!u.ok)throw new Error(`SmartCanvas: failed to fetch config (${u.status})`);let f=await u.json();return G("SmartCanvas Config","Fetched config from URI",f),s&&DM(f,s),f}catch(u){if(s){let f=LM(s);if(f)return G("SmartCanvas Config","Serving config from offline cache"),f}throw u}};var IM=["cdn.syntrologie.com","api.syntrologie.com","dev-api.syntrologie.com","localhost","127.0.0.1",".syntrologie.com"];function Lw(t){if(typeof window>"u")return null;let n=new URLSearchParams(window.location.search).get(t);if(!n)return null;try{let i=n.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(i))}catch(i){return cn("Syntro Runtime",`Failed to decode ${t}:`,i),null}}var ts,ns;function Dr(){if(ts==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.token)ts={token:t.token,api_base:t.apiBase||""},console.log(`[DIAG] getEditorSource: from __SYNTRO_EDITOR_PARAMS__ (token=${ts.token.slice(0,15)}...)`);else{let e=Lw("editor_source");e&&(ts=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 ts??null}function Oa(){if(ns==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.mode)ns={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=${ns.mode})`);else{let e=Lw("editor_conf");e&&(ns=e),console.log(`[DIAG] getEditorConf: from URL param \u2192 ${e?`mode=${e.mode}`:"NULL"}`)}}return ns??null}function zM(t){G("Syntro Runtime","Validating editor URL:",t);try{if(t.startsWith("/"))return G("Syntro Runtime","\u2713 Relative URL allowed (same-origin):",t),!0;let e=new URL(t),n=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!n?(cn("Syntro Runtime","\u274C Editor URL must use HTTPS:",t),!1):IM.some(r=>r.startsWith(".")?e.hostname.endsWith(r)||e.hostname===r.slice(1):e.hostname===r)?(G("Syntro Runtime","\u2713 Editor URL validated"),!0):(cn("Syntro Runtime","\u274C Editor URL host not in allowlist:",e.hostname),!1)}catch(e){return cn("Syntro Runtime",`\u274C Invalid editor URL: ${t}`,e),!1}}var Hw=()=>{let t=Oa();return!Dr()?.token||!t?null:t.mode==="editor"||t.mode==="audit"||t.mode==="review"?t.mode:null};function BM(){return Dr()?.token??null}function $M(){return Dr()?.api_base??null}var ql=null,Iw=async t=>{if(G("Syntro Runtime","====== LOAD EDITOR SDK ======"),typeof window>"u"){G("Syntro Runtime","Not in browser - skipping editor SDK load");return}if(window.SyntroEditor){G("Syntro Runtime","Editor SDK already loaded (window.SyntroEditor exists)");return}if(ql)return G("Syntro Runtime","Editor SDK load already in progress, waiting..."),ql;let e=typeof t=="string"?{editorUrl:t}:t??{};if(e.editorUrl==="skip"){G("Syntro Runtime",'editorUrl="skip" \u2014 deferring to caller'),G("Syntro Runtime","================================");return}let n=$M(),r=(n?`${n}/api/editor/sdk/editor-sdk.js`:null)||e.editorUrl;if(!r){cn("Syntro Runtime","\u274C No editor SDK URL available (no api_base, no editorUrl option)"),G("Syntro Runtime","================================");return}let a=BM();if(!a){cn("Syntro Runtime","\u274C No token found in editor_source."),G("Syntro Runtime","================================");return}let o=`${r}?token=${encodeURIComponent(a)}`;if(G("Syntro Runtime","Editor URL:",o),G("Syntro Runtime","Options:",{hasIntegrity:!!e.integrity,hasEditorUrl:!!r,hasApiBase:!!n,tokenPrefix:`${a.slice(0,10)}...`}),!zM(r)){console.error("[Syntro Runtime] \u274C BLOCKED: Editor from untrusted URL:",r),G("Syntro Runtime","================================");return}return G("Syntro Runtime","\u2713 URL validated, injecting script tag..."),ql=new Promise((s,l)=>{let c=document.createElement("script");c.src=o,c.async=!0,e.integrity&&(c.integrity=e.integrity,c.crossOrigin="anonymous",G("Syntro Runtime","SRI integrity check enabled")),c.onload=()=>{G("Syntro Runtime","\u2713 Editor SDK script loaded successfully"),G("Syntro Runtime","================================"),s()},c.onerror=u=>{console.error("[Syntro Runtime] \u274C Failed to load Editor SDK:",u),console.error("[Syntro Runtime] URL attempted:",o),G("Syntro Runtime","================================"),ql=null,l(u)},document.head.appendChild(c),G("Syntro Runtime","Script tag appended to <head>")}),ql};function Pl(t,e){for(let n of t){let i=n.props;if(!i)continue;let r=i.scope;if(!r?.events)continue;let a=i.actions;if(!a)continue;let o=new Set;for(let u of a)if(u.showWhen?.type==="rules")for(let f of u.showWhen.rules)for(let h of f.conditions)h.type==="event_count"&&h.key&&o.add(h.key);if(o.size===0)continue;let{events:s,urlContains:l,props:c}=r;for(let u of o)e.register(u,f=>{if(!s.includes(f.name)||l&&!String(f.props?.pathname??"").includes(l))return!1;if(c){for(let[h,g]of Object.entries(c))if(f.props?.[h]!==g)return!1}return!0})}}var ii=null;function Bw(t){ii&&ii!==t?t.appendChild(ii):ii=t;let e=t.getRootNode();e instanceof ShadowRoot&&FM(e)}function $w(){return ii||(ii=document.createElement("div"),ii.id="syntro-overlays",Object.assign(ii.style,{position:"fixed",inset:"0",zIndex:"2147483647",pointerEvents:"none"}),document.body.appendChild(ii)),ii}var zw=!1;function FM(t){if(zw)return;let e=`
114
114
  :host {
115
115
  --syntro-surface: #0f1318;
116
116
  --syntro-fg: #cbd0d7;
@@ -426,7 +426,7 @@ Error generating stack: `+i.message+`
426
426
  .syntro-badge-ping { animation: syntro-badge-ping 1.5s cubic-bezier(0,0,0.2,1) infinite; }
427
427
  .syntro-badge-glow { animation: syntro-badge-glow 2s ease-in-out infinite; }
428
428
  .syntro-badge-bounce { animation: syntro-badge-bounce 2s ease-in-out infinite; }
429
- `;function pN(t){if(t.querySelector(`#${Gw}`))return;let e=document.createElement("style");e.id=Gw,e.textContent=fN,t.appendChild(e)}var hN={position:"right",baseWidth:"clamp(320px, 16.666vw, 420px)",expandedWidth:"40vw",zIndex:2147483600,backdropBlur:"18px",mode:"dark",colorPrimary:ne[3],colorBackground:E[1],colorText:dt.primary,colorTextSecondary:dt.secondary,borderRadius:"12px",glassBackground:oe(E[1],.6),glassBlur:"blur(24px)",glassSaturate:"saturate(1.2)"};function Zw({isOpen:t,onToggle:e,telemetry:n,launcherLabel:i="Adaptives",launcherAnimate:r=!1,launcherAnimationStyle:a="pulse",notificationCount:o,footerSlot:s,tiles:l,isLoading:c,error:u,canvasTitle:f,displayMode:h="standard",theme:g}){let[_,b]=(0,qt.useState)(!1),[w,d]=(0,qt.useState)(null),p=(0,qt.useRef)(null),m=Ii(),{shadowRoot:v,portalRoot:S}=zd(),{notifications:T,dismiss:A}=Sm(m?.events??null,l);xm(m,l,m?.apps);let k=(0,qt.useCallback)(L=>{m&&m.events.publish(_e.NOTIFICATION_CLICKED,{notificationId:L.id,tileId:L.tileId,itemId:L.itemId}),t||e(),m&&L.tileId&&m.events.publish(_e.NOTIFICATION_DEEP_LINK,{tileId:L.tileId,itemId:L.itemId}),A(L.id)},[m,t,e,A]),C={...hN,...g};(0,qt.useEffect)(()=>{t&&l.forEach(L=>{if(n?.trackRectangleViewed(L.id,"overlay"),m){let de=Gl.tileViewed(L.id,"overlay");m.events.publish(de.name,de.props,de.source)}})},[n,m,t,l]),(0,qt.useEffect)(()=>{b(!0),pN(v)},[v]);let x=(0,qt.useCallback)(()=>{let L=!t;if(L?n?.trackCanvasOpened("overlay"):n?.trackCanvasClosed("overlay"),m){let de=L?Gl.canvasOpened("overlay"):Gl.canvasClosed("overlay");m.events.publish(de.name,de.props,de.source)}e()},[t,n,m,e]),M=(0,qt.useCallback)(L=>{let de=L.currentTarget.getBoundingClientRect();p.current={startX:L.clientX,startY:L.clientY,startElX:de.left,startElY:de.top,dragged:!1},L.currentTarget.setPointerCapture(L.pointerId)},[]),z=(0,qt.useCallback)(L=>{let de=p.current;if(!de)return;let fn=L.clientX-de.startX,We=L.clientY-de.startY;(Math.abs(fn)>5||Math.abs(We)>5)&&(de.dragged=!0),de.dragged&&d({x:de.startElX+fn,y:de.startElY+We})},[]),U=(0,qt.useCallback)(L=>{let de=p.current;p.current=null,de&&!de.dragged&&x()},[x]),P=h==="focused",Z=C.position==="right",X={display:"flex",flexDirection:"column",width:P?C.expandedWidth:C.baseWidth,minWidth:"320px",height:"100%",maxHeight:"100%",pointerEvents:"auto",opacity:t?1:0,transition:t?"transform 340ms cubic-bezier(0.16, 1, 0.3, 1), opacity 280ms ease-out":"transform 280ms cubic-bezier(0.4, 0, 0.2, 1), opacity 200ms ease-in",color:C.colorText||dt.primary,background:P?C.glassBackground??oe(E[1],.6):"transparent",backdropFilter:P?`${C.glassBlur??"blur(24px)"} ${C.glassSaturate??"saturate(1.2)"}`:"blur(6px)",WebkitBackdropFilter:P?`${C.glassBlur??"blur(24px)"} ${C.glassSaturate??"saturate(1.2)"}`:"blur(6px)",...P?{}:{maskImage:Z?"linear-gradient(to right, transparent, black 6%)":"linear-gradient(to left, transparent, black 6%)",WebkitMaskImage:Z?"linear-gradient(to right, transparent, black 6%)":"linear-gradient(to left, transparent, black 6%)"},border:"none",borderRadius:"0",boxShadow:"none",transform:t?"translateX(0)":Z?"translateX(120%)":"translateX(-120%)"},W={position:"absolute",inset:0,display:"flex",flexDirection:Z?"row-reverse":"row",alignItems:"stretch",pointerEvents:"none",padding:"0"},D=(0,pe.jsx)("div",{"data-shadow-canvas-id":"overlay-root",style:{position:"fixed",inset:0,pointerEvents:t?"auto":"none",zIndex:C.zIndex},children:(0,pe.jsxs)("div",{style:W,children:[(0,pe.jsxs)("div",{"data-shadow-canvas-id":"overlay-container",style:X,children:[P&&f&&(0,pe.jsx)("header",{style:{color:"white",padding:"1.5rem 1.5rem 0"},children:(0,pe.jsx)("p",{style:{margin:0,fontSize:"0.7rem",textTransform:"uppercase",letterSpacing:"0.5em",color:dt.tertiary},children:f})}),(0,pe.jsx)("div",{style:{flex:1,overflowY:"auto",padding:P?"0":"1rem"},children:c?(0,pe.jsx)("div",{style:{color:dt.primary,padding:P?"1rem":"0"},children:"Loading..."}):u?(0,pe.jsxs)("div",{style:{color:Be[8],padding:P?"1rem":"0"},children:["Failed to load: ",u]}):P?l.length>0?(0,pe.jsx)(Zl,{config:l[0],surface:"overlay",telemetry:n,style:{width:"100%",height:"100%"}}):null:(0,pe.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",width:"100%"},children:l.map(L=>(0,pe.jsx)(Zl,{config:L,surface:"overlay",telemetry:n,style:{width:"100%"}},L.id))})}),s]}),(0,pe.jsx)("div",{onClick:x,style:{flex:"1 1 auto",pointerEvents:t?"auto":"none",cursor:"default"}})]})});return _?(0,pe.jsxs)(pe.Fragment,{children:[(0,Am.createPortal)((0,pe.jsxs)("div",{"data-shadow-canvas-id":"overlay-launcher",style:{position:"fixed",inset:0,pointerEvents:"none",zIndex:C.zIndex+47},children:[(0,pe.jsx)(mm,{notifications:T,onDismiss:A,onClickNotification:k,position:C.position}),(0,pe.jsxs)("button",{type:"button","aria-label":"Toggle shadow canvas",className:r&&!t?"syntro-launcher-animate":void 0,style:{position:"fixed",...w?{top:w.y,left:w.x}:{bottom:"2.5rem",right:Z?"2.5rem":void 0,left:Z?void 0:"2.5rem"},pointerEvents:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:"56px",height:"56px",borderRadius:"9999px",color:Il.primary.icon,boxShadow:`0 8px 32px ${oe(E[0],.6)}`,transition:p.current?"none":"transform 0.2s ease, opacity 0.3s ease, background-color 0.2s ease",outline:"none",padding:0,border:"none",backgroundColor:Il.primary.backgroundDefault,cursor:p.current?.dragged?"grabbing":"pointer",touchAction:"none"},onPointerDown:M,onPointerMove:z,onPointerUp:U,onMouseEnter:L=>{p.current?.dragged||(L.currentTarget.style.backgroundColor=Il.primary.backgroundHover)},onMouseLeave:L=>{p.current?.dragged||(L.currentTarget.style.backgroundColor=Il.primary.backgroundDefault)},children:[(0,pe.jsx)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",style:{transition:"transform 200ms ease"},children:t?(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)("path",{d:"M18 6L6 18"}),(0,pe.jsx)("path",{d:"M6 6l12 12"})]}):(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)("path",{d:"M12 3l1.912 5.813a2 2 0 0 0 1.275 1.275L21 12l-5.813 1.912a2 2 0 0 0-1.275 1.275L12 21l-1.912-5.813a2 2 0 0 0-1.275-1.275L3 12l5.813-1.912a2 2 0 0 0 1.275-1.275L12 3Z"}),(0,pe.jsx)("path",{d:"M5 3v4"}),(0,pe.jsx)("path",{d:"M3 5h4"}),(0,pe.jsx)("path",{d:"M19 17v4"}),(0,pe.jsx)("path",{d:"M17 19h4"})]})}),!t&&T.length>0&&(0,pe.jsxs)("div",{style:{position:"absolute",top:-2,right:-2,pointerEvents:"none"},children:[(0,pe.jsx)("span",{className:"syntro-badge-ping",style:{position:"absolute",inset:0,borderRadius:"9999px",background:oe(ne[4],.4)}}),(0,pe.jsx)("span",{className:"syntro-badge-glow",style:{position:"absolute",inset:-4,borderRadius:"9999px"}}),(0,pe.jsx)("span",{className:"syntro-badge-bounce",style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,borderRadius:"9999px",background:ne[4],color:Ze.white,fontSize:11,fontWeight:700},children:T.length>99?"99+":T.length})]})]})]}),S),t?(0,Am.createPortal)(D,S):null]}):null}var Lr=ee(nt(),1);var gN=t=>[...t].sort((e,n)=>(n.priority??0)-(e.priority??0));function Yw({fetcher:t,pollIntervalMs:e=3e4,experiments:n,runtime:i}){let[r,a]=(0,Lr.useState)({tiles:[],actions:[],isLoading:!0}),o=(0,Lr.useCallback)(async()=>{try{a(c=>({...c,isLoading:!0,error:void 0}));let s=await t();G("SmartCanvas Config","Raw config response",s);let l=s.tiles||[];i?(l=await i.filterTiles(l),n&&(l=l.filter(c=>n.shouldRenderRectangle(c)))):n&&(l=l.filter(c=>n.shouldRenderRectangle(c))),G("SmartCanvas Config",`Tile count after filtering: ${l.length}`),a({tiles:gN(l),actions:s.actions||[],isLoading:!1,fetchedAt:s.fetchedAt,canvasTitle:s.canvasTitle,configVersion:s.configVersion,theme:s.theme,launcher:s.launcher})}catch(s){let l=s instanceof Error?s.message:"Unknown error";console.error("[SmartCanvas Config] Failed to fetch/filter config:",l,s),a(c=>({...c,isLoading:!1,error:l}))}},[n,t,i]);return(0,Lr.useEffect)(()=>{if(o(),!e)return;let s=setInterval(o,e);return()=>clearInterval(s)},[o,e]),(0,Lr.useMemo)(()=>r,[r])}var Yl=ee(qe(),1);function Kw({controller:t,fetcher:e,configUri:n,configUriFeatureKey:i="smart-canvas-config-uri",configFeatureKey:r="smart-canvas-config",fetchCredentials:a="include",pollIntervalMs:o,experiments:s,telemetry:l,runtime:c,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h="smart-canvas-overlay-uri",overlayFetchCredentials:g="include",footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p}){return c?(0,Yl.jsx)(Em,{runtime:c,children:(0,Yl.jsx)(Ww,{controller:t,fetcher:e,configUri:n,configUriFeatureKey:i,configFeatureKey:r,fetchCredentials:a,pollIntervalMs:o,experiments:s,telemetry:l,runtime:c,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h,overlayFetchCredentials:g,footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p})}):(0,Yl.jsx)(Ww,{controller:t,fetcher:e,configUri:n,configUriFeatureKey:i,configFeatureKey:r,fetchCredentials:a,pollIntervalMs:o,experiments:s,telemetry:l,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h,overlayFetchCredentials:g,footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p})}function Ww({controller:t,fetcher:e,configUri:n,configUriFeatureKey:i="smart-canvas-config-uri",configFeatureKey:r="smart-canvas-config",fetchCredentials:a="include",pollIntervalMs:o,experiments:s,telemetry:l,runtime:c,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h="smart-canvas-overlay-uri",overlayFetchCredentials:g="include",footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p}){let[m,v]=(0,Nt.useState)(t.getState().open),S=Cm(),[T,A]=(0,Nt.useState)(()=>typeof window<"u"?window.location.pathname:"/"),k=S?.url?new URL(S.url).pathname:T;(0,Nt.useEffect)(()=>{if(c||typeof window>"u")return;let Z=()=>A(window.location.pathname);window.addEventListener("popstate",Z);let X=history.pushState,W=history.replaceState;return history.pushState=function(...D){X.apply(this,D),queueMicrotask(Z)},history.replaceState=function(...D){W.apply(this,D),queueMicrotask(Z)},()=>{window.removeEventListener("popstate",Z),history.pushState=X,history.replaceState=W}},[c]);let C=(0,Nt.useMemo)(()=>e||es({configUri:n,experiments:s,featureKey:i,configFeatureKey:r,credentials:a}),[e,n,s,i,r,a]),x=Yw({fetcher:C,pollIntervalMs:o,experiments:s,runtime:c}),M=x.tiles.length>0&&!x.error;(0,Nt.useEffect)(()=>t.subscribe(Z=>v(Z.open)),[t]),(0,Nt.useEffect)(()=>{!x.isLoading&&!M&&t.getState().open&&t.setOpen(!1)},[t,M,x.isLoading]);let z=(0,Nt.useRef)(p??null),U=(0,Nt.useRef)(!!p);(0,Nt.useEffect)(()=>{if(!c?.actions)return;if(U.current){x.actions.length>0&&(U.current=!1);return}let Z=!1;return(async()=>{if(z.current){console.log("[SmartCanvasApp] Reverting previous action batch before re-apply");try{await z.current.revertAll()}catch(W){console.error("[SmartCanvasApp] Failed to revert actions:",W)}z.current=null}if(!Z&&x.actions.length>0){console.log(`[SmartCanvasApp] Applying ${x.actions.length} action(s):`,x.actions.map((W,D)=>`[${D}] ${W.kind}${W.anchorId?` anchor="${W.anchorId}"`:""}${W.label?` "${W.label}"`:""}`).join(", "));try{let W=await c.actions.applyBatch(x.actions);Z?await W.revertAll():(z.current=W,console.log("[SmartCanvasApp] Action batch applied successfully"))}catch(W){Z||console.error("[SmartCanvasApp] Failed to apply actions:",W,`
429
+ `;function pN(t){if(t.querySelector(`#${Gw}`))return;let e=document.createElement("style");e.id=Gw,e.textContent=fN,t.appendChild(e)}var hN={position:"right",baseWidth:"clamp(320px, 16.666vw, 420px)",expandedWidth:"40vw",zIndex:2147483600,backdropBlur:"18px",mode:"dark",colorPrimary:ne[3],colorBackground:E[1],colorText:dt.primary,colorTextSecondary:dt.secondary,borderRadius:"12px",glassBackground:oe(E[1],.6),glassBlur:"blur(24px)",glassSaturate:"saturate(1.2)"};function Zw({isOpen:t,onToggle:e,telemetry:n,launcherLabel:i="Adaptives",launcherAnimate:r=!1,launcherAnimationStyle:a="pulse",notificationCount:o,footerSlot:s,tiles:l,isLoading:c,error:u,canvasTitle:f,displayMode:h="standard",theme:g}){let[_,b]=(0,qt.useState)(!1),[w,d]=(0,qt.useState)(null),p=(0,qt.useRef)(null),m=Ii(),{shadowRoot:v,portalRoot:S}=zd(),{notifications:T,dismiss:A}=Sm(m?.events??null,l);xm(m,l,m?.apps);let k=(0,qt.useCallback)(L=>{m&&m.events.publish(_e.NOTIFICATION_CLICKED,{notificationId:L.id,tileId:L.tileId,itemId:L.itemId}),t||e(),m&&L.tileId&&m.events.publish(_e.NOTIFICATION_DEEP_LINK,{tileId:L.tileId,itemId:L.itemId}),A(L.id)},[m,t,e,A]),C={...hN,...g};(0,qt.useEffect)(()=>{t&&l.forEach(L=>{if(n?.trackRectangleViewed(L.id,"overlay"),m){let de=Gl.tileViewed(L.id,"overlay");m.events.publish(de.name,de.props,de.source)}})},[n,m,t,l]),(0,qt.useEffect)(()=>{b(!0),pN(v)},[v]);let x=(0,qt.useCallback)(()=>{let L=!t;if(L?n?.trackCanvasOpened("overlay"):n?.trackCanvasClosed("overlay"),m){let de=L?Gl.canvasOpened("overlay"):Gl.canvasClosed("overlay");m.events.publish(de.name,de.props,de.source)}e()},[t,n,m,e]),M=(0,qt.useCallback)(L=>{let de=L.currentTarget.getBoundingClientRect();p.current={startX:L.clientX,startY:L.clientY,startElX:de.left,startElY:de.top,dragged:!1},L.currentTarget.setPointerCapture(L.pointerId)},[]),z=(0,qt.useCallback)(L=>{let de=p.current;if(!de)return;let fn=L.clientX-de.startX,We=L.clientY-de.startY;(Math.abs(fn)>5||Math.abs(We)>5)&&(de.dragged=!0),de.dragged&&d({x:de.startElX+fn,y:de.startElY+We})},[]),U=(0,qt.useCallback)(L=>{let de=p.current;p.current=null,de&&!de.dragged&&x()},[x]),P=h==="focused",Z=C.position==="right",X={display:"flex",flexDirection:"column",width:P?C.expandedWidth:C.baseWidth,minWidth:"320px",height:"100%",maxHeight:"100%",pointerEvents:"auto",opacity:t?1:0,transition:t?"transform 340ms cubic-bezier(0.16, 1, 0.3, 1), opacity 280ms ease-out":"transform 280ms cubic-bezier(0.4, 0, 0.2, 1), opacity 200ms ease-in",color:C.colorText||dt.primary,background:P?C.glassBackground??oe(E[1],.6):"transparent",backdropFilter:P?`${C.glassBlur??"blur(24px)"} ${C.glassSaturate??"saturate(1.2)"}`:"blur(6px)",WebkitBackdropFilter:P?`${C.glassBlur??"blur(24px)"} ${C.glassSaturate??"saturate(1.2)"}`:"blur(6px)",...P?{}:{maskImage:Z?"linear-gradient(to right, transparent, black 6%)":"linear-gradient(to left, transparent, black 6%)",WebkitMaskImage:Z?"linear-gradient(to right, transparent, black 6%)":"linear-gradient(to left, transparent, black 6%)"},border:"none",borderRadius:"0",boxShadow:"none",transform:t?"translateX(0)":Z?"translateX(120%)":"translateX(-120%)"},W={position:"absolute",inset:0,display:"flex",flexDirection:Z?"row-reverse":"row",alignItems:"stretch",pointerEvents:"none",padding:"0"},D=(0,pe.jsx)("div",{"data-shadow-canvas-id":"overlay-root",style:{position:"fixed",inset:0,pointerEvents:t?"auto":"none",zIndex:C.zIndex},children:(0,pe.jsxs)("div",{style:W,children:[(0,pe.jsxs)("div",{"data-shadow-canvas-id":"overlay-container",style:X,children:[P&&f&&(0,pe.jsx)("header",{style:{color:"white",padding:"1.5rem 1.5rem 0"},children:(0,pe.jsx)("p",{style:{margin:0,fontSize:"0.7rem",textTransform:"uppercase",letterSpacing:"0.5em",color:dt.tertiary},children:f})}),(0,pe.jsx)("div",{style:{flex:1,overflowY:"auto",padding:P?"0":"1rem"},children:c?(0,pe.jsx)("div",{style:{color:dt.primary,padding:P?"1rem":"0"},children:"Loading..."}):u?(0,pe.jsxs)("div",{style:{color:Be[8],padding:P?"1rem":"0"},children:["Failed to load: ",u]}):P?l.length>0?(0,pe.jsx)(Zl,{config:l[0],surface:"overlay",telemetry:n,style:{width:"100%",height:"100%"}}):null:(0,pe.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",width:"100%"},children:l.map(L=>(0,pe.jsx)(Zl,{config:L,surface:"overlay",telemetry:n,style:{width:"100%"}},L.id))})}),s]}),(0,pe.jsx)("div",{onClick:x,style:{flex:"1 1 auto",pointerEvents:t?"auto":"none",cursor:"default"}})]})});return _?(0,pe.jsxs)(pe.Fragment,{children:[(0,Am.createPortal)((0,pe.jsxs)("div",{"data-shadow-canvas-id":"overlay-launcher",style:{position:"fixed",inset:0,pointerEvents:"none",zIndex:C.zIndex+47},children:[(0,pe.jsx)(mm,{notifications:T,onDismiss:A,onClickNotification:k,position:C.position}),(0,pe.jsxs)("button",{type:"button","aria-label":"Toggle shadow canvas",className:r&&!t?"syntro-launcher-animate":void 0,style:{position:"fixed",...w?{top:w.y,left:w.x}:{bottom:"2.5rem",right:Z?"2.5rem":void 0,left:Z?void 0:"2.5rem"},pointerEvents:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:"56px",height:"56px",borderRadius:"9999px",color:Il.primary.icon,boxShadow:`0 8px 32px ${oe(E[0],.6)}`,transition:p.current?"none":"transform 0.2s ease, opacity 0.3s ease, background-color 0.2s ease",outline:"none",padding:0,border:"none",backgroundColor:Il.primary.backgroundDefault,cursor:p.current?.dragged?"grabbing":"pointer",touchAction:"none"},onPointerDown:M,onPointerMove:z,onPointerUp:U,onMouseEnter:L=>{p.current?.dragged||(L.currentTarget.style.backgroundColor=Il.primary.backgroundHover)},onMouseLeave:L=>{p.current?.dragged||(L.currentTarget.style.backgroundColor=Il.primary.backgroundDefault)},children:[(0,pe.jsx)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",style:{transition:"transform 200ms ease"},children:t?(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)("path",{d:"M18 6L6 18"}),(0,pe.jsx)("path",{d:"M6 6l12 12"})]}):(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)("path",{d:"M12 3l1.912 5.813a2 2 0 0 0 1.275 1.275L21 12l-5.813 1.912a2 2 0 0 0-1.275 1.275L12 21l-1.912-5.813a2 2 0 0 0-1.275-1.275L3 12l5.813-1.912a2 2 0 0 0 1.275-1.275L12 3Z"}),(0,pe.jsx)("path",{d:"M5 3v4"}),(0,pe.jsx)("path",{d:"M3 5h4"}),(0,pe.jsx)("path",{d:"M19 17v4"}),(0,pe.jsx)("path",{d:"M17 19h4"})]})}),!t&&T.length>0&&(0,pe.jsxs)("div",{style:{position:"absolute",top:-2,right:-2,pointerEvents:"none"},children:[(0,pe.jsx)("span",{className:"syntro-badge-ping",style:{position:"absolute",inset:0,borderRadius:"9999px",background:oe(ne[4],.4)}}),(0,pe.jsx)("span",{className:"syntro-badge-glow",style:{position:"absolute",inset:-4,borderRadius:"9999px"}}),(0,pe.jsx)("span",{className:"syntro-badge-bounce",style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,borderRadius:"9999px",background:ne[4],color:Ze.white,fontSize:11,fontWeight:700},children:T.length>99?"99+":T.length})]})]})]}),S),t?(0,Am.createPortal)(D,S):null]}):null}var Lr=ee(nt(),1);var gN=t=>[...t].sort((e,n)=>(n.priority??0)-(e.priority??0));function Yw({fetcher:t,pollIntervalMs:e=3e4,experiments:n,runtime:i,pathname:r}){let[a,o]=(0,Lr.useState)({tiles:[],actions:[],isLoading:!0}),s=(0,Lr.useCallback)(async()=>{try{o(u=>({...u,isLoading:!0,error:void 0}));let l=await t();G("SmartCanvas Config","Raw config response",l);let c=l.tiles||[];i?(c=await i.filterTiles(c),n&&(c=c.filter(u=>n.shouldRenderRectangle(u)))):n&&(c=c.filter(u=>n.shouldRenderRectangle(u))),G("SmartCanvas Config",`Tile count after filtering: ${c.length}`),o({tiles:gN(c),actions:l.actions||[],isLoading:!1,fetchedAt:l.fetchedAt,canvasTitle:l.canvasTitle,configVersion:l.configVersion,theme:l.theme,launcher:l.launcher})}catch(l){let c=l instanceof Error?l.message:"Unknown error";console.error("[SmartCanvas Config] Failed to fetch/filter config:",c,l),o(u=>({...u,isLoading:!1,error:c}))}},[n,t,i]);return(0,Lr.useEffect)(()=>{if(s(),!e)return;let l=setInterval(s,e);return()=>clearInterval(l)},[s,e,r]),(0,Lr.useMemo)(()=>a,[a])}var Yl=ee(qe(),1);function Kw({controller:t,fetcher:e,configUri:n,configUriFeatureKey:i="smart-canvas-config-uri",configFeatureKey:r="smart-canvas-config",fetchCredentials:a="include",pollIntervalMs:o,experiments:s,telemetry:l,runtime:c,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h="smart-canvas-overlay-uri",overlayFetchCredentials:g="include",footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p}){return c?(0,Yl.jsx)(Em,{runtime:c,children:(0,Yl.jsx)(Ww,{controller:t,fetcher:e,configUri:n,configUriFeatureKey:i,configFeatureKey:r,fetchCredentials:a,pollIntervalMs:o,experiments:s,telemetry:l,runtime:c,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h,overlayFetchCredentials:g,footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p})}):(0,Yl.jsx)(Ww,{controller:t,fetcher:e,configUri:n,configUriFeatureKey:i,configFeatureKey:r,fetchCredentials:a,pollIntervalMs:o,experiments:s,telemetry:l,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h,overlayFetchCredentials:g,footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p})}function Ww({controller:t,fetcher:e,configUri:n,configUriFeatureKey:i="smart-canvas-config-uri",configFeatureKey:r="smart-canvas-config",fetchCredentials:a="include",pollIntervalMs:o,experiments:s,telemetry:l,runtime:c,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h="smart-canvas-overlay-uri",overlayFetchCredentials:g="include",footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p}){let[m,v]=(0,Nt.useState)(t.getState().open),S=Cm(),[T,A]=(0,Nt.useState)(()=>typeof window<"u"?window.location.pathname:"/"),k=S?.url?new URL(S.url).pathname:T;(0,Nt.useEffect)(()=>{if(c||typeof window>"u")return;let Z=()=>A(window.location.pathname);window.addEventListener("popstate",Z);let X=history.pushState,W=history.replaceState;return history.pushState=function(...D){X.apply(this,D),queueMicrotask(Z)},history.replaceState=function(...D){W.apply(this,D),queueMicrotask(Z)},()=>{window.removeEventListener("popstate",Z),history.pushState=X,history.replaceState=W}},[c]);let C=(0,Nt.useMemo)(()=>e||es({configUri:n,experiments:s,featureKey:i,configFeatureKey:r,credentials:a}),[e,n,s,i,r,a]),x=Yw({fetcher:C,pollIntervalMs:o,experiments:s,runtime:c,pathname:k}),M=x.tiles.length>0&&!x.error;(0,Nt.useEffect)(()=>t.subscribe(Z=>v(Z.open)),[t]),(0,Nt.useEffect)(()=>{!x.isLoading&&!M&&t.getState().open&&t.setOpen(!1)},[t,M,x.isLoading]);let z=(0,Nt.useRef)(p??null),U=(0,Nt.useRef)(!!p);(0,Nt.useEffect)(()=>{if(!c?.actions)return;if(U.current){x.actions.length>0&&(U.current=!1);return}let Z=!1;return(async()=>{if(z.current){console.log("[SmartCanvasApp] Reverting previous action batch before re-apply");try{await z.current.revertAll()}catch(W){console.error("[SmartCanvasApp] Failed to revert actions:",W)}z.current=null}if(!Z&&x.actions.length>0){console.log(`[SmartCanvasApp] Applying ${x.actions.length} action(s):`,x.actions.map((W,D)=>`[${D}] ${W.kind}${W.anchorId?` anchor="${W.anchorId}"`:""}${W.label?` "${W.label}"`:""}`).join(", "));try{let W=await c.actions.applyBatch(x.actions);Z?await W.revertAll():(z.current=W,console.log("[SmartCanvasApp] Action batch applied successfully"))}catch(W){Z||console.error("[SmartCanvasApp] Failed to apply actions:",W,`
430
430
  Actions that failed:`,JSON.stringify(x.actions,null,2))}}})(),()=>{Z=!0,z.current&&(console.log("[SmartCanvasApp] Cleanup: reverting action batch (actions changed or unmount)"),z.current.revertAll().catch(W=>{console.error("[SmartCanvasApp] Failed to revert actions on cleanup:",W)}),z.current=null)}},[c,x.actions]),(0,Nt.useEffect)(()=>{if(c)return c.events.subscribe({names:["canvas.requestOpen"]},()=>t.setOpen(!0))},[c,t]);let P=(0,Nt.useMemo)(()=>{let Z=x.theme;return Z?{...Z,...d}:d},[x.theme,d]);return!x.isLoading&&!M?null:(0,Yl.jsx)(Zw,{tiles:x.tiles,isLoading:x.isLoading,error:x.error,canvasTitle:x.canvasTitle,telemetry:l,launcherLabel:b??x.launcher?.label,launcherAnimate:x.launcher?.animate,launcherAnimationStyle:x.launcher?.animationStyle,notificationCount:x.launcher?.notificationCount??x.tiles.length,footerSlot:_,isOpen:m,onToggle:()=>t.toggle(),displayMode:x.displayMode,theme:P})}var km=ee(qe(),1),Xw="smart-canvas",Qw=`
431
431
  :host {
432
432
  font: inherit;
@@ -446,7 +446,7 @@ Actions that failed:`,JSON.stringify(x.actions,null,2))}}})(),()=>{Z=!0,z.curren
446
446
  `).replace(/\r/g,`
447
447
  `)).length,r=0;r<i;r++){var o=t.charCodeAt(r),s=null;o<128?n++:s=o>127&&o<2048?String.fromCharCode(o>>6|192,63&o|128):String.fromCharCode(o>>12|224,o>>6&63|128,63&o|128),Ki(s)||(n>e&&(a+=t.substring(e,n)),a+=s,e=n=r+1)}return n>e&&(a+=t.substring(e,t.length)),a},WL=!!yv||!!vv,HC="text/plain",zf=function(t,e,n){var i;n===void 0&&(n=!0);var[r,a]=t.split("?"),o=j({},e),s=(i=a?.split("&").map((c=>{var u,[f,h]=c.split("="),g=n&&(u=o[f])!==null&&u!==void 0?u:h;return delete o[f],f+"="+g})))!==null&&i!==void 0?i:[],l=fL(o);return l&&s.push(l),r+"?"+s.join("&")},bc=(t,e)=>JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e),fv=t=>{var{data:e,compression:n}=t;if(e){if(n===Wi.GZipJS){var i=ZL((function(l,c){var u=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var f=new Ln(l.length+(l.length>>>1)),h=0,g=function(d){f[h++]=d},_=0;_<u;++_){if(h+5>f.length){var b=new Ln(h+8+(u-_<<1));b.set(f),f=b}var w=l.charCodeAt(_);w<128||c?g(w):w<2048?(g(192|w>>>6),g(128|63&w)):w>55295&&w<57344?(g(240|(w=65536+(1047552&w)|1023&l.charCodeAt(++_))>>>18),g(128|w>>>12&63),g(128|w>>>6&63),g(128|63&w)):(g(224|w>>>12),g(128|w>>>6&63),g(128|63&w))}return YA(f,0,h)})(bc(e)),{mtime:0}),r=new Blob([i],{type:HC});return{contentType:HC,body:r,estimatedSize:r.size}}if(n===Wi.Base64){var a=(function(l){var c,u,f,h,g,_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b=0,w=0,d="",p=[];if(!l)return l;l=YL(l);do c=(g=l.charCodeAt(b++)<<16|l.charCodeAt(b++)<<8|l.charCodeAt(b++))>>18&63,u=g>>12&63,f=g>>6&63,h=63&g,p[w++]=_.charAt(c)+_.charAt(u)+_.charAt(f)+_.charAt(h);while(b<l.length);switch(d=p.join(""),l.length%3){case 1:d=d.slice(0,-2)+"==";break;case 2:d=d.slice(0,-1)+"="}return d})(bc(e)),o=(l=>"data="+encodeURIComponent(typeof l=="string"?l:bc(l)))(a);return{contentType:"application/x-www-form-urlencoded",body:o,estimatedSize:new Blob([o]).size}}var s=bc(e);return{contentType:"application/json",body:s,estimatedSize:new Blob([s]).size}}},_f=[];vv&&_f.push({transport:"fetch",method:t=>{var e,n,{contentType:i,body:r,estimatedSize:a}=(e=fv(t))!==null&&e!==void 0?e:{},o=new Headers;Re(t.headers,(function(u,f){o.append(f,u)})),i&&o.append("Content-Type",i);var s=t.url,l=null;if(tC){var c=new tC;l={signal:c.signal,timeout:setTimeout((()=>c.abort()),t.timeout)}}vv(s,j({method:t?.method||"GET",headers:o,keepalive:t.method==="POST"&&(a||0)<52428.8,body:r,signal:(n=l)==null?void 0:n.signal},t.fetchOptions)).then((u=>u.text().then((f=>{var h={statusCode:u.status,text:f};if(u.status===200)try{h.json=JSON.parse(f)}catch(g){$.error(g)}t.callback==null||t.callback(h)})))).catch((u=>{$.error(u),t.callback==null||t.callback({statusCode:0,text:u})})).finally((()=>l?clearTimeout(l.timeout):null))}}),yv&&_f.push({transport:"XHR",method:t=>{var e,n=new yv;n.open(t.method||"GET",t.url,!0);var{contentType:i,body:r}=(e=fv(t))!==null&&e!==void 0?e:{};Re(t.headers,(function(a,o){n.setRequestHeader(o,a)})),i&&n.setRequestHeader("Content-Type",i),t.timeout&&(n.timeout=t.timeout),t.disableXHRCredentials||(n.withCredentials=!0),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(r)}}),dn!=null&&dn.sendBeacon&&_f.push({transport:"sendBeacon",method:t=>{var e=zf(t.url,{beacon:"1"});try{var n,{contentType:i,body:r}=(n=fv(t))!==null&&n!==void 0?n:{},a=typeof r=="string"?new Blob([r],{type:i}):r;dn.sendBeacon(e,a)}catch{}}});var Bf=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function IC(t,e,n){return bc({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var WA={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>Bf(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!Bf(n,i))))),icontains:(t,e)=>e.map(yf).some((n=>t.map(yf).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(yf).every((n=>t.map(yf).every((i=>!n.includes(i)))))},yf=t=>t.toLowerCase();function KA(t,e){return!t||Object.entries(t).every((n=>{var[i,r]=n,a=e?.[i];if(I(a)||Ki(a))return!1;var o=[String(a)],s=WA[r.operator];return!!s&&s(r.values,o)}))}var pv=st("[Error tracking]"),ly=class{constructor(e){var n,i;this.Jt=[],this.Kt=new wv([new Cv,new Nv,new Tv,new Av,new Ov,new Rv,new kv,new Mv],Y4("web:javascript",q4,Z4)),this._instance=e,this.Jt=(n=(i=this._instance.persistence)==null?void 0:i.get_property(Lv))!==null&&n!==void 0?n:[]}onRemoteConfig(e){var n,i,r,a=(n=(i=e.errorTracking)==null?void 0:i.suppressionRules)!==null&&n!==void 0?n:[],o=(r=e.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Jt=a,this._instance.persistence&&this._instance.persistence.register({[Lv]:this.Jt,[fC]:o})}get Yt(){var e,n=!!this._instance.get_property(fC),i=this._instance.config.error_tracking.captureExtensionExceptions;return(e=i??n)!==null&&e!==void 0&&e}buildProperties(e,n){return this.Kt.buildFromUnknown(e,{syntheticException:n?.syntheticException,mechanism:{handled:n?.handled}})}sendExceptionEvent(e){var n=e.$exception_list;if(this.Xt(n)){if(this.Qt(n))return void pv.info("Skipping exception capture because a suppression rule matched");if(!this.Yt&&this.Zt(n))return void pv.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ti(n))return void pv.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"})}Qt(e){if(e.length===0)return!1;var n=e.reduce(((i,r)=>{var{type:a,value:o}=r;return ot(a)&&a.length>0&&i.$exception_types.push(a),ot(o)&&o.length>0&&i.$exception_values.push(o),i}),{$exception_types:[],$exception_values:[]});return this.Jt.some((i=>{var r=i.values.map((a=>{var o,s=WA[a.operator],l=Ae(a.value)?a.value:[a.value],c=(o=n[a.key])!==null&&o!==void 0?o:[];return l.length>0&&s(l,c)}));return i.type==="OR"?r.some(Boolean):r.every(Boolean)}))}Zt(e){return e.flatMap((n=>{var i,r;return(i=(r=n.stacktrace)==null?void 0:r.frames)!==null&&i!==void 0?i:[]})).some((n=>n.filename&&n.filename.startsWith("chrome-extension://")))}ti(e){if(e.length>0){var n,i,r,a,o=(n=(i=e[0].stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[],s=o[o.length-1];return(r=s==null||(a=s.filename)==null?void 0:a.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}Xt(e){return!Ee(e)&&Ae(e)}},Zn=st("[FeatureFlags]"),uc=st("[FeatureFlags]",{debugEnabled:!0}),hv="$active_feature_flags",_s="$override_feature_flags",zC="$feature_flag_payloads",dc="$override_feature_flag_payloads",BC="$feature_flag_request_id",$C="$feature_flag_evaluated_at",FC=t=>{var e={};for(var[n,i]of bf(t||{}))i&&(e[n]=i);return e},KL=t=>{var e=t.flags;return e?(t.featureFlags=Object.fromEntries(Object.keys(e).map((n=>{var i;return[n,(i=e[n].variant)!==null&&i!==void 0?i:e[n].enabled]}))),t.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter((n=>e[n].enabled)).filter((n=>{var i;return(i=e[n].metadata)==null?void 0:i.payload})).map((n=>{var i;return[n,(i=e[n].metadata)==null?void 0:i.payload]})))):Zn.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),t},XL=(function(t){return t.FeatureFlags="feature_flags",t.Recordings="recordings",t})({}),cy=class{constructor(e){this.ii=!1,this.ei=!1,this.ri=!1,this.si=!1,this.ni=!1,this.oi=!1,this.ai=!1,this._instance=e,this.featureFlagEventHandlers=[]}li(){var e=this._instance.config.evaluation_environments;return e!=null&&e.length?e.filter((n=>{var i=n&&typeof n=="string"&&n.trim().length>0;return i||Zn.error("Invalid evaluation environment found:",n,"Expected non-empty string"),i})):[]}ui(){return this.li().length>0}flags(){if(this._instance.config.__preview_remote_config)this.oi=!0;else{var e=!this.hi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.vi({disableFlags:e})}}get hasLoadedFlags(){return this.ei}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(Hv),n=this._instance.get_property(_s),i=this._instance.get_property(dc);if(!i&&!n)return e||{};var r=Ye({},e||{}),a=[...new Set([...Object.keys(i||{}),...Object.keys(n||{})])];for(var o of a){var s,l,c=r[o],u=n?.[o],f=I(u)?(s=c?.enabled)!==null&&s!==void 0&&s:!!u,h=I(u)?c.variant:typeof u=="string"?u:void 0,g=i?.[o],_=j({},c,{enabled:f,variant:f?h??c?.variant:void 0});f!==c?.enabled&&(_.original_enabled=c?.enabled),h!==c?.variant&&(_.original_variant=c?.variant),g&&(_.metadata=j({},c?.metadata,{payload:g,original_payload:c==null||(l=c.metadata)==null?void 0:l.payload})),r[o]=_}return this.ii||(Zn.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:i,finalDetails:r}),this.ii=!0),r}getFlagVariants(){var e=this._instance.get_property(Es),n=this._instance.get_property(_s);if(!n)return e||{};for(var i=Ye({},e),r=Object.keys(n),a=0;a<r.length;a++)i[r[a]]=n[r[a]];return this.ii||(Zn.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:n,finalFlags:i}),this.ii=!0),i}getFlagPayloads(){var e=this._instance.get_property(zC),n=this._instance.get_property(dc);if(!n)return e||{};for(var i=Ye({},e||{}),r=Object.keys(n),a=0;a<r.length;a++)i[r[a]]=n[r[a]];return this.ii||(Zn.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:n,finalPayloads:i}),this.ii=!0),i}reloadFeatureFlags(){this.si||this._instance.config.advanced_disable_feature_flags||this.hi||(this.hi=setTimeout((()=>{this.vi()}),5))}di(){clearTimeout(this.hi),this.hi=void 0}ensureFlagsLoaded(){this.ei||this.ri||this.hi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.si=e}vi(e){var n;if(this.di(),!this._instance.O())if(this.ri)this.ni=!0;else{var i={token:this._instance.config.token,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:j({},((n=this._instance.persistence)==null?void 0:n.get_initial_props())||{},this._instance.get_property(vc)||{}),group_properties:this._instance.get_property(Xa)};(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(i.disable_flags=!0),this.ui()&&(i.evaluation_environments=this.li());var r=this._instance.config.__preview_remote_config,a=r?"/flags/?v=2":"/flags/?v=2&config=true",o=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",s=this._instance.requestRouter.endpointFor("flags",a+o);r&&(i.timezone=qA()),this.ri=!0,this._instance.ci({method:"POST",url:s,data:i,compression:this._instance.config.disable_compression?void 0:Wi.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:l=>{var c,u,f=!0;if(l.statusCode===200&&(this.ni||(this.$anon_distinct_id=void 0),f=!1),this.ri=!1,this.oi||(this.oi=!0,this._instance.fi((u=l.json)!==null&&u!==void 0?u:{})),!i.disable_flags||this.ni)if(this.ai=!f,l.json&&(c=l.json.quotaLimited)!=null&&c.includes(XL.FeatureFlags))Zn.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 h;i.disable_flags||this.receivedFeatureFlags((h=l.json)!==null&&h!==void 0?h:{},f),this.ni&&(this.ni=!1,this.vi())}}})}}getFeatureFlag(e,n){if(n===void 0&&(n={}),this.ei||this.getFlags()&&this.getFlags().length>0){var i=this.getFlagVariants()[e],r=""+i,a=this._instance.get_property(BC)||void 0,o=this._instance.get_property($C)||void 0,s=this._instance.get_property(Cf)||{};if((n.send_event||!("send_event"in n))&&(!(e in s)||!s[e].includes(r))){var l,c,u,f,h,g,_,b,w;Ae(s[e])?s[e].push(r):s[e]=[r],(l=this._instance.persistence)==null||l.register({[Cf]:s});var d=this.getFeatureFlagDetails(e),p={$feature_flag:e,$feature_flag_response:i,$feature_flag_payload:this.getFeatureFlagPayload(e)||null,$feature_flag_request_id:a,$feature_flag_evaluated_at:o,$feature_flag_bootstrapped_response:((c=this._instance.config.bootstrap)==null||(c=c.featureFlags)==null?void 0:c[e])||null,$feature_flag_bootstrapped_payload:((u=this._instance.config.bootstrap)==null||(u=u.featureFlagPayloads)==null?void 0:u[e])||null,$used_bootstrap_value:!this.ai};I(d==null||(f=d.metadata)==null?void 0:f.version)||(p.$feature_flag_version=d.metadata.version);var m,v=(h=d==null||(g=d.reason)==null?void 0:g.description)!==null&&h!==void 0?h:d==null||(_=d.reason)==null?void 0:_.code;v&&(p.$feature_flag_reason=v),d!=null&&(b=d.metadata)!=null&&b.id&&(p.$feature_flag_id=d.metadata.id),I(d?.original_variant)&&I(d?.original_enabled)||(p.$feature_flag_original_response=I(d.original_variant)?d.original_enabled:d.original_variant),d!=null&&(w=d.metadata)!=null&&w.original_payload&&(p.$feature_flag_original_payload=d==null||(m=d.metadata)==null?void 0:m.original_payload),this._instance.capture("$feature_flag_called",p)}return i}Zn.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){return this.getFlagPayloads()[e]}getRemoteConfigPayload(e,n){var i=this._instance.config.token,r={distinct_id:this._instance.get_distinct_id(),token:i};this.ui()&&(r.evaluation_environments=this.li()),this._instance.ci({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:r,compression:this._instance.config.disable_compression?void 0:Wi.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:a=>{var o,s=(o=a.json)==null?void 0:o.featureFlagPayloads;n(s?.[e]||void 0)}})}isFeatureEnabled(e,n){if(n===void 0&&(n={}),this.ei||this.getFlags()&&this.getFlags().length>0){var i=this.getFeatureFlag(e,n);return I(i)?void 0:!!i}Zn.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((n=>n!==e))}receivedFeatureFlags(e,n){if(this._instance.persistence){this.ei=!0;var i=this.getFlagVariants(),r=this.getFlagPayloads(),a=this.getFlagsWithDetails();(function(o,s,l,c,u){l===void 0&&(l={}),c===void 0&&(c={}),u===void 0&&(u={});var f=KL(o),h=f.flags,g=f.featureFlags,_=f.featureFlagPayloads;if(g){var b=o.requestId,w=o.evaluatedAt;if(Ae(g)){Zn.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var d={};if(g)for(var p=0;p<g.length;p++)d[g[p]]=!0;s&&s.register({[hv]:g,[Es]:d})}else{var m=g,v=_,S=h;o.errorsWhileComputingFlags&&(m=j({},l,m),v=j({},c,v),S=j({},u,S)),s&&s.register(j({[hv]:Object.keys(FC(m)),[Es]:m||{},[zC]:v||{},[Hv]:S||{}},b?{[BC]:b}:{},w?{[$C]:w}:{}))}}})(e,this._instance.persistence,i,r,a),this.pi(n)}}override(e,n){n===void 0&&(n=!1),Zn.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:n})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return Zn.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(_s),this._instance.persistence.unregister(dc),this.pi(),uc.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var n,i=e;if(this.ii=!!((n=i.suppressWarning)!==null&&n!==void 0&&n),"flags"in i){if(i.flags===!1)this._instance.persistence.unregister(_s),uc.info("Flag overrides cleared");else if(i.flags){if(Ae(i.flags)){for(var r={},a=0;a<i.flags.length;a++)r[i.flags[a]]=!0;this._instance.persistence.register({[_s]:r})}else this._instance.persistence.register({[_s]:i.flags});uc.info("Flag overrides set",{flags:i.flags})}}return"payloads"in i&&(i.payloads===!1?(this._instance.persistence.unregister(dc),uc.info("Payload overrides cleared")):i.payloads&&(this._instance.persistence.register({[dc]:i.payloads}),uc.info("Payload overrides set",{payloads:i.payloads}))),void this.pi()}this.pi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ei){var{flags:n,flagVariants:i}=this.gi();e(n,i)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,n,i){var r,a=(this._instance.get_property(mc)||[]).find((c=>c.flagKey===e)),o={["$feature_enrollment/"+e]:n},s={$feature_flag:e,$feature_enrollment:n,$set:o};a&&(s.$early_access_feature_name=a.name),i&&(s.$feature_enrollment_stage=i),this._instance.capture("$feature_enrollment_update",s),this.setPersonPropertiesForFlags(o,!1);var l=j({},this.getFlagVariants(),{[e]:n});(r=this._instance.persistence)==null||r.register({[hv]:Object.keys(FC(l)),[Es]:l}),this.pi()}getEarlyAccessFeatures(e,n,i){n===void 0&&(n=!1);var r=this._instance.get_property(mc),a=i?"&"+i.map((o=>"stage="+o)).join("&"):"";if(r&&!n)return e(r);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+a),method:"GET",callback:o=>{var s,l;if(o.json){var c=o.json.earlyAccessFeatures;return(s=this._instance.persistence)==null||s.unregister(mc),(l=this._instance.persistence)==null||l.register({[mc]:c}),e(c)}}})}gi(){var e=this.getFlags(),n=this.getFlagVariants();return{flags:e.filter((i=>n[i])),flagVariants:Object.keys(n).filter((i=>n[i])).reduce(((i,r)=>(i[r]=n[r],i)),{})}}pi(e){var{flags:n,flagVariants:i}=this.gi();this.featureFlagEventHandlers.forEach((r=>r(n,i,{errorsLoading:e})))}setPersonPropertiesForFlags(e,n){n===void 0&&(n=!0);var i=this._instance.get_property(vc)||{};this._instance.register({[vc]:j({},i,e)}),n&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(vc)}setGroupPropertiesForFlags(e,n){n===void 0&&(n=!0);var i=this._instance.get_property(Xa)||{};Object.keys(i).length!==0&&Object.keys(i).forEach((r=>{i[r]=j({},i[r],e[r]),delete e[r]})),this._instance.register({[Xa]:j({},i,e)}),n&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var n=this._instance.get_property(Xa)||{};this._instance.register({[Xa]:j({},n,{[e]:{}})})}else this._instance.unregister(Xa)}reset(){this.ei=!1,this.ri=!1,this.si=!1,this.ni=!1,this.oi=!1,this.ai=!1,this.$anon_distinct_id=void 0,this.di(),this.ii=!1}},QL=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],xc=class{constructor(e,n){this.F=e,this.props={},this.mi=!1,this.yi=(i=>{var r="";return i.token&&(r=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+r+"_posthog"})(e),this.Y=this.bi(e),this.load(),e.debug&&$.info("Persistence loaded",e.persistence,j({},this.props)),this.update_config(e,e,n),this.save()}isDisabled(){return!!this.wi}bi(e){QL.indexOf(e.persistence.toLowerCase())===-1&&($.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n=e.persistence.toLowerCase();return n==="localstorage"&&Ue.H()?Ue:n==="localstorage+cookie"&&hf.H()?hf:n==="sessionstorage"&&St.H()?St:n==="memory"?_L:n==="cookie"?ui:hf.H()?hf:ui}properties(){var e={};return Re(this.props,(function(n,i){if(i===Es&&ft(n))for(var r=Object.keys(n),a=0;a<r.length;a++)e["$feature/"+r[a]]=n[r[a]];else s=i,l=!1,(Ki(o=nL)?l:eC&&o.indexOf===eC?o.indexOf(s)!=-1:(Re(o,(function(c){if(l||(l=c===s))return wf})),l))||(e[i]=n);var o,s,l})),e}load(){if(!this.wi){var e=this.Y.W(this.yi);e&&(this.props=Ye({},e))}}save(){this.wi||this.Y.G(this.yi,this.props,this.xi,this.Si,this.Ei,this.F.debug)}remove(){this.Y.V(this.yi,!1),this.Y.V(this.yi,!0)}clear(){this.remove(),this.props={}}register_once(e,n,i){if(ft(e)){I(n)&&(n="None"),this.xi=I(i)?this.$i:i;var r=!1;if(Re(e,((a,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.props[o]=a,r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(ft(e)){this.xi=I(n)?this.$i:n;var i=!1;if(Re(e,((r,a)=>{e.hasOwnProperty(a)&&this.props[a]!==r&&(this.props[a]=r,i=!0)})),i)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.mi){var e=BA(this.F.custom_campaign_params,this.F.mask_personal_data_properties,this.F.custom_personal_data_properties);ws(Ty(e))||this.register(e),this.mi=!0}}update_search_keyword(){var e;this.register((e=B?.referrer)?FA(e):{})}update_referrer_info(){var e;this.register_once({$referrer:UA(),$referring_domain:B!=null&&B.referrer&&((e=Of(B.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[$v]||this.props[Fv]||this.register_once({[Af]:VA(this.F.mask_personal_data_properties,this.F.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};Re([Fv,$v],(o=>{var s=this.props[o];s&&Re(s,(function(l,c){e["$initial_"+bv(c)]=l}))}));var n,i,r=this.props[Af];if(r){var a=(n=jA(r),i={},Re(n,(function(o,s){i["$initial_"+bv(s)]=o})),i);Ye(e,a)}return e}safe_merge(e){return Re(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){if(this.$i=this.xi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==n.persistence){var r=this.bi(e),a=this.props;this.clear(),this.Y=r,this.props=a,this.save()}}set_disabled(e){this.wi=e,this.wi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Si&&(this.Si=e,this.remove(),this.save())}set_secure(e){e!==this.Ei&&(this.Ei=e,this.remove(),this.save())}set_event_timer(e,n){var i=this.props[gc]||{};i[e]=n,this.props[gc]=i,this.save()}remove_event_timer(e){var n=(this.props[gc]||{})[e];return I(n)||(delete this.props[gc][e],this.save()),n}get_property(e){return this.props[e]}set_property(e,n){this.props[e]=n,this.save()}},fc=(function(t){return t.Activation="events",t.Cancellation="cancelEvents",t})({}),SB=(function(t){return t.Button="button",t.Tab="tab",t.Selector="selector",t})({}),xB=(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})({}),wB=(function(t){return t.Top="top",t.Left="left",t.Right="right",t.Bottom="bottom",t})({}),gv=(function(t){return t.Popover="popover",t.API="api",t.Widget="widget",t.ExternalSurvey="external_survey",t})({}),EB=(function(t){return t.Open="open",t.MultipleChoice="multiple_choice",t.SingleChoice="single_choice",t.Rating="rating",t.Link="link",t})({}),CB=(function(t){return t.NextQuestion="next_question",t.End="end",t.ResponseBased="response_based",t.SpecificQuestion="specific_question",t})({}),AB=(function(t){return t.Once="once",t.Recurring="recurring",t.Always="always",t})({}),Sf=(function(t){return t.SHOWN="survey shown",t.DISMISSED="survey dismissed",t.SENT="survey sent",t})({}),UC=(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})({}),XA=(function(t){return t.Popover="popover",t.Inline="inline",t})({}),Rc=class{constructor(){this.ki={},this.ki={}}on(e,n){return this.ki[e]||(this.ki[e]=[]),this.ki[e].push(n),()=>{this.ki[e]=this.ki[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.ki[e]||[])i(n);for(var r of this.ki["*"]||[])r(e,n)}};function Ss(t,e,n){if(Ee(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}var uy=class{constructor(e){this.Pi=new Rc,this.Ti=(n,i)=>this.Ri(n,i)&&this.Ii(n,i)&&this.Fi(n,i)&&this.Ci(n,i),this.Ri=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.Mi=new Set,this.Oi=new Set}init(){var e;if(!I((e=this._instance)==null?void 0:e.Ai)){var n;(n=this._instance)==null||n.Ai(((i,r)=>{this.on(i,r)}))}}register(e){var n,i;if(!I((n=this._instance)==null?void 0:n.Ai)&&(e.forEach((o=>{var s,l;(s=this.Oi)==null||s.add(o),(l=o.steps)==null||l.forEach((c=>{var u;(u=this.Mi)==null||u.add(c?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,a=new Set;e.forEach((o=>{var s;(s=o.steps)==null||s.forEach((l=>{l!=null&&l.selector&&a.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(a)}}on(e,n){var i;n!=null&&e.length!=0&&(this.Mi.has(e)||this.Mi.has(n?.event))&&this.Oi&&((i=this.Oi)==null?void 0:i.size)>0&&this.Oi.forEach((r=>{this.Di(n,r)&&this.Pi.emit("actionCaptured",r.name)}))}ji(e){this.onAction("actionCaptured",(n=>e(n)))}Di(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.Ti(e,i))return!0;return!1}onAction(e,n){return this.Pi.on(e,n)}Ii(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!Ss(r,n.url,n.url_matching||"contains"))return!1}return!0}Fi(e,n){return!!this.Li(e,n)&&!!this.Ni(e,n)&&!!this.Ui(e,n)}Li(e,n){var i;if(n==null||!n.href)return!0;var r=this.zi(e);if(r.length>0)return r.some((s=>Ss(s.href,n.href,n.href_matching||"exact")));var a,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&Ss((a=o.match(/(?::|")href="(.*?)"/))?a[1]:"",n.href,n.href_matching||"exact")}Ni(e,n){var i;if(n==null||!n.text)return!0;var r=this.zi(e);if(r.length>0)return r.some((c=>Ss(c.text,n.text,n.text_matching||"exact")||Ss(c.$el_text,n.text,n.text_matching||"exact")));var a,o,s,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(a=(function(c){for(var u,f=[],h=/(?::|")text="(.*?)"/g;!Ee(u=h.exec(c));)f.includes(u[1])||f.push(u[1]);return f})(l),o=n.text,s=n.text_matching||"exact",a.some((c=>Ss(c,o,s))))}Ui(e,n){var i,r;if(n==null||!n.selector)return!0;var a=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(a!=null&&a.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}zi(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}Ci(e,n){return n==null||!n.properties||n.properties.length===0||KA(n.properties.reduce(((i,r)=>{var a=Ae(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:a,operator:r.operator||"exact"},i}),{}),e?.properties)}},Se=st("[Surveys]"),dy="seenSurvey_",JL=(t,e)=>{var n="$survey_"+e+"/"+t.id;return t.current_iteration&&t.current_iteration>0&&(n="$survey_"+e+"/"+t.id+"/"+t.current_iteration),n},VC=t=>{var e=""+dy+t.id;return t.current_iteration&&t.current_iteration>0&&(e=""+dy+t.id+"_"+t.current_iteration),e},e3=[gv.Popover,gv.Widget,gv.API],t3={ignoreConditions:!1,ignoreDelay:!1,displayType:XA.Popover},fy=class{constructor(e){this._instance=e,this.Hi=new Map,this.Bi=new Map,this.qi=new Map}Wi(e,n){return!!e&&KA(e.propertyFilters,n?.properties)}Gi(e,n){var i=new Map;return e.forEach((r=>{var a;(a=r.conditions)==null||(a=a[n])==null||(a=a.values)==null||a.forEach((o=>{if(o!=null&&o.name){var s=i.get(o.name)||[];s.push(r.id),i.set(o.name,s)}}))})),i}Vi(e,n,i){var r,a=(i===fc.Activation?this.Hi:this.Bi).get(e),o=[];return(r=this._instance)==null||r.getSurveys((s=>{o=s.filter((l=>a?.includes(l.id)))})),o.filter((s=>{var l,c=(l=s.conditions)==null||(l=l[i])==null||(l=l.values)==null?void 0:l.find((u=>u.name===e));return this.Wi(c,n)}))}register(e){var n;I((n=this._instance)==null?void 0:n.Ai)||(this.Ji(e),this.Ki(e))}Ki(e){var n=e.filter((i=>{var r,a;return((r=i.conditions)==null?void 0:r.actions)&&((a=i.conditions)==null||(a=a.actions)==null||(a=a.values)==null?void 0:a.length)>0}));n.length!==0&&(this.Yi==null&&(this.Yi=new uy(this._instance),this.Yi.init(),this.Yi.ji((i=>{this.onAction(i)}))),n.forEach((i=>{var r,a,o,s,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(a=i.conditions)!=null&&(a=a.actions)!=null&&a.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((s=this.Yi)==null||s.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((c=>{if(c&&c.name){var u=this.qi.get(c.name);u&&u.push(i.id),this.qi.set(c.name,u||[i.id])}})))})))}Ji(e){var n,i=e.filter((a=>{var o,s;return((o=a.conditions)==null?void 0:o.events)&&((s=a.conditions)==null||(s=s.events)==null||(s=s.values)==null?void 0:s.length)>0})),r=e.filter((a=>{var o,s;return((o=a.conditions)==null?void 0:o.cancelEvents)&&((s=a.conditions)==null||(s=s.cancelEvents)==null||(s=s.values)==null?void 0:s.length)>0}));(i.length!==0||r.length!==0)&&((n=this._instance)==null||n.Ai(((a,o)=>{this.onEvent(a,o)})),this.Hi=this.Gi(e,fc.Activation),this.Bi=this.Gi(e,fc.Cancellation))}onEvent(e,n){var i,r=((i=this._instance)==null||(i=i.persistence)==null?void 0:i.props[pf])||[];if(Sf.SHOWN===e&&n&&r.length>0){var a;Se.info("survey event matched, removing survey from activated surveys",{event:e,eventPayload:n,existingActivatedSurveys:r});var o=n==null||(a=n.properties)==null?void 0:a.$survey_id;if(o){var s=r.indexOf(o);s>=0&&(r.splice(s,1),this.Xi(r))}}else{if(this.Bi.has(e)){var l=this.Vi(e,n,fc.Cancellation);l.length>0&&(Se.info("cancel event matched, cancelling surveys",{event:e,surveysToCancel:l.map((u=>u.id))}),l.forEach((u=>{var f,h=r.indexOf(u.id);h>=0&&r.splice(h,1),(f=this._instance)==null||f.cancelPendingSurvey(u.id)})),this.Xi(r))}if(this.Hi.has(e)){Se.info("survey event name matched",{event:e,eventPayload:n,surveys:this.Hi.get(e)});var c=this.Vi(e,n,fc.Activation);this.Xi(r.concat(c.map((u=>u.id))||[]))}}}onAction(e){var n,i=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[pf])||[];this.qi.has(e)&&this.Xi(i.concat(this.qi.get(e)||[]))}Xi(e){var n;Se.info("updating activated surveys",{activatedSurveys:e}),(n=this._instance)==null||(n=n.persistence)==null||n.register({[pf]:[...new Set(e)]})}getSurveys(){var e,n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[pf];return n||[]}getEventToSurveys(){return this.Hi}Qi(){return this.Yi}},py=class{constructor(e){this.Zi=void 0,this._surveyManager=null,this.te=!1,this.ie=!1,this.ee=[],this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var n=e.surveys;if(Ee(n))return Se.warn("Flags not loaded yet. Not loading surveys.");var i=Ae(n);this.Zi=i?n.length>0:n,Se.info("flags response received, isSurveysEnabled: "+this.Zi),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;n<localStorage.length;n++){var i=localStorage.key(n);(i!=null&&i.startsWith(dy)||i!=null&&i.startsWith("inProgressSurvey_"))&&e.push(i)}e.forEach((r=>localStorage.removeItem(r)))}loadIfEnabled(){if(!this._surveyManager)if(this.ie)Se.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)Se.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())Se.info("Not loading surveys in cookieless mode without consent.");else{var e=J?.__PosthogExtensions__;if(e){if(!I(this.Zi)||this._instance.config.advanced_enable_surveys){var n=this.Zi||this._instance.config.advanced_enable_surveys;this.ie=!0;try{var i=e.generateSurveys;if(i)return void this.re(i,n);var r=e.loadExternalDependency;if(!r)return void this.se("PostHog loadExternalDependency extension not found.");r(this._instance,"surveys",(a=>{a||!e.generateSurveys?this.se("Could not load surveys script",a):this.re(e.generateSurveys,n)}))}catch(a){throw this.se("Error initializing surveys",a),a}finally{this.ie=!1}}}else Se.error("PostHog Extensions not found.")}}re(e,n){this._surveyManager=e(this._instance,n),this._surveyEventReceiver=new fy(this._instance),Se.info("Surveys loaded successfully"),this.ne({isLoaded:!0})}se(e,n){Se.error(e,n),this.ne({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.ee.push(e),this._surveyManager&&this.ne({isLoaded:!0}),()=>{this.ee=this.ee.filter((n=>n!==e))}}getSurveys(e,n){if(n===void 0&&(n=!1),this._instance.config.disable_surveys)return Se.info("Disabled. Not loading surveys."),e([]);var i=this._instance.get_property(Iv);if(i&&!n)return e(i,{isLoaded:!0});if(this.te)return e([],{isLoaded:!1,error:"Surveys are already being loaded"});try{this.te=!0,this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:r=>{var a;this.te=!1;var o=r.statusCode;if(o!==200||!r.json){var s="Surveys API could not be loaded, status: "+o;return Se.error(s),e([],{isLoaded:!1,error:s})}var l,c=r.json.surveys||[],u=c.filter((f=>(function(h){return!(!h.start_date||h.end_date)})(f)&&((function(h){var g;return!((g=h.conditions)==null||(g=g.events)==null||(g=g.values)==null||!g.length)})(f)||(function(h){var g;return!((g=h.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(f))));return u.length>0&&((l=this._surveyEventReceiver)==null||l.register(u)),(a=this._instance.persistence)==null||a.register({[Iv]:c}),e(c,{isLoaded:!0})}})}catch(r){throw this.te=!1,r}}ne(e){for(var n of this.ee)try{if(!e.isLoaded)return n([],e);this.getSurveys(n)}catch(i){Se.error("Error in survey callback",i)}}getActiveMatchingSurveys(e,n){if(n===void 0&&(n=!1),!Ee(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,n);Se.warn("init was not called")}oe(e){var n=null;return this.getSurveys((i=>{var r;n=(r=i.find((a=>a.id===e)))!==null&&r!==void 0?r:null})),n}ae(e){if(Ee(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var n=typeof e=="string"?this.oe(e):e;return n?this._surveyManager.checkSurveyEligibility(n):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(Ee(this._surveyManager))return Se.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var n=this.ae(e);return{visible:n.eligible,disabledReason:n.reason}}canRenderSurveyAsync(e,n){return Ee(this._surveyManager)?(Se.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise((i=>{this.getSurveys((r=>{var a,o=(a=r.find((l=>l.id===e)))!==null&&a!==void 0?a:null;if(o){var s=this.ae(o);i({visible:s.eligible,disabledReason:s.reason})}else i({visible:!1,disabledReason:"Survey not found"})}),n)}))}renderSurvey(e,n){var i;if(Ee(this._surveyManager))Se.warn("init was not called");else{var r=typeof e=="string"?this.oe(e):e;if(r!=null&&r.id)if(e3.includes(r.type)){var a=B?.querySelector(n);if(a)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Se.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,s;Se.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(s=this._surveyManager)==null||s.renderSurvey(r,a),Se.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,a);Se.warn("Survey element not found")}else Se.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Se.warn("Survey not found")}}displaySurvey(e,n){var i;if(Ee(this._surveyManager))Se.warn("init was not called");else{var r=this.oe(e);if(r){var a=r;if((i=r.appearance)!=null&&i.surveyPopupDelaySeconds&&n.ignoreDelay&&(a=j({},r,{appearance:j({},r.appearance,{surveyPopupDelaySeconds:0})})),n.ignoreConditions===!1){var o=this.canRenderSurvey(r);if(!o.visible)return void Se.warn("Survey is not eligible to be displayed: ",o.disabledReason)}n.displayType!==XA.Inline?this._surveyManager.handlePopoverSurvey(a):this.renderSurvey(a,n.selector)}else Se.warn("Survey not found")}}cancelPendingSurvey(e){Ee(this._surveyManager)?Se.warn("init was not called"):this._surveyManager.cancelSurvey(e)}},jC=st("[RateLimiter]"),hy=class{constructor(e){var n,i;this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=r=>{var a=r.text;if(a&&a.length)try{(JSON.parse(a).quota_limited||[]).forEach((o=>{jC.info((o||"events")+" is quota limited."),this.serverLimits[o]=new Date().getTime()+6e4}))}catch(o){return void jC.warn('could not rate limit - continuing. Error: "'+o?.message+'"',{text:a})}},this.instance=e,this.captureEventsPerSecond=((n=e.config.rate_limiting)==null?void 0:n.events_per_second)||10,this.captureEventsBurstLimit=Math.max(((i=e.config.rate_limiting)==null?void 0:i.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond),this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var a=new Date().getTime(),o=(n=(i=this.instance.persistence)==null?void 0:i.get_property(Bv))!==null&&n!==void 0?n:{tokens:this.captureEventsBurstLimit,last:a};o.tokens+=(a-o.last)/1e3*this.captureEventsPerSecond,o.last=a,o.tokens>this.captureEventsBurstLimit&&(o.tokens=this.captureEventsBurstLimit);var s=o.tokens<1;return s||e||(o.tokens=Math.max(0,o.tokens-1)),!s||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+this.captureEventsPerSecond+" events per second and "+this.captureEventsBurstLimit+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=s,(r=this.instance.persistence)==null||r.set_property(Bv,o),{isRateLimited:s,remainingTokens:o.tokens}}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()<n}},Ka=st("[RemoteConfig]"),gy=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=J._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}le(e){var n,i;(n=J.__PosthogExtensions__)!=null&&n.loadExternalDependency?(i=J.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,"remote-config",(()=>e(this.remoteConfig))):(Ka.error("PostHog Extensions not found. Cannot load remote config."),e())}ue(e){this._instance.ci({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:n=>{e(n.json)}})}load(){try{if(this.remoteConfig)return Ka.info("Using preloaded remote config",this.remoteConfig),void this.fi(this.remoteConfig);if(this._instance.O())return void Ka.warn("Remote config is disabled. Falling back to local config.");this.le((e=>{if(!e)return Ka.info("No config found after loading remote JS config. Falling back to JSON."),void this.ue((n=>{this.fi(n)}));this.fi(e)}))}catch(e){Ka.error("Error loading remote config",e)}}fi(e){e?this._instance.config.__preview_remote_config?(this._instance.fi(e),e.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):Ka.info("__preview_remote_config is disabled. Logging config instead",e):Ka.error("Failed to fetch remote config from PostHog.")}},my=3e3,vy=class{constructor(e,n){this.he=!0,this.ve=[],this.de=li(n?.flush_interval_ms||my,250,5e3,$.createLogger("flush interval"),my),this.ce=e}enqueue(e){this.ve.push(e),this.fe||this.pe()}unload(){this.ge();var e=this.ve.length>0?this._e():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.ce(j({},i,{transport:"sendBeacon"}))}))}enable(){this.he=!1,this.pe()}pe(){var e=this;this.he||(this.fe=setTimeout((()=>{if(this.ge(),this.ve.length>0){var n=this._e(),i=function(){var a=n[r],o=new Date().getTime();a.data&&Ae(a.data)&&Re(a.data,(s=>{s.offset=Math.abs(s.timestamp-o),delete s.timestamp})),e.ce(a)};for(var r in n)i()}}),this.de))}ge(){clearTimeout(this.fe),this.fe=void 0}_e(){var e={};return Re(this.ve,(n=>{var i,r=n,a=(r?r.batchKey:null)||r.url;I(e[a])&&(e[a]=j({},r,{data:[]})),(i=e[a].data)==null||i.push(r.data)})),this.ve=[],e}},n3=["retriesPerformedSoFar"],yy=class{constructor(e){this.me=!1,this.ye=3e3,this.ve=[],this._instance=e,this.ve=[],this.be=!0,!I(R)&&"onLine"in R.navigator&&(this.be=R.navigator.onLine,this.we=()=>{this.be=!0,this.Dt()},this.xe=()=>{this.be=!1},tt(R,"online",this.we),tt(R,"offline",this.xe))}get length(){return this.ve.length}retriableRequest(e){var{retriesPerformedSoFar:n}=e,i=WC(e,n3);di(n)&&n>0&&(i.url=zf(i.url,{retry_count:n})),this._instance.ci(j({},i,{callback:r=>{r.statusCode!==200&&(r.statusCode<400||r.statusCode>=500)&&(n??0)<10?this.Se(j({retriesPerformedSoFar:n},i)):i.callback==null||i.callback(r)}}))}Se(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var s=3e3*Math.pow(2,o),l=s/2,c=Math.min(18e5,s),u=(Math.random()-.5)*(c-l);return Math.ceil(c+u)})(n),r=Date.now()+i;this.ve.push({retryAt:r,requestOptions:e});var a="Enqueued failed request for retry in "+i;navigator.onLine||(a+=" (Browser is offline)"),$.warn(a),this.me||(this.me=!0,this.Ee())}Ee(){if(this.$e&&clearTimeout(this.$e),this.ve.length===0)return this.me=!1,void(this.$e=void 0);this.$e=setTimeout((()=>{this.be&&this.ve.length>0&&this.Dt(),this.Ee()}),this.ye)}Dt(){var e=Date.now(),n=[],i=this.ve.filter((a=>a.retryAt<e||(n.push(a),!1)));if(this.ve=n,i.length>0)for(var{requestOptions:r}of i)this.retriableRequest(r)}unload(){for(var{requestOptions:e}of(this.$e&&(clearTimeout(this.$e),this.$e=void 0),this.me=!1,I(R)||(this.we&&(R.removeEventListener("online",this.we),this.we=void 0),this.xe&&(R.removeEventListener("offline",this.xe),this.xe=void 0)),this.ve))try{this._instance.ci(j({},e,{transport:"sendBeacon"}))}catch(n){$.error(n)}this.ve=[]}},by=class{constructor(e){this.ke=()=>{var n,i,r,a;this.Pe||(this.Pe={});var o=this.scrollElement(),s=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,c=s+(o?.clientHeight||0),u=o?.scrollHeight||0;this.Pe.lastScrollY=Math.ceil(s),this.Pe.maxScrollY=Math.max(s,(n=this.Pe.maxScrollY)!==null&&n!==void 0?n:0),this.Pe.maxScrollHeight=Math.max(l,(i=this.Pe.maxScrollHeight)!==null&&i!==void 0?i:0),this.Pe.lastContentY=c,this.Pe.maxContentY=Math.max(c,(r=this.Pe.maxContentY)!==null&&r!==void 0?r:0),this.Pe.maxContentHeight=Math.max(u,(a=this.Pe.maxContentHeight)!==null&&a!==void 0?a:0)},this._instance=e}getContext(){return this.Pe}resetContext(){var e=this.Pe;return setTimeout(this.ke,0),e}startMeasuringScrollPosition(){tt(R,"scroll",this.ke,{capture:!0}),tt(R,"scrollend",this.ke,{capture:!0}),tt(R,"resize",this.ke)}scrollElement(){if(!this._instance.config.scroll_root_selector)return R?.document.documentElement;var e=Ae(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var n of e){var i=R?.document.querySelector(n);if(i)return i}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return R&&(R.scrollY||R.pageYOffset||R.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return R&&(R.scrollX||R.pageXOffset||R.document.documentElement.scrollLeft)||0}},i3=t=>VA(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties),$f=class{constructor(e,n,i,r){this.Te=a=>{var o=this.Re();if(!o||o.sessionId!==a){var s={sessionId:a,props:this.Ie(this._instance)};this.Fe.register({[zv]:s})}},this._instance=e,this.Ce=n,this.Fe=i,this.Ie=r||i3,this.Ce.onSessionId(this.Te)}Re(){return this.Fe.props[zv]}getSetOnceProps(){var e,n=(e=this.Re())==null?void 0:e.props;return n?"r"in n?jA(n):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return Re(Ty(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+bv(i)]=n})),e}},mv=st("[SessionId]"),Ff=class{on(e,n){return this.Me.on(e,n)}constructor(e,n,i){var r;if(this.Oe=[],this.Ae=void 0,this.Me=new Rc,this.De=(u,f)=>Math.abs(u-f)>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.F=e.config,this.Fe=e.persistence,this.je=void 0,this.Le=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.Ne=n||Kr,this.Ue=i||Kr;var a=this.F.persistence_name||this.F.token,o=this.F.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*li(o,60,36e3,mv.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.ze(),this.He="ph_"+a+"_window_id",this.Be="ph_"+a+"_primary_window_exists",this.qe()){var s=St.W(this.He),l=St.W(this.Be);s&&!l?this.je=s:St.V(this.He),St.G(this.Be,!0)}if((r=this.F.bootstrap)!=null&&r.sessionID)try{var c=(u=>{var f=u.replace(/-/g,"");if(f.length!==32)throw new Error("Not a valid UUID");if(f[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(f.substring(0,12),16)})(this.F.bootstrap.sessionID);this.We(this.F.bootstrap.sessionID,new Date().getTime(),c)}catch(u){mv.error("Invalid sessionID in bootstrap",u)}this.Ge()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return I(this.Oe)&&(this.Oe=[]),this.Oe.push(e),this.Le&&e(this.Le,this.je),()=>{this.Oe=this.Oe.filter((n=>n!==e))}}qe(){return this.F.persistence!=="memory"&&!this.Fe.wi&&St.H()}Ve(e){e!==this.je&&(this.je=e,this.qe()&&St.G(this.He,e))}Je(){return this.je?this.je:this.qe()?St.W(this.He):null}We(e,n,i){e===this.Le&&n===this._sessionActivityTimestamp&&i===this._sessionStartTimestamp||(this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Le=e,this.Fe.register({[Ef]:[n,e,i]}))}Ke(){var e=this.Fe.props[Ef];return Ae(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.We(null,null,null)}destroy(){clearTimeout(this.Ye),this.Ye=void 0,this.Ae&&R&&(R.removeEventListener("beforeunload",this.Ae,{capture:!1}),this.Ae=void 0),this.Oe=[]}Ge(){this.Ae=()=>{this.qe()&&St.V(this.Be)},tt(R,"beforeunload",this.Ae,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.F.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),[r,a,o]=this.Ke(),s=this.Je(),l=di(o)&&o>0&&Math.abs(i-o)>864e5,c=!1,u=!a,f=!u&&!e&&this.De(i,r);u||f||l?(a=this.Ne(),s=this.Ue(),mv.info("new session ID generated",{sessionId:a,windowId:s,changeReason:{noSessionId:u,activityTimeout:f,sessionPastMaximumLength:l}}),o=i,c=!0):s||(s=this.Ue(),c=!0);var h=r===0||!e||l?i:r,g=o===0?new Date().getTime():o;return this.Ve(s),this.We(a,h,g),e||this.ze(),c&&this.Oe.forEach((_=>_(a,s,c?{noSessionId:u,activityTimeout:f,sessionPastMaximumLength:l}:void 0))),{sessionId:a,windowId:s,sessionStartTimestamp:g,changeReason:c?{noSessionId:u,activityTimeout:f,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:r}}ze(){clearTimeout(this.Ye),this.Ye=setTimeout((()=>{var[e]=this.Ke();if(this.De(new Date().getTime(),e)){var n=this.Le;this.resetSessionId(),this.Me.emit("forcedIdleReset",{idleSessionId:n})}}),1.1*this.sessionTimeoutMs)}},r3=["$set_once","$set"],Yr=st("[SiteApps]"),_y=class{constructor(e){this._instance=e,this.Xe=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Qe(e,n){if(n){var i=this.globalsForEvent(n);this.Xe.push(i),this.Xe.length>1e3&&(this.Xe=this.Xe.slice(10))}}get siteAppLoaders(){var e;return(e=J._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance.Ai(this.Qe.bind(this));this.Ze=()=>{e(),this.Xe=[],this.Ze=void 0}}}globalsForEvent(e){var n,i,r,a,o,s,l;if(!e)throw new Error("Event payload is required");var c={},u=this._instance.get_property("$groups")||[],f=this._instance.get_property("$stored_group_properties")||{};for(var[h,g]of Object.entries(f))c[h]={id:u[h],type:h,properties:g};var{$set_once:_,$set:b}=e;return{event:j({},WC(e,r3),{properties:j({},e.properties,b?{$set:j({},(n=(i=e.properties)==null?void 0:i.$set)!==null&&n!==void 0?n:{},b)}:{},_?{$set_once:j({},(r=(a=e.properties)==null?void 0:a.$set_once)!==null&&r!==void 0?r:{},_)}:{}),elements_chain:(o=(s=e.properties)==null?void 0:s.$elements_chain)!==null&&o!==void 0?o:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:c}}setupSiteApp(e){var n=this.apps[e.id],i=()=>{var s;!n.errored&&this.Xe.length&&(Yr.info("Processing "+this.Xe.length+" events for site app with id "+e.id),this.Xe.forEach((l=>n.processEvent==null?void 0:n.processEvent(l))),n.processedBuffer=!0),Object.values(this.apps).every((l=>l.processedBuffer||l.errored))&&((s=this.Ze)==null||s.call(this))},r=!1,a=s=>{n.errored=!s,n.loaded=!0,Yr.info("Site app with id "+e.id+" "+(s?"loaded":"errored")),r&&i()};try{var{processEvent:o}=e.init({posthog:this._instance,callback:s=>{a(s)}});o&&(n.processEvent=o),r=!0}catch(s){Yr.error("Error while initializing PostHog app with config id "+e.id,s),a(!1)}if(r&&n.loaded)try{i()}catch(s){Yr.error("Error while processing buffered events PostHog app with config id "+e.id,s),n.errored=!0}}tr(){var e=this.siteAppLoaders||[];for(var n of e)this.apps[n.id]={id:n.id,loaded:!1,errored:!1,processedBuffer:!1};for(var i of e)this.setupSiteApp(i)}ir(e){if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(e);for(var i of Object.values(this.apps))try{i.processEvent==null||i.processEvent(n)}catch(r){Yr.error("Error while processing event "+e.event+" for site app "+i.id,r)}}}onRemoteConfig(e){var n,i,r,a=this;if((n=this.siteAppLoaders)!=null&&n.length)return this.isEnabled?(this.tr(),void this._instance.on("eventCaptured",(c=>this.ir(c)))):void Yr.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((i=this.Ze)==null||i.call(this),(r=e.siteApps)!=null&&r.length)if(this.isEnabled){var o=function(c){var u;J["__$$ph_site_app_"+c]=a._instance,(u=J.__PosthogExtensions__)==null||u.loadSiteApp==null||u.loadSiteApp(a._instance,l,(f=>{if(f)return Yr.error("Error while initializing PostHog app with config id "+c,f)}))};for(var{id:s,url:l}of e.siteApps)o(s)}else Yr.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},QA=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&rC(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>rC(r?.brand,e))))return!0}catch{}return!!t.webdriver},_c=(function(t){return t.US="us",t.EU="eu",t.CUSTOM="custom",t})({}),qC="i.posthog.com",Sy=class{constructor(e){this.er={},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,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+qC,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.er[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.er[this.apiHost]=_c.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.er[this.apiHost]=_c.EU:this.er[this.apiHost]=_c.CUSTOM),this.er[this.apiHost]}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(this.region===_c.CUSTOM)return this.apiHost+n;var i=qC+n;switch(e){case"assets":return"https://"+this.region+"-assets."+i;case"api":return"https://"+this.region+"."+i}}},a3={icontains:(t,e)=>!!R&&e.href.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>!!R&&e.href.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>!!R&&Bf(e.href,t),not_regex:(t,e)=>!!R&&!Bf(e.href,t),exact:(t,e)=>e.href===t,is_not:(t,e)=>e.href!==t},xy=class t{constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{t.rr("retrieved web experiments from the server"),n.sr=new Map,r.forEach((a=>{if(a.feature_flag_key){var o;n.sr&&(t.rr("setting flag key ",a.feature_flag_key," to web experiment ",a),(o=n.sr)==null||o.set(a.feature_flag_key,a));var s=n._instance.getFeatureFlag(a.feature_flag_key);ot(s)&&a.variants[s]&&n.nr(a.name,s,a.variants[s].transforms)}else if(a.variants)for(var l in a.variants){var c=a.variants[l];t.ar(c)&&n.nr(a.name,l,c.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}onFeatureFlags(e){if(this._is_bot())t.rr("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(Ee(this.sr))return this.sr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();t.rr("applying feature flags",e),e.forEach((n=>{var i;if(this.sr&&(i=this.sr)!=null&&i.has(n)){var r,a=this._instance.getFeatureFlag(n),o=(r=this.sr)==null?void 0:r.get(n);a&&o!=null&&o.variants[a]&&this.nr(o.name,a,o.variants[a].transforms)}}))}}previewWebExperiment(){var e=t.getWindowLocation();if(e!=null&&e.search){var n=Mf(e?.search,"__experiment_id"),i=Mf(e?.search,"__experiment_variant");n&&i&&(t.rr("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.lr(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this._instance.config.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:a=>{if(a.statusCode!==200||!a.json)return e([]);var o=a.json.experiments||[];return e(o)}})}lr(e,n,i){var r=i.filter((a=>a.id===e));r&&r.length>0&&(t.rr("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.nr(r[0].name,n,r[0].variants[n].transforms))}static ar(e){return!Ee(e.conditions)&&t.ur(e)&&t.hr(e)}static ur(e){var n;if(Ee(e.conditions)||Ee((n=e.conditions)==null?void 0:n.url))return!0;var i,r,a,o=t.getWindowLocation();return!!o&&((i=e.conditions)==null||!i.url||a3[(r=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&r!==void 0?r:"icontains"](e.conditions.url,o))}static getWindowLocation(){return R?.location}static hr(e){var n;if(Ee(e.conditions)||Ee((n=e.conditions)==null?void 0:n.utm))return!0;var i=BA();if(i.utm_source){var r,a,o,s,l,c,u,f,h=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_campaign)==i.utm_campaign,g=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_source)==i.utm_source,_=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((c=e.conditions)==null||(c=c.utm)==null?void 0:c.utm_medium)==i.utm_medium,b=(u=e.conditions)==null||(u=u.utm)==null||!u.utm_term||((f=e.conditions)==null||(f=f.utm)==null?void 0:f.utm_term)==i.utm_term;return h&&_&&b&&g}return!1}static rr(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];$.info("[WebExperiments] "+e,i)}nr(e,n,i){this._is_bot()?t.rr("Refusing to render web experiment since the viewer is a likely bot"):n!=="control"?i.forEach((r=>{if(r.selector){var a;t.rr("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(a=document)==null?void 0:a.querySelectorAll(r.selector);o?.forEach((s=>{var l=s;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):t.rr("Control variants leave the page unmodified.")}_is_bot(){return dn&&this._instance?QA(dn,this._instance.config.custom_blocked_useragents):void 0}},o3=st("[PostHog ExternalIntegrations]"),s3={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},wy=class{constructor(e){this._instance=e}it(e,n){var i;(i=J.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return o3.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(o){var s,l,c;!r||(s=J.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[o]||e.it(s3[o],(()=>{var u;(u=J.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[o])==null||u.start(e._instance)})),!r&&(l=J.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[o]&&((c=J.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[o])==null||c.stop())};for(var[i,r]of Object.entries((a=this._instance.config.integrations)!==null&&a!==void 0?a:{})){var a;n(i)}}},Ey="[SessionRecording]",pc=st(Ey),Uf=class{get started(){var e;return!((e=this.vr)==null||!e.isStarted)}get status(){return this.vr?this.vr.status:this.dr&&!this.cr?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.dr=!1,this.pr=void 0,this._instance=e,!this._instance.sessionManager)throw pc.error("started without valid sessionManager"),new Error(Ey+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(Ey+' cannot be used with cookieless_mode="always"')}get cr(){var e,n=!((e=this._instance.get_property(rv))==null||!e.enabled),i=!this._instance.config.disable_session_recording,r=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return R&&n&&i&&!r}startIfEnabledOrStop(e){var n;if(!this.cr||(n=this.vr)==null||!n.isStarted){var i=!I(Object.assign)&&!I(Array.from);this.cr&&i?(this.gr(e),pc.info("starting")):this.stopRecording()}}gr(e){var n,i,r;this.cr&&(J!=null&&(n=J.__PosthogExtensions__)!=null&&(n=n.rrweb)!=null&&n.record&&(i=J.__PosthogExtensions__)!=null&&i.initSessionRecording?this._r(e):(r=J.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.mr,(a=>{if(a)return pc.error("could not load recorder",a);this._r(e)})))}stopRecording(){var e,n;(e=this.pr)==null||e.call(this),this.pr=void 0,(n=this.vr)==null||n.stop()}yr(){var e;(e=this._instance.persistence)==null||e.unregister(aA)}br(e){if(this._instance.persistence){var n,i,r=this._instance.persistence,a=()=>{var o=e.sessionRecording===!1?void 0:e.sessionRecording,s=o?.sampleRate,l=Ee(s)?null:parseFloat(s);Ee(l)&&this.yr();var c=o?.minimumDurationMilliseconds;r.register({[rv]:j({enabled:!!o},o,{networkPayloadCapture:j({capturePerformance:e.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:I(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers})})};a(),(n=this.pr)==null||n.call(this),this.pr=(i=this._instance.sessionManager)==null?void 0:i.onSessionId(a)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.br(e),this.dr=!0,this.startIfEnabledOrStop()):this.dr=!0:pc.info("skipping remote config with no sessionRecording",e)}log(e,n){var i;n===void 0&&(n="log"),(i=this.vr)!=null&&i.log?this.vr.log(e,n):pc.warn("log called before recorder was ready")}get mr(){var e,n,i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(rv);return(i==null||(n=i.scriptConfig)==null?void 0:n.script)||"lazy-recorder"}_r(e){var n,i;if((n=J.__PosthogExtensions__)==null||!n.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.vr||(this.vr=(i=J.__PosthogExtensions__)==null?void 0:i.initSessionRecording(this._instance),this.vr._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.vr.start(e)}onRRwebEmit(e){var n;(n=this.vr)==null||n.onRRwebEmit==null||n.onRRwebEmit(e)}overrideLinkedFlag(){var e,n;this.vr||(n=this._instance.persistence)==null||n.register({$replay_override_linked_flag:!0}),(e=this.vr)==null||e.overrideLinkedFlag()}overrideSampling(){var e,n;this.vr||(n=this._instance.persistence)==null||n.register({$replay_override_sampling:!0}),(e=this.vr)==null||e.overrideSampling()}overrideTrigger(e){var n,i;this.vr||(i=this._instance.persistence)==null||i.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(n=this.vr)==null||n.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.vr)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,n){var i;return!((i=this.vr)==null||!i.tryAddCustomEvent(e,n))}},wc={},Cy=()=>{},xs="posthog",JA=!WL&&Zt?.indexOf("MSIE")===-1&&Zt?.indexOf("Mozilla")===-1,PC=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:tL(B?.location),persistence:"localStorage+cookie",persistence_name:"",loaded:Cy,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:Yt&&ot(Yt?.search)&&Yt.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_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(R==null||(e=R.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:n=>{var i="Bad HTTP status: "+n.statusCode+" "+n.text;$.error(i)},get_device_id:n=>n,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:my},error_tracking:{},_onCapture:Cy,__preview_eager_load_replay:!1},(n=>({rageclick:!(n&&n>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(n&&n>="2025-05-24")||"history_change",session_recording:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{}}))(t))},GC=t=>{var e={};I(t.process_person)||(e.person_profiles=t.process_person),I(t.xhr_headers)||(e.request_headers=t.xhr_headers),I(t.cookie_name)||(e.persistence_name=t.cookie_name),I(t.disable_cookie)||(e.disable_persistence=t.disable_cookie),I(t.store_google)||(e.save_campaign_params=t.store_google),I(t.verbose)||(e.debug=t.verbose);var n=Ye({},e,t);return Ae(t.property_blacklist)&&(I(t.property_denylist)?n.property_denylist=t.property_blacklist:Ae(t.property_denylist)?n.property_denylist=[...t.property_blacklist,...t.property_denylist]:$.error("Invalid value for property_denylist config: "+t.property_denylist)),n},Ay=class{constructor(){this.__forceAllowLocalhost=!1}get wr(){return this.__forceAllowLocalhost}set wr(e){$.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},Vf=class t{get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new Ay,this.Sr=!1,this.version=Gi.LIB_VERSION,this.Er=new Rc,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=PC(),this.SentryIntegration=Wv,this.sentryIntegration=e=>(function(n,i){var r=SA(n,i);return{name:_A,processEvent:a=>r(a)}})(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.$r=!1,this.kr=null,this.Pr=null,this.Tr=null,this.featureFlags=new cy(this),this.toolbar=new Kv(this),this.scrollManager=new by(this),this.pageViewManager=new iy(this),this.surveys=new py(this),this.experiments=new xy(this),this.exceptions=new ly(this),this.rateLimiter=new hy(this),this.requestRouter=new Sy(this),this.consent=new Gv(this),this.externalIntegrations=new wy(this),this.people={set:(e,n,i)=>{var r=ot(e)?{[e]:n}:e;this.setPersonProperties(r),i?.({})},set_once:(e,n,i)=>{var r=ot(e)?{[e]:n}:e;this.setPersonProperties(void 0,r),i?.({})}},this.on("eventCaptured",(e=>$.info('send "'+e?.event+'"',e)))}init(e,n,i){if(i&&i!==xs){var r,a=(r=wc[i])!==null&&r!==void 0?r:new t;return a._init(e,n,i),wc[i]=a,wc[xs][i]=a,a}return this._init(e,n,i)}_init(e,n,i){var r;if(n===void 0&&(n={}),I(e)||_v(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={},n.debug=this.Rr(n.debug),this.Ir=n,this.Fr=[],n.person_profiles&&(this.Pr=n.person_profiles),this.set_config(Ye({},PC(n.defaults),GC(n),{name:i,token:e})),this.config.on_xhr_error&&$.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Wi.GZipJS;var a=this.Cr();this.persistence=new xc(this.config,a),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xc(j({},this.config,{persistence:"sessionStorage"}),a);var o=j({},this.persistence.props),s=j({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Mr=new vy((p=>this.Or(p)),this.config.request_queue_config),this.Ar=new yy(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 Ff(this),this.sessionPropsManager=new $f(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?($.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Dr(l)}),0)):($.info("Initializing extensions synchronously"),this.Dr(l)),Gi.DEBUG=Gi.DEBUG||this.config.debug,Gi.DEBUG&&$.info("Starting in debug mode",{this:this,config:n,thisC:j({},this.config),p:o,s}),((r=n.bootstrap)==null?void 0:r.distinctID)!==void 0){var c,u,f=this.config.get_device_id(Kr()),h=(c=n.bootstrap)!=null&&c.isIdentifiedID?f:n.bootstrap.distinctID;this.persistence.set_property(Zi,(u=n.bootstrap)!=null&&u.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:n.bootstrap.distinctID,$device_id:h})}if(this.jr()){var g,_,b=Object.keys(((g=n.bootstrap)==null?void 0:g.featureFlags)||{}).filter((p=>{var m;return!((m=n.bootstrap)==null||(m=m.featureFlags)==null||!m[p])})).reduce(((p,m)=>{var v;return p[m]=((v=n.bootstrap)==null||(v=v.featureFlags)==null?void 0:v[m])||!1,p}),{}),w=Object.keys(((_=n.bootstrap)==null?void 0:_.featureFlagPayloads)||{}).filter((p=>b[p])).reduce(((p,m)=>{var v,S;return(v=n.bootstrap)!=null&&(v=v.featureFlagPayloads)!=null&&v[m]&&(p[m]=(S=n.bootstrap)==null||(S=S.featureFlagPayloads)==null?void 0:S[m]),p}),{});this.featureFlags.receivedFeatureFlags({featureFlags:b,featureFlagPayloads:w})}if(l)this.register_once({distinct_id:ac,$device_id:null},"");else if(!this.get_distinct_id()){var d=this.config.get_device_id(Kr());this.register_once({distinct_id:d,$device_id:d},""),this.persistence.set_property(Zi,"anonymous")}return tt(R,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),n.segment?wL(this,(()=>this.Lr())):this.Lr(),Xr(this.config._onCapture)&&this.config._onCapture!==Cy&&($.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(p=>this.config._onCapture(p.event,p)))),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}Dr(e){var n=performance.now();this.historyAutocapture=new Yv(this),this.historyAutocapture.startIfEnabled();var i=[];i.push((()=>{new Xv(this).startIfEnabledOrStop()})),i.push((()=>{var r;this.siteApps=new _y(this),(r=this.siteApps)==null||r.init()})),e||i.push((()=>{this.sessionRecording=new Uf(this),this.sessionRecording.startIfEnabledOrStop()})),this.config.disable_scroll_properties||i.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),i.push((()=>{this.autocapture=new Vv(this),this.autocapture.startIfEnabled()})),i.push((()=>{this.surveys.loadIfEnabled()})),i.push((()=>{this.heatmaps=new ny(this),this.heatmaps.startIfEnabled()})),i.push((()=>{this.webVitalsAutocapture=new ty(this)})),i.push((()=>{this.exceptionObserver=new Zv(this),this.exceptionObserver.startIfEnabled()})),i.push((()=>{this.deadClicksAutocapture=new Df(this,xL),this.deadClicksAutocapture.startIfEnabled()})),i.push((()=>{if(this.Nr){var r=this.Nr;this.Nr=void 0,this.fi(r)}})),this.Ur(i,n)}Ur(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.Ur(e,n)}),0);var i=e.shift();if(i)try{i()}catch(a){$.error("Error initializing extension:",a)}}var r=Math.round(performance.now()-n);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:r}),this.config.__preview_deferred_init_extensions&&$.info("PostHog extensions initialized ("+r+"ms)")}fi(e){var n,i,r,a,o,s,l,c;if(!B||!B.body)return $.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.fi(e)}),500);this.config.__preview_deferred_init_extensions&&(this.Nr=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=ue(e.supportedCompression,Wi.GZipJS)?Wi.GZipJS:ue(e.supportedCompression,Wi.Base64)?Wi.Base64:void 0),(n=e.analytics)!=null&&n.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Pr?this.Pr:"identified_only"}),(i=this.siteApps)==null||i.onRemoteConfig(e),(r=this.sessionRecording)==null||r.onRemoteConfig(e),(a=this.autocapture)==null||a.onRemoteConfig(e),(o=this.heatmaps)==null||o.onRemoteConfig(e),this.surveys.onRemoteConfig(e),(s=this.webVitalsAutocapture)==null||s.onRemoteConfig(e),(l=this.exceptionObserver)==null||l.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(c=this.deadClicksAutocapture)==null||c.onRemoteConfig(e)}Lr(){try{this.config.loaded(this)}catch(e){$.critical("`loaded` function failed",e)}this.zr(),this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.Hr()}),1),new gy(this).load(),this.featureFlags.flags()}zr(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.Mr)==null||e.enable())}_dom_loaded(){this.is_capturing()&&Jr(this.__request_queue,(e=>this.Or(e))),this.__request_queue=[],this.zr()}_handle_unload(){var e,n;this.config.request_batching?(this.Br()&&this.capture("$pageleave"),(e=this.Mr)==null||e.unload(),(n=this.Ar)==null||n.unload()):this.Br()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}ci(e){this.__loaded&&(JA?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=zf(e.url,{ip:this.config.ip?1:0}),e.headers=j({},this.config.request_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,(n=>{var i,r,a,o=j({},n);o.timeout=o.timeout||6e4,o.url=zf(o.url,{_:new Date().getTime().toString(),ver:Gi.LIB_VERSION,compression:o.compression});var s=(i=o.transport)!==null&&i!==void 0?i:"fetch",l=_f.filter((u=>!o.disableTransport||!u.transport||!o.disableTransport.includes(u.transport))),c=(r=(a=nA(l,(u=>u.transport===s)))==null?void 0:a.method)!==null&&r!==void 0?r:l[0].method;if(!c)throw new Error("No available transport method");c(o)})(j({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),n.statusCode>=400&&((i=(r=this.config).on_request_error)==null||i.call(r,n)),e.callback==null||e.callback(n)}}))))}Or(e){this.Ar?this.Ar.retriableRequest(e):this.ci(e)}_execute_array(e){var n,i=[],r=[],a=[];Jr(e,(s=>{s&&(n=s[0],Ae(n)?a.push(s):Xr(s)?s.call(this):Ae(s)&&n==="alias"?i.push(s):Ae(s)&&n.indexOf("capture")!==-1&&Xr(this[n])?a.push(s):r.push(s))}));var o=function(s,l){Jr(s,(function(c){if(Ae(c[0])){var u=l;Re(c,(function(f){u=u[f[0]].apply(u,f.slice(1))}))}else this[c[0]].apply(this,c.slice(1))}),l)};o(i,this),o(r,this),o(a,this)}jr(){var e,n;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((n=this.config.bootstrap)==null?void 0:n.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,n,i){var r;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Mr){if(this.is_capturing())if(!I(e)&&ot(e)){var a=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(a&&!this.config.__preview_capture_bot_pageviews)){var o=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(o==null||!o.isRateLimited){n!=null&&n.$current_url&&!ot(n?.$current_url)&&($.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$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=i?.timestamp||s,c=Kr(),u={uuid:c,event:e,properties:this.calculateEventProperties(e,n||{},l,c)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&a&&(u.event="$bot_pageview",u.properties.$browser_type="bot"),o&&(u.properties.$lib_rate_limit_remaining_tokens=o.remainingTokens),i?.$set&&(u.$set=i?.$set);var f,h=this.qr(i?.$set_once);if(h&&(u.$set_once=h),(u=J4(u,i!=null&&i._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,I(i?.timestamp)||(u.properties.$event_time_override_provided=!0,u.properties.$event_time_override_system_time=s),e===Sf.DISMISSED||e===Sf.SENT){var g=n?.[UC.SURVEY_ID],_=n?.[UC.SURVEY_ITERATION];f={id:g,current_iteration:_},localStorage.getItem(VC(f))||localStorage.setItem(VC(f),"true"),u.$set=j({},u.$set,{[JL({id:g,current_iteration:_},e===Sf.SENT?"responded":"dismissed")]:!0})}var b=j({},u.properties.$set,u.$set);if(ws(b)||this.setPersonPropertiesForFlags(b),!Ee(this.config.before_send)){var w=this.Wr(u);if(!w)return;u=w}this.Er.emit("eventCaptured",u);var d={method:"POST",url:(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:u,compression:"best-available",batchKey:i?._batchKey};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Or(d):this.Mr.enqueue(d),u}$.critical("This capture call is ignored due to client rate limiting.")}}else $.error("No event name provided to posthog.capture")}else $.uninitializedWarning("posthog.capture")}Ai(e){return this.on("eventCaptured",(n=>e(n.event,n)))}calculateEventProperties(e,n,i,r,a){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=a?void 0:this.persistence.remove_event_timer(e),s=j({},n);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,(!ot(s.distinct_id)&&!di(s.distinct_id)||_v(s.distinct_id))&&$.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),s}var c,u=$L(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:f,windowId:h}=this.sessionManager.checkAndGetSessionAndWindowId(a,i.getTime());s.$session_id=f,s.$window_id=h}this.sessionPropsManager&&Ye(s,this.sessionPropsManager.getSessionProps());try{var g;this.sessionRecording&&Ye(s,this.sessionRecording.sdkDebugProperties),s.$sdk_debug_retry_queue_size=(g=this.Ar)==null?void 0:g.length}catch(d){s.$sdk_debug_error_capturing_properties=String(d)}if(this.requestRouter.region===_c.CUSTOM&&(s.$lib_custom_api_host=this.config.api_host),c=e!=="$pageview"||a?e!=="$pageleave"||a?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),s=Ye(s,c),e==="$pageview"&&B&&(s.title=B.title),!I(o)){var _=i.getTime()-o;s.$duration=parseFloat((_/1e3).toFixed(3))}Zt&&this.config.opt_out_useragent_filter&&(s.$browser_type=this._is_bot()?"bot":"browser"),(s=Ye({},u,this.persistence.properties(),this.sessionPersistence.properties(),s)).$is_identified=this._isIdentified(),Ae(this.config.property_denylist)?Re(this.config.property_denylist,(function(d){delete s[d]})):$.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&($.error("sanitize_properties is deprecated. Use before_send instead"),s=b(s,e));var w=this.Gr();return s.$process_person_profile=w,w&&!a&&this.Vr("_calculate_event_properties"),s}qr(e){var n;if(!this.persistence||!this.Gr()||this.Sr)return e;var i=this.persistence.get_initial_props(),r=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),a=Ye({},i,r||{},e||{}),o=this.config.sanitize_properties;return o&&($.error("sanitize_properties is deprecated. Use before_send instead"),a=o(a,"$set_once")),this.Sr=!0,ws(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e)}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e)}Jr(e,n){this.register({[e]:n})}getFeatureFlag(e,n){return this.featureFlags.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n=this.featureFlags.getFeatureFlagPayload(e);try{return JSON.parse(n)}catch{return n}}isFeatureEnabled(e,n){return this.featureFlags.isFeatureEnabled(e,n)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateEarlyAccessFeatureEnrollment(e,n,i){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){return n===void 0&&(n=!1),this.featureFlags.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.Er.on(e,n)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys.getSurveys(e,n)}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys.getActiveMatchingSurveys(e,n)}renderSurvey(e,n){this.surveys.renderSurvey(e,n)}displaySurvey(e,n){n===void 0&&(n=t3),this.surveys.displaySurvey(e,n)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,n){return n===void 0&&(n=!1),this.surveys.canRenderSurveyAsync(e,n)}identify(e,n,i){if(!this.__loaded||!this.persistence)return $.uninitializedWarning("posthog.identify");if(di(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!==ac){if(this.Vr("posthog.identify")){var r=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var a=r;this.register_once({$had_persisted_distinct_id:!0,$device_id:a},"")}e!==r&&e!==this.get_property(hc)&&(this.unregister(hc),this.register({distinct_id:e}));var o=(this.persistence.get_property(Zi)||"anonymous")==="anonymous";e!==r&&o?(this.persistence.set_property(Zi,"identified"),this.setPersonPropertiesForFlags(j({},i||{},n||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Tr=IC(e,n,i),this.featureFlags.setAnonymousDistinctId(r)):(n||i)&&this.setPersonProperties(n,i),e!==r&&(this.reloadFeatureFlags(),this.unregister(Cf))}}else $.critical('The string "'+ac+'" 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,n){if((e||n)&&this.Vr("posthog.setPersonProperties")){var i=IC(this.get_distinct_id(),e,n);this.Tr!==i?(this.setPersonPropertiesForFlags(j({},n||{},e||{})),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Tr=i):$.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,n,i){if(e&&n){if(this.Vr("posthog.group")){var r=this.getGroups();r[e]!==n&&this.resetGroupPropertiesForFlags(e),this.register({$groups:j({},r,{[e]:n})}),i&&(this.capture("$groupidentify",{$group_type:e,$group_key:n,$group_set:i}),this.setGroupPropertiesForFlags({[e]:i})),r[e]===n||i||this.reloadFeatureFlags()}}else $.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){n===void 0&&(n=!0),this.featureFlags.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,n){n===void 0&&(n=!0),this.Vr("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,n)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var n,i,r,a;if($.info("reset"),!this.__loaded)return $.uninitializedWarning("posthog.reset");var o=this.get_property("$device_id");if(this.consent.reset(),(n=this.persistence)==null||n.clear(),(i=this.sessionPersistence)==null||i.clear(),this.surveys.reset(),this.featureFlags.reset(),(r=this.persistence)==null||r.set_property(Zi,"anonymous"),(a=this.sessionManager)==null||a.resetSessionId(),this.Tr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:ac,$device_id:null},"");else{var s=this.config.get_device_id(Kr());this.register_once({distinct_id:s,$device_id:e?s:o},"")}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,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:n,sessionStartTimestamp:i}=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n);if(e!=null&&e.withTimestamp&&i){var a,o=(a=e.timestampLookBack)!==null&&a!==void 0?a:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(iA)?($.critical("Attempting to create alias for existing People user - aborting."),-2):this.Vr("posthog.alias")?(I(n)&&(n=this.get_distinct_id()),e!==n?(this.Jr(hc,e),this.capture("$create_alias",{alias:e,distinct_id:n})):($.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=j({},this.config);if(ft(e)){var i,r,a,o,s;Ye(this.config,GC(e));var l=this.Cr();(i=this.persistence)==null||i.update_config(this.config,n,l),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xc(j({},this.config,{persistence:"sessionStorage"}),l);var c=this.Rr(this.config.debug);Qr(c)&&(this.config.debug=c),Qr(this.config.debug)&&(this.config.debug?(Gi.DEBUG=!0,Ue.H()&&Ue.G("ph_debug","true"),$.info("set_config",{config:e,oldConfig:n,newConfig:j({},this.config)})):(Gi.DEBUG=!1,Ue.H()&&Ue.V("ph_debug"))),(r=this.sessionRecording)==null||r.startIfEnabledOrStop(),(a=this.autocapture)==null||a.startIfEnabled(),(o=this.heatmaps)==null||o.startIfEnabled(),this.surveys.loadIfEnabled(),this.Kr(),(s=this.externalIntegrations)==null||s.startIfEnabledOrStop()}}startSessionRecording(e){var n=e===!0,i={sampling:n||!(e==null||!e.sampling),linked_flag:n||!(e==null||!e.linked_flag),url_trigger:n||!(e==null||!e.url_trigger),event_trigger:n||!(e==null||!e.event_trigger)};if(Object.values(i).some(Boolean)){var r,a,o,s,l;(r=this.sessionManager)==null||r.checkAndGetSessionAndWindowId(),i.sampling&&((a=this.sessionRecording)==null||a.overrideSampling()),i.linked_flag&&((o=this.sessionRecording)==null||o.overrideLinkedFlag()),i.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),i.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,n){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(j({},r,n))}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:xs;return n!==xs&&(n=xs+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(Zi))==="identified"||((n=this.sessionPersistence)==null?void 0:n.get_property(Zi))==="identified"}Gr(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&ws(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[hc])&&((n=this.persistence)==null||(n=n.props)==null||!n[Tf]))}Br(){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.Gr()||this.Vr("posthog.createPersonProfile")&&this.setPersonProperties({},{})}Vr(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.Jr(Tf,!0),!0)}Cr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),n=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!n}Kr(){var e,n,i,r,a=this.Cr();return((e=this.persistence)==null?void 0:e.wi)!==a&&((i=this.persistence)==null||i.set_disabled(a)),((n=this.sessionPersistence)==null?void 0:n.wi)!==a&&((r=this.sessionPersistence)==null||r.set_disabled(a)),a}opt_in_capturing(e){var n;if(this.config.cookieless_mode!=="always"){var i,r;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(i=this.sessionManager)==null||i.destroy(),this.sessionManager=new Ff(this),this.persistence&&(this.sessionPropsManager=new $f(this,this.sessionManager,this.persistence)),this.sessionRecording=new Uf(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.Kr(),this.zr(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(I(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((r=e?.captureEventName)!==null&&r!==void 0?r:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hr()}else $.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,n;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.Kr(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:ac,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(n=this.sessionRecording)==null||n.stopRecording(),this.sessionRecording=void 0,this.Hr())):$.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===Yi.GRANTED?"granted":e===Yi.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.Kr()}_is_bot(){return dn?QA(dn,this.config.custom_blocked_useragents):void 0}Hr(){B&&(B.visibilityState==="visible"?this.$r||(this.$r=!0,this.capture("$pageview",{title:B.title},{send_instantly:!0}),this.kr&&(B.removeEventListener("visibilitychange",this.kr),this.kr=null)):this.kr||(this.kr=this.Hr.bind(this),tt(B,"visibilitychange",this.kr)))}debug(e){e===!1?(R?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(R?.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}))}O(){var e,n,i,r,a,o,s,l=this.Ir||{};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):(i="advanced_disable_decide",r=!1,a=$,o=(n="advanced_disable_flags")in(e=l)&&!I(e[n]),s=i in e&&!I(e[i]),o?e[n]:s?(a&&a.warn("Config field '"+i+"' is deprecated. Please use '"+n+"' instead. The old field will be removed in a future major version."),e[i]):r)}Wr(e){if(Ee(this.config.before_send))return e;var n=Ae(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var r of n){if(i=r(i),Ee(i)){var a="Event '"+e.event+"' was rejected in beforeSend function";return I4(e.event)?$.warn(a+". This can cause unexpected behavior."):$.info(a),null}i.properties&&!ws(i.properties)||$.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return i}getPageViewId(){var e;return(e=this.pageViewManager.Vt)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Rr(e){var n=Qr(e)&&!e,i=Ue.H()&&Ue.q("ph_debug")==="true";return!n&&(!!i||e)}};(function(t,e){for(var n=0;n<e.length;n++)t.prototype[e[n]]=Q4(t.prototype[e[n]])})(Vf,["identify"]);var ZC,eT=(ZC=wc[xs]=new Vf,(function(){function t(){t.done||(t.done=!0,JA=!1,Re(wc,(function(e){e._dom_loaded()})))}B!=null&&B.addEventListener?B.readyState==="complete"?t():tt(B,"DOMContentLoaded",t,{capture:!1}):R&&$.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),ZC);var zy=class{constructor(e={}){this.options=e;V(this,"client");V(this,"featureFlagsCallback");V(this,"captureCallback");V(this,"consentUnsub");if(this.client=e.client,this.featureFlagsCallback=e.onFeatureFlagsLoaded,this.captureCallback=e.onCapture,!this.client&&e.consent&&e.requireExplicitConsent&&typeof window<"u"&&e.apiKey){let n=e.consent;n.getStatus()==="granted"&&this.initPostHog(),this.consentUnsub=n.subscribe(r=>{r==="granted"?this.client?this.client.opt_in_capturing():this.initPostHog():r==="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 n=e.enableFeatureFlags??!0,i=`syntro_${e.apiKey.slice(-6)||"sdk"}`;this.client=eT.init(e.apiKey,{api_host:e.apiHost??"https://telemetry.syntrologie.com",advanced_disable_feature_flags:!n,advanced_disable_feature_flags_on_first_load:!n,autocapture:e.autocapture??!0,capture_pageview:e.capturePageview??!0,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,loaded:r=>{if(n&&this.featureFlagsCallback){r.onFeatureFlags(()=>{let o=this.getAllFeatureFlags();o&&this.featureFlagsCallback&&this.featureFlagsCallback(o)});let a=this.getAllFeatureFlags();a&&Object.keys(a).length>0&&this.featureFlagsCallback(a)}this.captureCallback&&r.on("eventCaptured",a=>{let o=typeof a=="string"?a:a?.event,s=typeof a=="string"?void 0:a?.properties;typeof o=="string"&&this.captureCallback?.(o,s)})}},i)}getAllFeatureFlags(){return this.client?.featureFlags?.getFlagVariants?.()}getSegmentFlags(){let e=this.getAllFeatureFlags();if(!e)return{};let n={};for(let[i,r]of Object.entries(e))i.startsWith("in_segment_")&&(n[i]=r===!0);return n}identify(e,n){this.client?.identify(e,n)}alias(e,n){this.client?.alias(e,n)}track(e,n){this.client?.capture(e,n)}trackCanvasOpened(e){this.track("shadow_canvas_opened",{surface:e})}trackCanvasClosed(e){this.track("shadow_canvas_closed",{surface:e})}trackRectangleViewed(e,n){this.track("shadow_canvas_rectangle_viewed",{rectangleId:e,surface:n})}trackAction(e,n,i){this.track("shadow_canvas_action",{action:e,rectangleId:n,surface:i})}register(e){this.client?.register?.(e)}getSessionId(){return this.client?.get_session_id?.()}startSessionRecording(){this.client?.startSessionRecording?.()}trackExperiment(e,n,i){let r=`$experiment_${e}`;this.register({[r]:i??`variation_${n}`,[`${r}_id`]:n}),this.track("$experiment_started",{$experiment_key:e,$experiment_variation_id:n,$experiment_variation_name:i??`variation_${n}`})}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 By(t={}){return new zy(t)}var $y=async(t,e)=>{let n=[];if(e.applyAction)for(let i of t.actions){let r=await e.applyAction(i);n.push(r)}return{cleanup:async()=>{for(let i=n.length-1;i>=0;i--)try{await n[i].revert()}catch{}}}},Fy=async(t,e)=>{let n=[];if(e.applyAction){let i=t.actions.map(r=>e.applyAction(r));if(t.waitFor==="any"){let r=await Promise.race(i);n.push(r);let a=await Promise.allSettled(i);for(let o of a)o.status==="fulfilled"&&o.value!==r&&n.push(o.value)}else{let r=await Promise.all(i);n.push(...r)}}return{cleanup:async()=>{for(let i of n)try{await i.revert()}catch{}}}},Uy=async(t,e)=>{let n,i,r=!1,a={cleanup:()=>{r=!0,i&&clearTimeout(i),n&&n()}};return t.event&&e.subscribeEvent?await new Promise(o=>{n=e.subscribeEvent(t.event,()=>{r||o()}),t.durationMs!==void 0&&(i=setTimeout(()=>{r||o()},t.durationMs))}):t.durationMs!==void 0&&await new Promise(o=>{i=setTimeout(()=>{r||o()},t.durationMs)}),a};var jy="syntro_active_tour",Gf=new Map;function l3(t){try{let e=localStorage.getItem(jy);if(!e)return null;let n=JSON.parse(e);return n.tourId!==t?null:n}catch{return null}}function Vy(t){try{localStorage.setItem(jy,JSON.stringify(t))}catch{}}function c3(){try{localStorage.removeItem(jy)}catch{}}function Dc(){return window.location.pathname}function u3(t){if(!t.route)return!0;let e=Dc();return t.route.includes("*")?new RegExp(`^${t.route.replace(/\*/g,".*")}$`).test(e):e===t.route}var qy=async(t,e)=>{let{tourId:n,steps:i,startStep:r,autoStart:a=!0}=t;if(i.length===0)throw new Error(`Tour "${n}" has no steps`);if(Gf.has(n))return{cleanup:async()=>{let m=Gf.get(n);m&&await m.cleanup()}};if(!e.applyAction)throw new Error("Tour executor requires applyAction in context");let o=l3(n),s=!!o;if(!s&&!a)return{cleanup:()=>{}};o||(o={tourId:n,currentStepId:r||i[0].id,startedAt:Date.now()},Vy(o));let l=i.findIndex(m=>m.id===o.currentStepId);if(l===-1){let m=r||i[0].id;l=i.findIndex(v=>v.id===m),l===-1&&(l=0),o.currentStepId=i[l].id,Vy(o)}let c=i[l];if(!u3(c))return e.publishEvent("tour.waiting_for_route",{tourId:n,stepId:c.id,expectedRoute:c.route,currentRoute:Dc()}),{cleanup:()=>{}};let u=!1,f=null,h=null,g=null,_=async()=>{h&&(h(),h=null),f?.isApplied()&&(await f.revert(),f=null)},b=async m=>{if(u)return;if(await _(),m==="end"){c3(),e.publishEvent("tour.completed",{tourId:n,totalSteps:i.length}),u=!0;return}let v=i.find(S=>S.id===m);if(!v){console.error(`[Tour] Step "${m}" not found`);return}if(o.currentStepId=m,Vy(o),e.publishEvent("tour.step_changed",{tourId:n,previousStepId:c.id,nextStepId:m}),v.route&&v.route!==Dc()){e.publishEvent("tour.awaiting_navigation",{tourId:n,stepId:m,targetRoute:v.route});return}await w(v)},w=async m=>{if(!u){e.publishEvent("tour.step_started",{tourId:n,stepId:m.id,stepIndex:i.findIndex(v=>v.id===m.id),totalSteps:i.length});try{f=await e.applyAction(m.action)}catch(v){console.error(`[Tour] Failed to execute step "${m.id}":`,v),e.publishEvent("tour.step_failed",{tourId:n,stepId:m.id,error:String(v)});return}if(m.onAction&&e.subscribeEvent){h=e.subscribeEvent("action.modal_cta_clicked",T=>{let A=T?.actionId;if(A&&m.onAction){let k=m.onAction[A];k&&b(k)}});let v=e.subscribeEvent("action.tooltip_cta_clicked",T=>{let A=T?.actionId;if(A&&m.onAction){let k=m.onAction[A];k&&b(k)}}),S=h;h=()=>{S(),v()}}}};g=(()=>{let m=Dc(),v=()=>{let A=Dc();A!==m&&(m=A,e.publishEvent("tour.route_changed",{tourId:n,newRoute:A}))};if(e.subscribeNavigation)return e.subscribeNavigation(()=>v());window.addEventListener("popstate",v);let S=history.pushState.bind(history),T=history.replaceState.bind(history);return history.pushState=(...A)=>{S(...A),queueMicrotask(v)},history.replaceState=(...A)=>{T(...A),queueMicrotask(v)},()=>{window.removeEventListener("popstate",v),history.pushState=S,history.replaceState=T}})(),s?e.publishEvent("tour.resumed",{tourId:n,stepId:o.currentStepId}):e.publishEvent("tour.started",{tourId:n,totalSteps:i.length,startStepId:o.currentStepId}),await w(c);let p=async()=>{u=!0,Gf.delete(n),await _(),g&&g(),e.publishEvent("tour.paused",{tourId:n,stepId:o.currentStepId})};return Gf.set(n,{cleanup:p}),{cleanup:p}};var Zf=class{constructor(){V(this,"executors",new Map);for(let{kind:e,executor:n}of Gg)this.registerCore(e,n);for(let{kind:e,executor:n}of Jg)this.registerCore(e,n);this.registerCore("core:mountWidget",async()=>{throw new Error("core:mountWidget must be handled by ActionEngine")}),this.registerCore("core:sequence",$y),this.registerCore("core:parallel",Fy),this.registerCore("core:wait",Uy),this.registerCore("core:tour",qy)}registerCore(e,n,i){this.executors.set(e,{kind:e,executor:n,schema:i,source:"core",isBuiltIn:!0})}register(e,n,i,r="custom",a=!1){if(this.executors.has(e)){if(this.executors.get(e).isBuiltIn)return;console.warn(`[ExecutorRegistry] Overriding executor for kind: ${e} (source: ${r})`)}console.log(`[ExecutorRegistry] Registered executor: ${e} (source: ${r})`),this.executors.set(e,{kind:e,executor:n,schema:i,source:r,isBuiltIn:a})}unregister(e){let n=this.executors.get(e);return n?n.isBuiltIn?(console.warn(`[ExecutorRegistry] Cannot unregister built-in executor: ${e}`),!1):(this.executors.delete(e),!0):!1}unregisterBySource(e){for(let[n,i]of this.executors.entries())i.source===e&&this.executors.delete(n)}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 n=[];if(!e||typeof e!="object")return n.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:n,warnings:[]};let{kind:i}=e;if(!i||typeof i!="string")return n.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:n,warnings:[]};let r=this.executors.get(i);if(!r)return n.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${i}`,field:"kind"}),{valid:!1,errors:n,warnings:[]};if(r.schema){let a=r.schema.safeParse(e);if(!a.success){for(let o of a.error.issues)n.push({code:"SCHEMA_VALIDATION_ERROR",message:o.message,field:o.path.join(".")});return{valid:!1,errors:n,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)}},Xi=new Zf;function d3(t){return Xi.get(t)}function Py(t){return Xi.has(t)}var f3=new Set(["onclick","onerror","onload","onmouseover","onfocus","onblur","onchange","onsubmit","onkeydown","onkeyup","onkeypress"]),tT=5e4,nT=50;function na(t){let e=[],n=[];if(!t||typeof t!="object")return e.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:e,warnings:n};let{kind:i}=t;if(!i||typeof i!="string")return e.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:e,warnings:n};if(!Py(i)&&i!=="core:mountWidget"){let r=Xi.list();return console.error(`[ActionValidation] Unknown action kind: "${i}". Registered kinds (${r.length}): [${r.join(", ")}]. This usually means the app that provides "${i}" hasn't been activated yet, or the executor was never registered in ExecutorRegistry.`),e.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${i}`,field:"kind"}),{valid:!1,errors:e,warnings:n}}switch(i){case"overlays:highlight":case"overlays:pulse":case"navigation:scrollTo":ta(t,e,n);break;case"overlays:badge":ta(t,e,n),p3(t,e,n);break;case"overlays:tooltip":ta(t,e,n),h3(t,e,n);break;case"overlays:modal":C3(t,e,n);break;case"content:insertHtml":ta(t,e,n),g3(t,e,n);break;case"content:setText":ta(t,e,n),m3(t,e,n);break;case"content:setAttr":ta(t,e,n),v3(t,e,n);break;case"content:addClass":case"content:removeClass":ta(t,e,n),y3(t,e,n);break;case"content:setStyle":ta(t,e,n),b3(t,e,n);break;case"core:mountWidget":_3(t,e,n);break;case"core:wait":S3(t,e,n);break;case"core:sequence":x3(t,e,n);break;case"core:parallel":w3(t,e,n);break;case"core:tour":A3(t,e,n);break;case"navigation:navigate":E3(t,e,n);break}return{valid:e.length===0,errors:e,warnings:n}}function ta(t,e,n){!t.anchorId||typeof t.anchorId!="string"?e.push({code:"MISSING_ANCHOR_ID",message:"Action requires an 'anchorId' property",field:"anchorId"}):t.anchorId.length>200&&n.push({code:"LONG_ANCHOR_ID",message:"Anchor ID is unusually long",suggestion:"Consider using a shorter, more descriptive ID"})}function p3(t,e,n){!t.content||typeof t.content!="string"?e.push({code:"MISSING_CONTENT",message:"Badge action requires 'content' property",field:"content"}):t.content.length>100&&n.push({code:"LONG_BADGE_CONTENT",message:"Badge content is quite long",suggestion:"Keep badge content short (under 100 characters)"})}function h3(t,e,n){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 g3(t,e,n){!t.html||typeof t.html!="string"?e.push({code:"MISSING_HTML",message:"insertHtml action requires 'html' property",field:"html"}):t.html.length>tT&&e.push({code:"HTML_TOO_LONG",message:`HTML content exceeds maximum length of ${tT}`,field:"html"});let i=["before","after","prepend","append","replace"];(!t.position||!i.includes(t.position))&&e.push({code:"INVALID_POSITION",message:`Position must be one of: ${i.join(", ")}`,field:"position"})}function m3(t,e,n){(t.text===void 0||t.text===null)&&e.push({code:"MISSING_TEXT",message:"setText action requires 'text' property",field:"text"})}function v3(t,e,n){!t.attr||typeof t.attr!="string"?e.push({code:"MISSING_ATTR",message:"setAttr action requires 'attr' property",field:"attr"}):(f3.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 y3(t,e,n){!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)||n.push({code:"INVALID_CLASS_NAME",message:"Class name contains unusual characters",suggestion:"Use alphanumeric characters, hyphens, and underscores"})}function b3(t,e,n){if(!t.styles||typeof t.styles!="object")e.push({code:"MISSING_STYLES",message:"setStyle action requires 'styles' object",field:"styles"});else{let i=Object.keys(t.styles).length;i>nT&&e.push({code:"TOO_MANY_STYLES",message:`Too many styles (${i}). Maximum is ${nT}`,field:"styles"});for(let[r,a]of Object.entries(t.styles))typeof a=="string"&&a.includes("expression(")&&e.push({code:"DANGEROUS_STYLE",message:`Style expressions are not allowed: ${r}`,field:`styles.${r}`})}}function _3(t,e,n){(!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 S3(t,e,n){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 x3(t,e,n){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&&n.push({code:"EMPTY_SEQUENCE",message:"sequence has no actions",suggestion:"Add at least one action to the sequence"});for(let i=0;i<t.actions.length;i++){let r=na(t.actions[i]);for(let a of r.errors)e.push({...a,field:`actions[${i}]${a.field?`.${a.field}`:""}`});for(let a of r.warnings)n.push(a)}}function w3(t,e,n){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&&n.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 i=0;i<t.actions.length;i++){let r=na(t.actions[i]);for(let a of r.errors)e.push({...a,field:`actions[${i}]${a.field?`.${a.field}`:""}`});for(let a of r.warnings)n.push(a)}}function E3(t,e,n){if(!t.url||typeof t.url!="string")e.push({code:"MISSING_URL",message:"navigate action requires 'url' property",field:"url"});else{let i=t.url.trim().toLowerCase();i.startsWith("javascript:")&&e.push({code:"DANGEROUS_URL",message:"javascript: URLs are not allowed",field:"url"}),i.startsWith("data:")&&n.push({code:"DATA_URL",message:"data: URLs may have limited support",suggestion:"Consider using a regular URL instead"})}}function C3(t,e,n){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 i=0;i<t.ctaButtons.length;i++){let r=t.ctaButtons[i];(!r.label||typeof r.label!="string")&&e.push({code:"MISSING_BUTTON_LABEL",message:`CTA button at index ${i} requires 'label' property`,field:`ctaButtons[${i}].label`}),(!r.actionId||typeof r.actionId!="string")&&e.push({code:"MISSING_BUTTON_ACTION_ID",message:`CTA button at index ${i} requires 'actionId' property`,field:`ctaButtons[${i}].actionId`})}}function A3(t,e,n){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 i=new Set;for(let r=0;r<t.steps.length;r++){let a=t.steps[r];if(!a.id||typeof a.id!="string"?e.push({code:"MISSING_STEP_ID",message:`Step at index ${r} requires 'id' property`,field:`steps[${r}].id`}):(i.has(a.id)&&e.push({code:"DUPLICATE_STEP_ID",message:`Duplicate step ID: ${a.id}`,field:`steps[${r}].id`}),i.add(a.id)),!a.action)e.push({code:"MISSING_STEP_ACTION",message:`Step at index ${r} requires 'action' property`,field:`steps[${r}].action`});else{let o=na(a.action);for(let s of o.errors)e.push({...s,field:`steps[${r}].action${s.field?`.${s.field}`:""}`});for(let s of o.warnings)n.push(s)}if(a.onAction)for(let[o,s]of Object.entries(a.onAction))s!=="end"&&!t.steps.some(l=>l.id===s)&&n.push({code:"UNKNOWN_TARGET_STEP",message:`Step "${a.id}" references unknown target step: ${s}`,suggestion:`Make sure step "${s}" exists in the tour`})}}function Gy(t){let e=[],n=[];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:n};for(let i=0;i<t.length;i++){let r=na(t[i]);if(!r.valid){let a=t[i];console.error(`[ActionValidation] Action [${i}] failed validation:`,`kind="${a?.kind??"undefined"}"`,r.errors.map(o=>`${o.code}: ${o.message}`).join("; "),a)}for(let a of r.errors)e.push({...a,field:a.field?`[${i}].${a.field}`:`[${i}]`});for(let a of r.warnings)n.push({...a,suggestion:a.suggestion?`Action ${i}: ${a.suggestion}`:void 0})}return e.length>0&&console.error(`[ActionValidation] Batch validation failed: ${e.length} error(s) in ${t.length} action(s).`,e.map(i=>`${i.field??"?"}: ${i.message}`).join(" | ")),{valid:e.length===0,errors:e,warnings:n}}var T3=0;function Zy(t){let{overlayRoot:e,eventBus:n,surfaces:i,anchorResolver:r,adaptiveId:a,executorRegistry:o=Xi,subscribeNavigation:s}=t,l=new Map;function c(){return`action-${++T3}`}function u(p,m){n&&n.publish(p,m)}function f(){return{overlayRoot:e,resolveAnchor:r,generateId:c,publishEvent:u,adaptiveId:a,applyAction:g,subscribeEvent:n?(p,m)=>n.subscribe({names:[p]},v=>m(v.props)):void 0,subscribeNavigation:s}}async function h(p,m){if(!i)throw new Error("Surfaces provider required for core:mountWidget actions");let v=i.mount(p.slot,{type:"widget",widgetId:p.widget.widgetId,config:p.widget.props},{priority:p.widget.priority});return m.publishEvent("action.applied",{id:m.generateId(),kind:"core:mountWidget",slot:p.slot,widgetId:p.widget.widgetId}),{cleanup:()=>{v.unmount()},updateFn:S=>{if("widget"in S&&S.widget){let T=S.widget;T.props&&v.update({type:"widget",widgetId:p.widget.widgetId,config:T.props})}}}}async function g(p){let m=na(p);if(!m.valid){let C=m.errors.map(x=>x.message).join("; ");throw console.error(`[ActionEngine] Validation failed for action kind="${p?.kind}":`,C,p),new Error(`Action validation failed: ${C}`)}let v=c(),S=f(),T;if(p.kind==="core:mountWidget")T=await h(p,S);else{let C=o.get(p.kind);if(!C){let x="list"in o?o.list():"(list unavailable)";throw console.error(`[ActionEngine] No executor for kind="${p.kind}".`,`Registered: [${x}]`),new Error(`No executor for action kind: ${p.kind}`)}T=await C(p,S)}let A={id:v,action:p,adaptiveId:a,appliedTs:Date.now(),state:"applied",cleanup:T.cleanup,updateFn:T.updateFn};return l.set(v,A),u("action.applied",{id:v,kind:p.kind,anchorId:"anchorId"in p?p.anchorId:void 0}),{id:v,action:p,async revert(){let C=l.get(v);if(!(!C||C.state!=="applied"))try{await C.cleanup(),C.state="reverted",u("action.reverted",{id:v,kind:p.kind})}catch(x){throw C.state="failed",u("action.failed",{id:v,kind:p.kind,error:String(x)}),x}finally{l.delete(v)}},isApplied(){return l.get(v)?.state==="applied"},async update(C){let x=l.get(v);if(!x||x.state!=="applied")throw new Error("Cannot update action that is not applied");if(x.updateFn)await x.updateFn(C);else throw new Error(`Action kind ${p.kind} does not support updates`)},getState(){return l.get(v)?.state??"reverted"}}}async function _(p){console.log(`[ActionEngine] applyBatch: ${p.length} action(s)`,p.map(k=>k.kind).join(", "));let m=Gy(p);if(!m.valid){let k=m.errors.map(C=>C.message).join("; ");throw console.error(`[ActionEngine] Batch validation FAILED for ${p.length} action(s):`,k,`
448
448
  Actions:`,p.map((C,x)=>` [${x}] ${C.kind} ${C.anchorId?`anchor="${C.anchorId}"`:""} ${C.label?`label="${C.label}"`:""}`).join(`
449
- `)),new Error(`Batch validation failed: ${k}`)}let v=c(),S=[],T=[];try{for(let k of p){let C=await g(k);S.push(C),T.push(C)}}catch(k){console.error(`[ActionEngine] Batch apply FAILED at action ${T.length+1}/${p.length}.`,`Successfully applied: ${T.length}. Rolling back...`,k);for(let C of T)try{await C.revert()}catch{}throw k}return{id:v,handles:S,async revertAll(){for(let k=S.length-1;k>=0;k--)try{await S[k].revert()}catch(C){console.error(`[ActionEngine] Error reverting action ${S[k].id}:`,C)}},isApplied(){return S.every(k=>k.isApplied())}}}function b(p){return na(p)}function w(){return Array.from(l.values()).map(p=>({id:p.id,action:p.action,adaptiveId:p.adaptiveId,appliedTs:p.appliedTs,state:p.state}))}function d(){for(let p of l.values())if(p.state==="applied")try{p.cleanup()}catch(m){console.error("[ActionEngine] Error during cleanup:",m)}l.clear()}return{apply:g,applyBatch:_,validate:b,getActive:w,destroy:d}}var k3=y.object({type:y.literal("page_url"),url:y.string()}),R3=y.object({type:y.literal("route"),routeId:y.string()}),O3=y.object({type:y.literal("anchor_visible"),anchorId:y.string(),state:y.enum(["visible","present","absent"])}),M3=y.object({type:y.literal("event_occurred"),eventName:y.string(),withinMs:y.number().optional()}),N3=y.object({type:y.literal("state_equals"),key:y.string(),value:y.unknown()}),D3=y.object({type:y.literal("viewport"),minWidth:y.number().optional(),maxWidth:y.number().optional(),minHeight:y.number().optional(),maxHeight:y.number().optional()}),L3=y.object({type:y.literal("session_metric"),key:y.string(),operator:y.enum(["gte","lte","eq","gt","lt"]),threshold:y.number()}),H3=y.object({type:y.literal("dismissed"),key:y.string(),inverted:y.boolean().optional()}),I3=y.object({type:y.literal("cooldown_active"),key:y.string(),inverted:y.boolean().optional()}),z3=y.object({type:y.literal("frequency_limit"),key:y.string(),limit:y.number(),inverted:y.boolean().optional()}),B3=y.object({type:y.literal("event_count"),key:y.string(),operator:y.enum(["gte","lte","eq","gt","lt"]),count:y.number().int().min(0),withinMs:y.number().positive().optional()}),Yy=y.discriminatedUnion("type",[k3,R3,O3,M3,N3,D3,L3,H3,I3,z3,B3]),iT=y.object({conditions:y.array(Yy),value:y.unknown()}),rT=y.object({type:y.literal("rules"),rules:y.array(iT),default:y.unknown()}),aT=y.object({type:y.literal("score"),field:y.string(),threshold:y.number(),above:y.unknown(),below:y.unknown()}),oT=y.object({type:y.literal("model"),modelId:y.string(),inputs:y.array(y.string()),outputMapping:y.record(y.string(),y.unknown()),default:y.unknown()}),sT=y.object({type:y.literal("external"),endpoint:y.string(),method:y.enum(["GET","POST"]).optional(),default:y.unknown(),timeoutMs:y.number().optional()}),lT=y.discriminatedUnion("type",[rT,aT,oT,sT]),cT=y.object({include:y.array(y.string()).optional(),exclude:y.array(y.string()).optional()}),Yf=y.object({routes:cT,strategy:lT.optional()});function QB(t){return Yy.safeParse(t)}function JB(t){return lT.safeParse(t)}function e$(t){return Yf.safeParse(t)}var t$=[{defName:"activationConfig",schema:Yf},{defName:"routeFilter",schema:cT},{defName:"ruleStrategy",schema:rT},{defName:"scoreStrategy",schema:aT},{defName:"modelStrategy",schema:oT},{defName:"externalStrategy",schema:sT},{defName:"rule",schema:iT},{defName:"condition",schema:Yy}];var pt={activation:Yf.optional()},uT=y.object({color:y.string().optional(),scrimOpacity:y.number().min(0).max(1).optional(),paddingPx:y.number().optional(),radiusPx:y.number().optional()}).strict(),dT=y.enum(["top-left","top-right","bottom-left","bottom-right"]),fT=y.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),Ky=y.object({label:y.string(),actionId:y.string(),primary:y.boolean().optional()}).strict(),pT=y.object({title:y.string().optional(),body:y.string(),ctaButtons:y.array(Ky).optional()}).strict(),hT=y.object({title:y.string().optional(),body:y.string()}).strict(),gT=y.enum(["before","after","prepend","append","replace"]),mT=y.enum(["immediate","hover","click"]),vT=y.object({widgetId:y.string(),props:y.record(y.unknown()).optional(),priority:y.number().optional()}).strict(),yT=y.object({id:y.string(),action:y.any(),route:y.string().optional(),onAction:y.record(y.string()).optional()}).strict(),bT=y.enum(["auto","smooth","instant"]),Wy=y.enum(["start","center","end","nearest"]),_T=y.object({kind:y.literal("content:setText"),anchorId:y.string(),text:y.string(),label:y.string().optional()}).extend(pt).strict(),ST=y.object({kind:y.literal("content:setAttr"),anchorId:y.string(),attr:y.string(),value:y.string(),label:y.string().optional()}).extend(pt).strict(),xT=y.object({kind:y.literal("content:addClass"),anchorId:y.string(),className:y.string(),label:y.string().optional()}).extend(pt).strict(),wT=y.object({kind:y.literal("content:removeClass"),anchorId:y.string(),className:y.string(),label:y.string().optional()}).extend(pt).strict(),ET=y.object({kind:y.literal("content:setStyle"),anchorId:y.string(),styles:y.record(y.string()),label:y.string().optional()}).extend(pt).strict(),CT=y.object({kind:y.literal("content:insertHtml"),anchorId:y.string(),html:y.string(),position:gT,label:y.string().optional()}).extend(pt).strict(),AT=y.object({kind:y.literal("overlays:highlight"),anchorId:y.string(),style:uT.optional(),duration:y.number().optional(),label:y.string().optional()}).extend(pt).strict(),TT=y.object({kind:y.literal("overlays:pulse"),anchorId:y.string(),duration:y.number().optional(),label:y.string().optional()}).extend(pt).strict(),kT=y.object({kind:y.literal("overlays:badge"),anchorId:y.string(),content:y.string(),position:dT.optional(),label:y.string().optional()}).extend(pt).strict(),RT=y.object({kind:y.literal("overlays:tooltip"),anchorId:y.string(),content:pT,trigger:mT.optional(),placement:fT.optional(),waitFor:y.string().optional(),label:y.string().optional()}).extend(pt).strict(),OT=y.object({kind:y.literal("overlays:modal"),content:hT,size:y.enum(["sm","md","lg"]).optional(),blocking:y.boolean().optional(),scrim:y.object({opacity:y.number().min(0).max(1).optional()}).strict().optional(),dismiss:y.object({onEsc:y.boolean().optional(),closeButton:y.boolean().optional(),timeoutMs:y.number().min(0).optional()}).strict().optional(),ctaButtons:y.array(Ky).optional(),waitFor:y.string().optional(),label:y.string().optional()}).extend(pt).strict(),MT=y.object({kind:y.literal("navigation:scrollTo"),anchorId:y.string(),behavior:bT.optional(),block:Wy.optional(),inline:Wy.optional(),label:y.string().optional()}).extend(pt).strict(),NT=y.object({kind:y.literal("navigation:navigate"),url:y.string(),target:y.enum(["_self","_blank"]).optional(),label:y.string().optional()}).extend(pt).strict(),DT=y.object({kind:y.literal("core:mountWidget"),slot:y.string(),widget:vT,label:y.string().optional()}).extend(pt).strict(),LT=y.object({kind:y.literal("core:wait"),durationMs:y.number().min(0).optional(),event:y.string().optional(),label:y.string().optional()}).extend(pt).strict(),HT=y.object({kind:y.literal("core:sequence"),actions:y.array(y.any()),label:y.string().optional()}).extend(pt).strict(),IT=y.object({kind:y.literal("core:parallel"),actions:y.array(y.any()),waitFor:y.enum(["all","any"]).optional(),label:y.string().optional()}).extend(pt).strict(),zT=y.object({kind:y.literal("core:tour"),tourId:y.string(),steps:y.array(yT).min(1),startStep:y.string().optional(),autoStart:y.boolean().optional(),label:y.string().optional()}).extend(pt).strict(),$3=[{defName:"setText",schema:_T},{defName:"setAttr",schema:ST},{defName:"addClass",schema:xT},{defName:"removeClass",schema:wT},{defName:"setStyle",schema:ET},{defName:"insertHtml",schema:CT},{defName:"highlight",schema:AT},{defName:"pulse",schema:TT},{defName:"badge",schema:kT},{defName:"tooltip",schema:RT},{defName:"modal",schema:OT},{defName:"scrollTo",schema:MT},{defName:"navigate",schema:NT},{defName:"mountWidget",schema:DT},{defName:"wait",schema:LT},{defName:"sequence",schema:HT},{defName:"parallel",schema:IT},{defName:"tour",schema:zT}];function F3(){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 Xy(t,e){if(!e)return;let n;try{n=new URL(t).pathname}catch{n=t}if(e.exclude){for(let i of e.exclude)if(BT(n,i))return}if(e.include){for(let i of e.include)if(BT(n,i))return i;return}return n}function BT(t,e){let n=t.replace(/\/$/,"")||"/",i=e.replace(/\/$/,"")||"/";if(n===i)return!0;let r=i.replace(/:[^/]+/g,"[^/]+").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(n)}var Wf=class{constructor(e={}){V(this,"context");V(this,"previousContext");V(this,"listeners",new Set);V(this,"telemetry");V(this,"routes");V(this,"navigation");V(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=F3(),this.previousContext={...this.context},e.telemetry?.getSessionId){let n=e.telemetry.getSessionId();n&&(this.context.session.sessionId=n)}e.initialPageHistory&&(this.context.session.pageHistory=e.initialPageHistory),this.context.page.routeId=Xy(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 n=Xy(this.context.page.url,this.routes);n!==this.context.page.routeId&&this.updateContext({page:{...this.context.page,routeId:n}})}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,n=()=>{clearTimeout(e),e=setTimeout(()=>{this.updateViewport()},100)};if(window.addEventListener("resize",n),this.cleanupFns.push(()=>window.removeEventListener("resize",n)),this.navigation){let i=this.navigation.subscribe(()=>this.updatePage());this.cleanupFns.push(i)}else{let i=()=>{this.updatePage()};window.addEventListener("popstate",i),this.cleanupFns.push(()=>window.removeEventListener("popstate",i));let r=history.pushState.bind(history),a=history.replaceState.bind(history);history.pushState=(...o)=>{r(...o),queueMicrotask(()=>this.updatePage())},history.replaceState=(...o)=>{a(...o),queueMicrotask(()=>this.updatePage())},this.cleanupFns.push(()=>{history.pushState=r,history.replaceState=a})}}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:n}=document,i=Xy(e,this.routes),r={url:e,title:n,routeId:i};(r.url!==this.context.page.url||r.title!==this.context.page.title||r.routeId!==this.context.page.routeId)&&(r.url!==this.context.page.url&&this.addPageToHistory(r.url),this.updateContext({page:r}))}addPageToHistory(e){let n={url:e,ts:Date.now()},i=[...this.context.session.pageHistory||[],n];i.length>50&&i.shift(),this.context.session.pageHistory=i}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(n){console.error("[ContextManager] Listener error:",n)}}};function Qy(t={}){return new Wf(t)}var U3=y.object({url:y.string(),routeId:y.string().optional(),title:y.string().optional(),locale:y.string().optional()}),V3=y.object({url:y.string(),ts:y.number()}),j3=y.object({sessionId:y.string(),startTs:y.number(),pageHistory:y.array(V3).optional()}),q3=y.object({width:y.number(),height:y.number()}),P3=y.object({x:y.number(),y:y.number(),w:y.number(),h:y.number()}),G3=y.object({anchorId:y.string(),present:y.boolean(),visible:y.boolean().optional(),boundingBox:P3.optional()}),Z3=y.record(y.string(),y.union([y.number(),y.string(),y.boolean(),y.undefined()])),Y3=y.object({page:U3,session:j3,viewport:q3,anchors:y.array(G3).optional(),augmented:Z3.optional()});function h$(t){return Y3.safeParse(t)}function $T(t,e){let{context:n,state:i,events:r}=e;switch(t.type){case"page_url":{let{url:a}=t,o=n.page.url,s=a.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*");return new RegExp(`^${s}$`).test(o)}case"route":return n.page.routeId===t.routeId;case"anchor_visible":{let a=n.anchors?.find(o=>o.anchorId===t.anchorId);switch(t.state){case"visible":return a?.visible===!0;case"present":return a?.present===!0;case"absent":return!a?.present;default:return!1}}case"event_occurred":{if(!r)return!1;let a=t.withinMs??6e4;return r.hasRecentEvent(t.eventName,a)}case"state_equals":return!1;case"viewport":{let{width:a,height:o}=n.viewport;return!(t.minWidth!==void 0&&a<t.minWidth||t.maxWidth!==void 0&&a>t.maxWidth||t.minHeight!==void 0&&o<t.minHeight||t.maxHeight!==void 0&&o>t.maxHeight)}case"session_metric":{if(!i)return!1;let a=i.getSessionMetric(t.key),{operator:o,threshold:s}=t;switch(o){case"gte":return a>=s;case"lte":return a<=s;case"eq":return a===s;case"gt":return a>s;case"lt":return a<s;default:return!1}}case"dismissed":{if(!i)return t.inverted??!1;let a=i.isDismissed(t.key);return t.inverted?!a:a}case"cooldown_active":{if(!i)return t.inverted??!1;let a=i.isCooldownActive(t.key);return t.inverted?!a:a}case"frequency_limit":{if(!i)return t.inverted??!1;let o=i.getFrequencyCount(t.key)>=t.limit;return t.inverted?!o:o}case"event_count":{if(!e.accumulator)return!1;let a=t,o=e.accumulator.getCount(a.key,a.withinMs);switch(a.operator){case"gte":return o>=a.count;case"lte":return o<=a.count;case"eq":return o===a.count;case"gt":return o>a.count;case"lt":return o<a.count;default:return!1}}default:return console.warn("[RuleStrategy] Unknown condition type:",t.type),!1}}function FT(t,e){let n=[];for(let i of t.conditions){let r=$T(i,e);if(n.push({condition:i,result:r}),!r)return{matched:!1,conditionResults:n}}return{matched:!0,conditionResults:n}}function Kf(t,e){for(let n=0;n<t.rules.length;n++){let i=t.rules[n],{matched:r,conditionResults:a}=FT(i,e);if(r)return{value:i.value,isFallback:!1,matchInfo:{strategyType:"rules",matchedRuleIndex:n,evaluatedConditions:a}}}return{value:t.default,isFallback:!0,matchInfo:{strategyType:"rules"}}}function Xf(t,e){let{context:n}=e,i=n.augmented?.[t.field];return i===void 0||typeof i!="number"?{value:t.below,isFallback:!0,matchInfo:{strategyType:"score"}}:{value:i>=t.threshold?t.above:t.below,isFallback:!1,matchInfo:{strategyType:"score"}}}function UT(t,e){let{state:n,events:i,sessionMetrics:r,accumulator:a}=e;return{context:t,state:n?{isDismissed:o=>n.dismissals.isDismissed(o),isCooldownActive:o=>n.cooldowns.isActive(o),getFrequencyCount:o=>n.frequency.count(o),getSessionMetric:o=>r?.get(o)??0}:void 0,events:i?{hasRecentEvent:(o,s)=>i.hasRecentEvent(o,s)}:void 0,accumulator:a?{getCount:(o,s)=>a.getCount(o,s)}:void 0}}async function VT(t,e,n={}){let i=UT(e,n);switch(t.type){case"rules":return Kf(t,i);case"score":return Xf(t,i);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 jT(t,e,n={}){let i=UT(e,n);switch(t.type){case"rules":return Kf(t,i);case"score":return Xf(t,i);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 Jy(t){return{evaluate:(e,n)=>VT(e,n,t),evaluateSync:(e,n)=>jT(e,n,t)}}function eb(t){let{eventBus:e,stateStore:n}=t,i=new Map,r=new Set,a=null,o=n.ns("accumulator");function s(c){let u=!1;for(let f of i.values()){if(!f.predicate(c))continue;let h=o.get(f.stateKey)||{count:0};h.count++,f.needsTimestamps&&(h.timestamps||(h.timestamps=[]),h.timestamps.push(c.ts),h.timestamps.length>200&&(h.timestamps=h.timestamps.slice(-200))),o.set(f.stateKey,h),u=!0}if(u)for(let f of r)try{f()}catch(h){console.error("[EventAccumulator] Subscriber error:",h)}}function l(){a||i.size===0||(a=e.subscribe(s))}return{register(c,u,f=!1){let h=`ev:${c}`,g=i.get(h);if(g){f&&!g.needsTimestamps&&(g.needsTimestamps=!0);return}i.set(h,{stateKey:h,needsTimestamps:f,predicate:u}),l()},getCount(c,u){let f=`ev:${c}`,h=o.get(f);if(!h)return 0;if(u===void 0||!h.timestamps)return h.count;let g=Date.now()-u;return h.timestamps.filter(_=>_>=g).length},subscribe(c){return r.add(c),()=>{r.delete(c)}},destroy(){a&&(a(),a=null),i.clear(),r.clear()}}}function tb(t,e){return e?!(e.names&&e.names.length>0&&!e.names.includes(t.name)||e.patterns&&e.patterns.length>0&&!e.patterns.some(i=>{try{return new RegExp(i).test(t.name)}catch{return!1}})||e.sources&&e.sources.length>0&&!e.sources.includes(t.source)):!0}var Qf=class{constructor(e={}){V(this,"subscriptions",new Set);V(this,"history",[]);V(this,"maxHistorySize");this.maxHistorySize=e.maxHistorySize??100}subscribe(e,n){let i,r;typeof e=="function"?(i=void 0,r=e):(i=e,r=n);let a={filter:i,callback:r};return this.subscriptions.add(a),()=>{this.subscriptions.delete(a)}}publish(e,n,i="canvas"){let r={ts:Date.now(),name:e,source:i,props:n,schemaVersion:is};this.publishEvent(r)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let n of this.subscriptions)if(tb(e,n.filter))try{n.callback(e)}catch(i){console.error("[EventBus] Subscriber error:",i)}}getRecent(e,n){let i=this.history;return e&&(i=i.filter(r=>tb(r,e))),n&&n>0&&(i=i.slice(-n)),i}hasRecentEvent(e,n,i){let r=Date.now()-n;return this.history.some(a=>a.name===e&&a.ts>=r&&(i===void 0||a.source===i))}countRecentEvents(e,n){let i=this.history.filter(r=>tb(r,e));if(n!==void 0){let r=Date.now()-n;i=i.filter(a=>a.ts>=r)}return i.length}clearHistory(){this.history=[]}getSubscriberCount(){return this.subscriptions.size}};function Lc(t={}){return new Qf(t)}var qT={$autocapture:"ui.click",$click:_e.UI_CLICK,$scroll:_e.UI_SCROLL,$input:_e.UI_INPUT,$change:_e.UI_CHANGE,$submit:_e.UI_SUBMIT,$pageview:_e.NAV_PAGE_VIEW,$pageleave:_e.NAV_PAGE_LEAVE,$session_start:"session.start",$identify:"user.identify"};function W3(t){let e=t.event;if(typeof e!="string")return"posthog.unknown";if(qT[e])return qT[e];if(e==="$autocapture"){let n=t.properties?.$tag_name,i=t.properties?.$event_type;return i==="submit"?_e.UI_SUBMIT:i==="change"?_e.UI_CHANGE:n==="input"||n==="textarea"?_e.UI_INPUT:_e.UI_CLICK}return e.startsWith("$")?e.replace("$","posthog."):`posthog.${e}`}function K3(t){let e={},n=t.properties||{},i=n.$elements;return n.$tag_name?e.tagName=n.$tag_name:i?.[0]?.tag_name&&(e.tagName=i[0].tag_name),n.$el_text&&(e.elementText=n.$el_text),i&&(e.elements=i),n.$current_url&&(e.url=n.$current_url),n.$pathname&&(e.pathname=n.$pathname),n.$host&&(e.host=n.$host),n.$viewport_width&&(e.viewportWidth=n.$viewport_width),n.$viewport_height&&(e.viewportHeight=n.$viewport_height),n.$session_id&&(e.sessionId=n.$session_id),n.$scroll_depth&&(e.scrollDepth=n.$scroll_depth),n.$scroll_percentage&&(e.scrollPercentage=n.$scroll_percentage),e.originalEvent=t.event,e}function PT(t){let e;return typeof t.timestamp=="number"?e=t.timestamp:typeof t.timestamp=="string"?e=new Date(t.timestamp).getTime():e=Date.now(),{ts:e,name:W3(t),source:"posthog",props:K3(t),schemaVersion:is}}function GT(t){let e=t.event;return!(typeof e!="string"||["$feature_flag_called","$feature_flags","$groups","$groupidentify","$set","$set_once","$unset","$create_alias","$capture_metrics","$performance_event","$web_vitals","$exception","$dead_click","$heatmap"].includes(e))}function nb(t){return(e,n)=>{if(typeof e!="string")return;let i={event:e,properties:n,timestamp:Date.now()};if(GT(i)){let r=PT(i);t(r)}}}var ZT=y.enum(["posthog","canvas","derived"]),X3=y.object({ts:y.number(),name:y.string(),source:ZT,props:y.record(y.string(),y.unknown()).optional(),schemaVersion:y.string()}),Q3=y.object({names:y.array(y.string()).optional(),patterns:y.array(y.string()).optional(),sources:y.array(ZT).optional()});function B$(t){return X3.safeParse(t)}function $$(t){return Q3.safeParse(t)}var Hc=class{constructor(){V(this,"listeners",new Set);V(this,"capturedPushState");V(this,"capturedReplaceState");V(this,"wasNative");V(this,"destroyed",!1);V(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,n){if(!this.destroyed)for(let i of this.listeners)try{i(e,n)}catch{}}isNativeFunction(e){try{return Function.prototype.toString.call(e).includes("[native code]")}catch{return!1}}};var ib="cooldown:";function YT(t){return{set(e,n){let i=ib+e,r=Date.now()+n;t.set(i,r)},isActive(e){return this.remaining(e)>0},remaining(e){let n=ib+e,i=t.get(n);if(i===void 0)return 0;let r=i-Date.now();return r<=0?(t.remove(n),0):r},clear(e){let n=ib+e;t.remove(n)}}}var Ic="dismissed:";function WT(t,e){return{mark(n,i=!1){let r=Ic+n;(i?e:t).set(r,!0)},isDismissed(n){let i=Ic+n;return t.has(i)||e.has(i)},clear(n){let i=Ic+n;t.remove(i),e.remove(i)},clearAll(){for(let n of t.keys())n.startsWith(Ic)&&t.remove(n);for(let n of e.keys())n.startsWith(Ic)&&e.remove(n)}}}var rb="freq:";function KT(t){function e(n){let i=rb+n,r=t.get(i);if(r){if(r.resetAt&&Date.now()>=r.resetAt){t.remove(i);return}return r}}return{increment(n,i){let r=rb+n,a=e(n),o=(a?.count??0)+1,s={count:o,resetAt:a?.resetAt??(i?Date.now()+i:void 0)};return t.set(r,s),o},count(n){return e(n)?.count??0},reset(n){let i=rb+n;t.remove(i)},hasReachedLimit(n,i){return this.count(n)>=i}}}var J3="syntro";function ab(t,e){let n=`${e}:`;return{get(i){if(t)try{let r=t.getItem(n+i);if(!r)return;let a=JSON.parse(r);if(a.expiresAt&&Date.now()>=a.expiresAt){t.removeItem(n+i);return}return a.value}catch{return}},set(i,r,a){if(t)try{let o={value:r,expiresAt:a?Date.now()+a:void 0};t.setItem(n+i,JSON.stringify(o))}catch(o){console.warn("[StateStore] Failed to save:",o)}},remove(i){t&&t.removeItem(n+i)},has(i){return t?this.get(i)!==void 0:!1},keys(){if(!t)return[];let i=[];for(let r=0;r<t.length;r++){let a=t.key(r);a?.startsWith(n)&&i.push(a.slice(n.length))}return i},clear(){if(!t)return;let i=this.keys();for(let r of i)t.removeItem(n+r)}}}function ob(t){let e=new Map,n=`${t}:`;return{get(i){let r=e.get(n+i);if(r){if(r.expiresAt&&Date.now()>=r.expiresAt){e.delete(n+i);return}return r.value}},set(i,r,a){e.set(n+i,{value:r,expiresAt:a?Date.now()+a:void 0})},remove(i){e.delete(n+i)},has(i){return this.get(i)!==void 0},keys(){let i=[];for(let r of e.keys())r.startsWith(n)&&i.push(r.slice(n.length));return i},clear(){for(let i of e.keys())i.startsWith(n)&&e.delete(i)}}}var Jf=class{constructor(e={}){V(this,"session");V(this,"user");V(this,"dismissals");V(this,"cooldowns");V(this,"frequency");V(this,"namespace");V(this,"namespacedStorages",new Map);this.namespace=e.namespace??J3,typeof window<"u"?(this.session=ab(typeof sessionStorage<"u"?sessionStorage:void 0,this.namespace),this.user=ab(typeof localStorage<"u"?localStorage:void 0,this.namespace)):(this.session=ob(this.namespace),this.user=ob(this.namespace)),this.dismissals=WT(this.session,this.user),this.cooldowns=YT(this.user),this.frequency=KT(this.session)}ns(e){let n=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(n)){let i=typeof window<"u"&&typeof sessionStorage<"u"?ab(sessionStorage,n):ob(n);this.namespacedStorages.set(n,i)}return this.namespacedStorages.get(n)}};function sb(t={}){return new Jf(t)}function zc(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function ep(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var XT={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"}},Bc={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:[]},QT={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function lb(t,e,n){let i=XT[e];Object.assign(t.style,i),n&&(n.maxWidth&&(t.style.maxWidth=n.maxWidth),n.maxHeight&&(t.style.maxHeight=n.maxHeight),n.minWidth&&(t.style.minWidth=n.minWidth),n.minHeight&&(t.style.minHeight=n.minHeight))}function cb(t,e,n){let i=n.placement==="auto"?"bottom":n.placement,r=[Ad(n.offset?{mainAxis:n.offset.y,crossAxis:n.offset.x}:8)];return n.flip!==!1&&r.push(kd()),n.shift!==!1&&r.push(Td({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",Cd(e,t,async()=>{let{x:o,y:s,strategy:l}=await Rd(e,t,{placement:i,middleware:r});Object.assign(t.style,{position:l,left:`${o}px`,top:`${s}px`})})}function ub(t,e,n="append"){return t.style.position="relative",t.style.display="inline-block",n==="prepend"?e.insertBefore(t,e.firstChild):e.appendChild(t),()=>{t.remove()}}function db(t,e){return e==="none"||Bc[e].length===0?null:t.animate(Bc[e],QT)}function fb(t,e){if(e==="none"||Bc[e].length===0)return Promise.resolve();let n=[...Bc[e]].reverse(),i=t.animate(n,QT);return new Promise(r=>{i.onfinish=()=>r(),i.oncancel=()=>r()})}function pb(t,e){let n=document.createElement("div");return n.setAttribute("data-syntro-surface",t),n.setAttribute("data-syntro-mount-id",e),n.className="syntro-surface",Object.assign(n.style,{pointerEvents:"auto",boxSizing:"border-box",overflow:"auto"}),n}function hb(t){switch(zc(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 JT(t){if(typeof window.Sanitizer=="function")try{let l=new window.Sanitizer({}).sanitizeToFragment(t),c=document.createElement("div");return c.append(l),c.innerHTML}catch{}let n=document.createElement("template");n.innerHTML=t;let i=n.content,r=document.createTreeWalker(i,NodeFilter.SHOW_ELEMENT,null),a=new Set(["b","strong","i","em","u","span","div","p","br","ul","ol","li","code","pre","small","sup","sub","a","button"]),o=[];for(;r.nextNode();){let s=r.currentNode,l=s.tagName.toLowerCase();if(!a.has(l)){o.push(s);continue}for(let c of Array.from(s.attributes)){let u=c.name.toLowerCase(),f=c.value.trim().toLowerCase(),h=u.startsWith("on"),g=(u==="href"||u==="src")&&f.startsWith("javascript:");(h||g)&&s.removeAttribute(c.name)}}for(let s of o){for(;s.firstChild;)s.parentNode?.insertBefore(s.firstChild,s);s.remove()}return n.innerHTML=(i.firstChild,n.innerHTML)}var e5=0;function gb(t){let{overlayRoot:e,eventBus:n,anchorResolver:i,defaultAnimation:r="fade",widgetRegistry:a}=t,o=new Map,s=new Map,l=new Map;function c(){return`mount-${++e5}`}function u(v,S){n&&n.publish(v,S)}function f(v){let S=l.get(v);if(S){let T=w(v);for(let A of S)try{A(T)}catch(k){console.error("[Surfaces] State callback error:",k)}}}let h=new Map;function g(v,S,T){switch(S.type){case"html":v.innerHTML=JT(S.content);return;case"widget":{if(a?.has(S.widgetId)){let A=a.mount(S.widgetId,v,S.config);return T&&h.set(T,A),()=>{A.unmount(),T&&h.delete(T)}}console.warn(`[Surfaces] Widget not found: ${S.widgetId}`),v.innerHTML=`<div data-widget-id="${S.widgetId}" data-widget-missing="true">Widget: ${S.widgetId}</div>`;return}case"custom":return S.mount(v);case"react":v.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function _(v,S,T){let A=c(),k=zc(v),C=T?.priority??0,x=T?.animation??r,M=T?.exclusive??!0,z=o.get(v);if(z&&M){if(z.options.priority>C)throw new Error(`Slot ${v} is occupied by higher priority content (${z.options.priority} > ${C})`);b(z)}let U=pb(v,A);U.style.zIndex=String(hb(v));let P;if(k==="static")lb(U,v,T?.constraints),e.appendChild(U);else if(k==="inline"){let D=ep(v);if(!D)throw new Error(`Invalid inline slot: ${v}`);if(!i)throw new Error("Anchor resolver required for inline slots");let L=i(D);if(!L)throw new Error(`Anchor not found for inline slot: ${D}`);P=ub(U,L)}else if(k==="adjacent"){let D=ep(v);if(!D)throw new Error(`Invalid adjacent slot: ${v}`);if(!i)throw new Error("Anchor resolver required for adjacent slots");let L=i(D);if(!L)throw new Error(`Anchor not found for adjacent slot: ${D}`);e.appendChild(U),P=cb(U,L,T?.position??{placement:"bottom"})}let Z=g(U,S,A);db(U,x);let X={id:A,slot:v,content:S,options:{priority:C,exclusive:M,animation:x,position:T?.position??{placement:"auto"},constraints:T?.constraints??{},adaptiveId:T?.adaptiveId,autoUnmountOnRouteChange:T?.autoUnmountOnRouteChange??!0},container:U,cleanup:()=>{P?.(),Z?.()},mountedAt:Date.now()};return o.set(v,X),s.set(v,(s.get(v)??0)+1),u("surface.mounted",{slot:v,id:A,adaptiveId:T?.adaptiveId}),f(v),{id:A,update(D){let L=o.get(v);if(!L||L.id!==A)throw new Error("Mount no longer active");let de=h.get(A);if(de){if(D.type==="widget"){de.update(D.config),L.content=D;return}de.unmount(),h.delete(A)}L.container.innerHTML="";let fn=g(L.container,D,A);if(L.content=D,fn){let We=L.cleanup;L.cleanup=()=>{We?.(),fn()}}},setOptions(D){let L=o.get(v);if(!L||L.id!==A)throw new Error("Mount no longer active");D.priority!==void 0&&(L.options.priority=D.priority),D.animation!==void 0&&(L.options.animation=D.animation),D.constraints&&k==="static"&&(D.constraints.maxWidth&&(L.container.style.maxWidth=D.constraints.maxWidth),D.constraints.maxHeight&&(L.container.style.maxHeight=D.constraints.maxHeight),D.constraints.minWidth&&(L.container.style.minWidth=D.constraints.minWidth),D.constraints.minHeight&&(L.container.style.minHeight=D.constraints.minHeight)),f(v)},async unmount(){let D=o.get(v);!D||D.id!==A||await b(D)},isMounted(){return o.get(v)?.id===A},getContainer(){let D=o.get(v);return D?.id===A?D.container:null}}}async function b(v){await fb(v.container,v.options.animation),v.cleanup?.(),v.container.remove(),o.delete(v.slot),u("surface.unmounted",{slot:v.slot,id:v.id}),f(v.slot)}function w(v){let S=o.get(v);return{slot:v,occupied:!!S,currentPriority:S?.options.priority,currentAdaptiveId:S?.options.adaptiveId,mountCount:s.get(v)??0,currentMountId:S?.id}}function d(v,S){let T=l.get(v);return T||(T=new Set,l.set(v,T)),T.add(S),()=>{T?.delete(S),T?.size===0&&l.delete(v)}}function p(v,S){let T=o.get(v);return T?S!==void 0?S>=T.options.priority:!1:!0}function m(){for(let v of o.values())try{v.cleanup?.(),v.container.remove()}catch(S){console.error("[Surfaces] Error during cleanup:",S)}o.clear(),l.clear()}return{mount:_,getState:w,onStateChange:d,canMount:p,destroy:m}}var tp=class{constructor(){V(this,"widgets",new Map);V(this,"mountedWidgets",new Map);V(this,"mountIdCounter",0);V(this,"runtimeRef");V(this,"listeners",new Set)}bindRuntime(e){this.runtimeRef=e}register(e,n,i="custom",r){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:n,source:i,metadata:r}),this.notify({type:"registered",widgetId:e})}unregister(e){let n=this.widgets.get(e);return n?n.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[n,i]of this.widgets.entries())i.source===e&&this.widgets.delete(n)}get(e){return this.widgets.get(e)?.widget}getRegistration(e){return this.widgets.get(e)}has(e){return this.widgets.has(e)}mount(e,n,i){let r=this.widgets.get(e);if(!r)throw new Error(`Widget not found: ${e}`);let a=`widget-mount-${++this.mountIdCounter}`;n.setAttribute("data-widget-mount-id",a),n.setAttribute("data-widget-id",e);let o={...i,runtime:this.runtimeRef},s=r.widget.mount(n,o);return this.mountedWidgets.set(a,{cleanup:s??void 0,container:n}),{widgetId:e,container:n,unmount:()=>{let c=this.mountedWidgets.get(a);c&&(c.cleanup?.(),this.mountedWidgets.delete(a),n.removeAttribute("data-widget-mount-id"),n.removeAttribute("data-widget-id"),n.innerHTML="")},update:c=>{if(r.widget.update)r.widget.update(n,c);else{let u=this.mountedWidgets.get(a);if(u){u.cleanup?.(),n.innerHTML="";let f={...c,runtime:this.runtimeRef},h=r.widget.mount(n,f);u.cleanup=h??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(n=>n.source===e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(let n of this.listeners)try{n(e)}catch(i){console.error("[WidgetRegistry] Listener error:",i)}}destroy(){for(let[e,n]of this.mountedWidgets.entries())n.cleanup?.(),n.container.innerHTML="";this.mountedWidgets.clear()}},mb=new tp;var tk="2.0.0";function t5(t,e){if(!e)return!0;let n;try{n=new URL(t).pathname}catch{n=t}let i=n.replace(/\/$/,"")||"/";if(e.exclude){for(let r of e.exclude)if(ek(i,r))return!1}if(e.include&&e.include.length>0){for(let r of e.include)if(ek(i,r))return!0;return!1}return!0}function ek(t,e){let n=e.replace(/\/$/,"")||"/";if(t===n)return!0;let i=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/:[^/]+/g,"[^/]+");return new RegExp(`^${i}$`).test(t)}function n5(t){try{return document.querySelector(t)}catch{return null}}function vb(t={}){let{telemetry:e,sessionMetrics:n,routes:i,mode:r="production",namespace:a}=t,o=t.widgets??mb,s=t.executors??Xi,l=t.apps??Vl,c=new Hc,u=Qy({telemetry:e,routes:i,navigation:c}),f=t.events??Lc(),h=sb({namespace:a}),g=eb({eventBus:f,stateStore:h}),_=Jy({state:h,events:f,sessionMetrics:n,accumulator:g}),b=$w(),w=v=>n5(v),d=gb({overlayRoot:b,eventBus:f,anchorResolver:w,widgetRegistry:o}),p=Zy({overlayRoot:b,eventBus:f,surfaces:d,anchorResolver:w,executorRegistry:s,subscribeNavigation:v=>c.subscribe(v)}),m={telemetry:e,context:u,events:f,state:h,sessionMetrics:n,actions:p,surfaces:d,widgets:o,executors:s,apps:l,accumulator:g,navigation:c,version:tk,mode:r,async evaluate(v){return _.evaluate(v,u.get())},evaluateSync(v){return _.evaluateSync(v,u.get())},async filterTiles(v){let S=u.get().page.url,T=[];for(let A of v){let k=A.activation;if(!k){T.push(A);continue}if(!t5(S,k.routes))continue;if(!k.strategy){T.push(A);continue}(await this.evaluate(k.strategy)).value&&T.push(A)}return T},setRoutes(v){u.setRoutes(v)},destroy(){l.unbind().catch(v=>{console.error("[Runtime] Error unbinding apps registry:",v)}),g.destroy(),c.destroy(),u.destroy(),p.destroy(),d.destroy()}};return l.bind(m),o.bindRuntime(m),m}var i5=y.object({value:y.unknown(),expiresAt:y.number().optional()}),r5=y.object({count:y.number(),resetAt:y.number().optional()});function U8(t){return i5.safeParse(t)}function V8(t){return r5.safeParse(t)}var nk={growthbook:t=>Ym({...t,autoInit:!0})};function ik(t,e){let n=nk[t];if(!n)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys(nk).join(", ")}`);return n(e)}var a5=["cdn.syntrologie.com","localhost","127.0.0.1"];function o5(t){try{let e=new URL(t),n=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!n?(console.warn("[SmartCanvas] CDN URL must use HTTPS:",t),!1):a5.some(r=>e.hostname===r)?!0:(console.warn("[SmartCanvas] CDN host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid CDN URL:",t),!1}}var yb=class{constructor(e){V(this,"name","cdn");V(this,"url");V(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!o5(this.url))throw new Error(`[SmartCanvas] CDN URL not allowed: ${this.url}`)}async fetch(){let e=performance.now(),n=await fetch(this.url,{credentials:"omit",cache:"default"});if(!n.ok)throw new Error(`[SmartCanvas] Failed to fetch config from CDN (${n.status})`);let i=await n.text();if(this.integrity){let l=await s5(i),c=this.integrity.replace("sha384-","");if(l!==c)throw new Error(`[SmartCanvas] Config integrity check failed. Expected ${c}, got ${l}`)}let r=JSON.parse(i),a=performance.now()-e,o=n.headers.get("cache-control"),s=n.headers.get("age");return{config:r,meta:{source:"cdn",fetchTimeMs:a,cached:o?.includes("public")??!1,cacheAge:s?parseInt(s,10):void 0}}}};async function s5(t){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-384",n),r=new Uint8Array(i);return btoa(String.fromCharCode(...r))}function rk(t){return new yb(t)}var l5="syntro_exp",c5="syntro_var",bb=class{constructor(e){V(this,"name","experiments");V(this,"client");V(this,"featureKey");V(this,"manifestKey");V(this,"variantFlagPrefix");this.client=e.client,this.featureKey=e.featureKey??"smart-canvas-config",this.manifestKey=e.manifestKey,this.variantFlagPrefix=e.variantFlagPrefix}async fetch(){let e=performance.now();if(typeof window<"u"){let r=new URLSearchParams(window.location.search),a=r.get(l5),o=r.get(c5);if(a&&o!==null&&this.client.setForcedVariations){let s=parseInt(o,10);Number.isNaN(s)||(console.log(`[SmartCanvas] Preview mode: forcing "${a}" to variation ${s}`),this.client.setForcedVariations({[a]:s}))}}if(this.manifestKey||this.variantFlagPrefix){let r=this.fetchMultiFlag();if(r){let a=performance.now()-e;return{config:r,meta:{source:"experiments",fetchTimeMs:a,cached:!0}}}}let n=this.client.getFeatureValue?.(this.featureKey,null);if(!n||typeof n!="object")throw new Error(`[SmartCanvas] Feature "${this.featureKey}" not found or invalid. Ensure the feature is configured in your experiment platform.`);let i=performance.now()-e;return{config:n,meta:{source:"experiments",fetchTimeMs:i,cached:!0}}}fetchMultiFlag(){let e=this.getVariantFlagKeys();return!e||e.length===0?null:Ld(this.client,e)}getVariantFlagKeys(){if(this.manifestKey){let e=this.client.getFeatureValue?.(this.manifestKey,null);if(e&&typeof e=="object"){let n=e.variant_flags;if(n&&n.length>0)return n}}if(this.variantFlagPrefix&&this.client.getAllFeatures){let e=this.client.getAllFeatures();return Object.keys(e).filter(n=>n.startsWith(this.variantFlagPrefix))}return[]}};function ak(t){return new bb(t)}var u5="https://cdn.syntrologie.com/configs",ok={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return rk({baseUrl:t.baseUrl??u5,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return ak({featureKey:t.featureKey})}};function sk(t,e={}){let n=ok[t];if(!n)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys(ok).join(", ")}`);return n(e)}var lk={posthog:t=>By(t),noop:()=>tv()};function ck(t,e){let n=lk[t];if(!n)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(lk).join(", ")}`);return n(e)}var _b="syn_";function np(t){if(!t.startsWith(_b))throw new Error("Invalid Syntro token: must start with 'syn_'");let n=t.slice(_b.length).replace(/-/g,"+").replace(/_/g,"/"),i=atob(n),r=JSON.parse(i);if(r.v!==1)throw new Error(`Unsupported token version: ${r.v}`);return r}function Sb(t){let e=JSON.stringify(t),n=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return _b+n}function Qi(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{}}function d5(){if(typeof window>"u")return G("Syntro Bootstrap","isEditorMode: not in browser"),!1;let t=Oa(),n=!!(Dr()?.token&&t?.mode==="editor");return G("Syntro Bootstrap","isEditorMode:",n),n}function f5(){if(typeof window>"u")return G("Syntro Bootstrap","isAuditMode: not in browser"),!1;let t=Oa(),n=!!(Dr()?.token&&t?.mode==="audit");return G("Syntro Bootstrap","isAuditMode:",n),n}function p5(){if(typeof window>"u")return G("Syntro Bootstrap","isReviewMode: not in browser"),!1;let t=Oa(),n=!!(Dr()?.token&&t?.mode==="review");return G("Syntro Bootstrap","isReviewMode:",n),n}var uk="syntro_segment_attributes";function h5(){if(typeof window>"u")return{};try{let t=localStorage.getItem(uk);if(t){let e=JSON.parse(t);return G("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){cn("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function g5(t){if(!(typeof window>"u"))try{localStorage.setItem(uk,JSON.stringify(t)),G("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){cn("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function m5(t){if(!t)return{};let e={};for(let[n,i]of Object.entries(t))n.startsWith("in_segment_")&&(e[n]=i===!0);return e}async function v5(t){um(),G("Syntro Bootstrap","====== INIT ======"),G("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=d5(),n=f5(),i=p5(),r=e?"editor":n?"audit":i?"review":null;if(console.log(`[DIAG] Mode detection: editor=${e}, audit=${n}, review=${i}, sdkMode=${r}`),console.log("[DIAG] editorSource:",Dr()),console.log("[DIAG] editorConf:",Oa()),G("Syntro Bootstrap","SDK mode:",r??"normal"),!r&&typeof window<"u"){let x=!!window.__SYNTRO_EDITOR_PARAMS__,M=!!window.__SYNTRO_AUDIT_LEGEND__,z=!!window.__SYNTRO_REVIEW_DATA__;if(x||M||z){let U=[x&&"__SYNTRO_EDITOR_PARAMS__",M&&"__SYNTRO_AUDIT_LEGEND__",z&&"__SYNTRO_REVIEW_DATA__"].filter(Boolean);console.warn(`[Syntro Bootstrap] \u26A0 Mode detection returned null but mode-specific globals found: ${U.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&&r){let M=Oa()?.syntro_token;M?.startsWith("syn_")&&(a=M,G("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${r} mode)`))}let o;if(a)if(a.startsWith("syn_"))G("Syntro Bootstrap","Token starts with syn_, decoding..."),o=np(a),um(o.d);else if(r)G("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${r} mode)`);else throw Hd("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),Hd("Syntro Bootstrap","Token received:",a),new Error("Invalid Syntro token: must start with 'syn_'");else if(r)G("Syntro Bootstrap",`\u2713 No token, but ${r} mode - proceeding`);else throw Hd("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 s=Qi("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||Qi("VITE_SYNTRO_EXPERIMENT_HOST")||o?.eh,l=Qi("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||Qi("VITE_SYNTRO_TELEMETRY_HOST")||o?.th,c=Qi("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||Qi("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,u=h5();G("Syntro Bootstrap","Phase 1: Using cached segment attributes:",u);let f,h=Lc();console.log("[Syntro Bootstrap] EventBus created");let g=nb(x=>{h.publishEvent(x)}),_=x=>{G("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let M=m5(x);if(G("Syntro Bootstrap","Segment flags from PostHog:",M),g5(M),f){let U={...w?.getAll?.()??{},...M};G("Syntro Bootstrap","Updating GrowthBook with attributes:",U),f.setAttributes?.(U)}},b;if(o?.t){let x=o.t==="noop"?"noop":"posthog";b=ck(x,{apiKey:o.t,apiHost:l,enableFeatureFlags:!0,onFeatureFlagsLoaded:_,onCapture:g}),console.log(`[Syntro Bootstrap] Telemetry client created (${x}) with EventBus wiring`)}let w;o?.e&&(f=ik("growthbook",{clientKey:o.e,apiHost:s,attributes:u,onExperimentViewed:b?.trackExperiment?(x,M,z)=>{b.trackExperiment(x,M,z)}:void 0})),t.enableSessionMetrics&&(w=Wm({experiments:f,onMetricChange:(x,M)=>{G("Syntro Bootstrap",`Session metric changed: ${x} = ${M}`)}}),G("Syntro Bootstrap","SessionMetricTracker created"));let d="production";e?d="editor":n?d="audit":Qi("NODE_ENV")==="development"&&(d="development");let p=vb({telemetry:b,sessionMetrics:w,mode:d,events:h});G("Syntro Bootstrap","Runtime created:",{version:p.version,mode:p.mode,hasContext:!!p.context,hasEvents:!!p.events,hasState:!!p.state}),G("Syntro Bootstrap","Core app executors already registered");let m=t.cdnBase||Qi("NEXT_PUBLIC_SYNTRO_CDN_BASE")||Qi("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",v=rm({cdnBase:m,registry:p.apps,onLoadStart:x=>{G("Syntro Bootstrap",`Loading app from CDN: ${x}`)},onLoadEnd:(x,M,z)=>{M?G("Syntro Bootstrap",`App loaded successfully: ${x}`):cn("Syntro Bootstrap",`Failed to load app: ${x}`,z)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:p.apps,runtime:p,version:p.version},G("Syntro Bootstrap","Global SynOS object exposed"));let S=p.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${S.length} apps in registry:`,S.map(x=>`${x.manifest.id}(${x.state})`).join(", "));for(let x of S)if(x.state==="registered")try{await p.apps.activate(x.manifest.id),console.log(`[DIAG] Activated: ${x.manifest.id} \u2192 widgets: [${p.widgets.list().join(", ")}]`)}catch(M){console.error(`[DIAG] FAILED to activate: ${x.manifest.id}`,M),cn("Syntro Bootstrap",`Failed to auto-activate built-in app: ${x.manifest.id}`,M)}if(console.log(`[DIAG] Activation complete. Total widgets: [${p.widgets.list().join(", ")}]`),f?.refreshFeatures)try{await f.refreshFeatures(),G("Syntro Bootstrap","GrowthBook features loaded")}catch(x){cn("Syntro Bootstrap","Failed to load GrowthBook features:",x)}let T;if(t.fetcher)T=t.fetcher;else if(o?.f){let x=sk(o.f,o.o??{});T=async()=>{let M=await x.fetch();return{...M.config,tiles:M.config.tiles??[]}}}else f&&(T=es({experiments:f}));let A=new Set,k=T?async()=>{let x=await T();console.log("[Syntro Bootstrap] Config fetched:",`tiles=${x.tiles?.length??0},`,`actions=${x.actions?.length??0},`,`theme=${x.theme?.name??"none"}`),x.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",x.actions.map((U,P)=>`[${P}] ${U.kind}${U.anchorId?` anchor="${U.anchorId}"`:""}${U.label?` "${U.label}"`:""}`).join(", "));let M=x,z=v.getRequiredApps(M);return z.length>0?console.log("[Syntro Bootstrap] Required external apps:",z.join(", ")):G("Syntro Bootstrap","No external apps required (all executors are built-in)"),z.length>0&&await v.loadAppsForConfig(M).then(async P=>{let Z=P.filter(D=>D.success),X=P.filter(D=>!D.success);Z.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${Z.map(D=>D.appId).join(", ")}`);let W=X.filter(D=>!A.has(D.appId));W.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",W.map(D=>`${D.appId} (${D.error})`).join(", ")),W.forEach(D=>A.add(D.appId)));for(let D of z)if(p.apps.has(D))try{await p.apps.activate(D),console.log(`[Syntro Bootstrap] App activated: ${D}`)}catch(L){console.error(`[Syntro Bootstrap] Failed to activate app: ${D}`,L)}else console.error(`[Syntro Bootstrap] App "${D}" required by config but NOT registered.`,`Available apps: [${Array.from(p.apps.list?.()??[]).join(", ")}]`)}),x}:void 0;return{canvas:await Rm({...t.canvas,fetcher:k,integrations:{experiments:f,telemetry:b},editorUrl:c,runtime:p}),runtime:p,experiments:f,telemetry:b,sessionMetrics:w,appLoader:v}}var dk={init:v5,encodeToken:Sb,decodeToken:np};typeof window<"u"&&(window.Syntro=dk);var fk="2026-02-26T20:06:39.444Z (ba85f6525)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${fk}`);let t=window.SynOS,e=t?.appRegistry||Vl;window.SynOS={...t,appRegistry:e,_runtimeBuild:fk,React:pk.default,ReactDOM:{...y5,createPortal:ip.createPortal,flushSync:ip.flushSync}},kw(e)}export{Bc as ANIMATION_KEYFRAMES,Yf as ActivationConfigZ,xT as AddClassZ,G3 as AnchorStateZ,O3 as AnchorVisibleConditionZ,Od as AppRegistry,Z3 as AugmentationZ,dT as BadgePositionZ,kT as BadgeZ,P3 as BoundingBoxZ,Gl as CanvasEvents,Jm as CanvasRecipeZ,Yy as ConditionZ,Wf as ContextManager,I3 as CooldownActiveConditionZ,Ky as CtaButtonZ,bm as DEFAULT_COOLDOWN,ym as DEFAULT_TTL,lT as DecisionStrategyZ,H3 as DismissedConditionZ,is as EVENT_SCHEMA_VERSION,Qf as EventBus,B3 as EventCountConditionZ,Q3 as EventFilterZ,M3 as EventOccurredConditionZ,ZT as EventSourceZ,Zf as ExecutorRegistry,sT as ExternalStrategyZ,r5 as FrequencyEntryZ,z3 as FrequencyLimitConditionZ,O4 as HighlightStepZ,uT as HighlightStyleZ,AT as HighlightZ,CT as InsertHtmlZ,gT as InsertPositionZ,vm as MAX_VISIBLE_TOASTS,hT as ModalContentZ,OT as ModalZ,oT as ModelStrategyZ,DT as MountWidgetZ,NT as NavigateZ,Hc as NavigationMonitor,X3 as NormalizedEventZ,mm as NotificationToastStack,U3 as PageContextZ,V3 as PageHistoryEntryZ,k3 as PageUrlConditionZ,IT as ParallelZ,fT as PlacementZ,TT as PulseZ,fk as RUNTIME_SDK_BUILD,tk as RUNTIME_VERSION,wT as RemoveClassZ,R3 as RouteConditionZ,cT as RouteFilterZ,rT as RuleStrategyZ,iT as RuleZ,Y3 as RuntimeContextZ,Em as RuntimeProvider,Nr as SDK_SCHEMA_VERSION,dm as SDK_VERSION,XT as STATIC_SLOT_STYLES,aT as ScoreStrategyZ,bT as ScrollBehaviorZ,Wy as ScrollLogicalPositionZ,MT as ScrollToZ,XE as SelectorZ,HT as SequenceZ,j3 as SessionContextZ,L3 as SessionMetricConditionZ,af as SessionMetricTracker,ST as SetAttrZ,ET as SetStyleZ,_T as SetTextZ,Zw as ShadowCanvasOverlay,Vw as ShadowRootProvider,Kw as SmartCanvasApp,pm as SmartCanvasController,Tm as SmartCanvasElement,vB as SmartCanvasPortal,_e as StandardEvents,N3 as StateEqualsConditionZ,Jf as StateStore,i5 as StoredValueZ,dk as Syntro,Zl as TileCard,o6 as TileWheel,pT as TooltipContentZ,R4 as TooltipStepZ,mT as TooltipTriggerZ,RT as TooltipZ,yT as TourStepForSchemaZ,zT as TourZ,D3 as ViewportConditionZ,q3 as ViewportContextZ,LT as WaitZ,vT as WidgetConfigZ,tp as WidgetRegistry,Vl as appRegistry,lb as applyStaticSlotStyles,nm as cleanupAppContext,Zg as contentRuntime,$3 as coreActionStepSchemas,Zy as createActionEngine,tm as createAppContext,rm as createAppLoader,es as createCanvasConfigFetcher,Qy as createContextManager,Jy as createDecisionEngine,eb as createEventAccumulator,Lc as createEventBus,Ym as createGrowthBookClient,tv as createNoopClient,gB as createOverlayRecipeFetcher,By as createPostHogClient,nb as createPostHogNormalizer,Wm as createSessionMetricTracker,Rm as createSmartCanvas,Fw as createSmartCanvasController,vb as createSmartCanvasRuntime,sb as createStateStore,pb as createSurfaceContainer,gb as createSurfaces,t$ as decisionSchemas,np as decodeToken,Sb as encodeToken,VT as evaluate,$T as evaluateCondition,FT as evaluateRule,Kf as evaluateRuleStrategy,Xf as evaluateScoreStrategy,jT as evaluateSync,Xi as executorRegistry,TM as getAntiFlickerSnippet,uw as getAppIdFromActionKind,im as getAppIdFromWidgetId,d3 as getExecutor,ep as getSlotAnchorId,zc as getSlotType,hb as getSlotZIndex,Py as hasExecutor,Bd as interpolateTemplate,cw as isCoreActionKind,_m as matchEvent,u6 as needsMigration,PT as normalizePostHogEvent,em as overlaysRuntime,Wl as parseVersion,db as playEnterAnimation,fb as playExitAnimation,Pl as registerConfigPredicates,eE as registerSmartCanvasElement,fm as resolveConfigUri,cb as setupAdjacentPositioning,ub as setupInlinePositioning,GT as shouldNormalizeEvent,uN as useDecision,Sm as useNotifications,xm as useNotifyWatcher,Cm as usePageContext,Ii as useRuntime,Fd as useRuntimeContext,lN as useRuntimeEvents,cN as useRuntimeState,oN as useSessionContext,Yw as useShadowCanvasConfig,zd as useShadowRoot,sN as useViewportContext,na as validateAction,Gy as validateActions,e$ as validateActivationConfig,QB as validateCondition,c6 as validateConfig,$$ as validateEventFilter,V8 as validateFrequencyEntry,B$ as validateNormalizedEvent,dB as validateRecipe,h$ as validateRuntimeContext,U8 as validateStoredValue,JB as validateStrategy,mb as widgetRegistry};
449
+ `)),new Error(`Batch validation failed: ${k}`)}let v=c(),S=[],T=[];try{for(let k of p){let C=await g(k);S.push(C),T.push(C)}}catch(k){console.error(`[ActionEngine] Batch apply FAILED at action ${T.length+1}/${p.length}.`,`Successfully applied: ${T.length}. Rolling back...`,k);for(let C of T)try{await C.revert()}catch{}throw k}return{id:v,handles:S,async revertAll(){for(let k=S.length-1;k>=0;k--)try{await S[k].revert()}catch(C){console.error(`[ActionEngine] Error reverting action ${S[k].id}:`,C)}},isApplied(){return S.every(k=>k.isApplied())}}}function b(p){return na(p)}function w(){return Array.from(l.values()).map(p=>({id:p.id,action:p.action,adaptiveId:p.adaptiveId,appliedTs:p.appliedTs,state:p.state}))}function d(){for(let p of l.values())if(p.state==="applied")try{p.cleanup()}catch(m){console.error("[ActionEngine] Error during cleanup:",m)}l.clear()}return{apply:g,applyBatch:_,validate:b,getActive:w,destroy:d}}var k3=y.object({type:y.literal("page_url"),url:y.string()}),R3=y.object({type:y.literal("route"),routeId:y.string()}),O3=y.object({type:y.literal("anchor_visible"),anchorId:y.string(),state:y.enum(["visible","present","absent"])}),M3=y.object({type:y.literal("event_occurred"),eventName:y.string(),withinMs:y.number().optional()}),N3=y.object({type:y.literal("state_equals"),key:y.string(),value:y.unknown()}),D3=y.object({type:y.literal("viewport"),minWidth:y.number().optional(),maxWidth:y.number().optional(),minHeight:y.number().optional(),maxHeight:y.number().optional()}),L3=y.object({type:y.literal("session_metric"),key:y.string(),operator:y.enum(["gte","lte","eq","gt","lt"]),threshold:y.number()}),H3=y.object({type:y.literal("dismissed"),key:y.string(),inverted:y.boolean().optional()}),I3=y.object({type:y.literal("cooldown_active"),key:y.string(),inverted:y.boolean().optional()}),z3=y.object({type:y.literal("frequency_limit"),key:y.string(),limit:y.number(),inverted:y.boolean().optional()}),B3=y.object({type:y.literal("event_count"),key:y.string(),operator:y.enum(["gte","lte","eq","gt","lt"]),count:y.number().int().min(0),withinMs:y.number().positive().optional()}),Yy=y.discriminatedUnion("type",[k3,R3,O3,M3,N3,D3,L3,H3,I3,z3,B3]),iT=y.object({conditions:y.array(Yy),value:y.unknown()}),rT=y.object({type:y.literal("rules"),rules:y.array(iT),default:y.unknown()}),aT=y.object({type:y.literal("score"),field:y.string(),threshold:y.number(),above:y.unknown(),below:y.unknown()}),oT=y.object({type:y.literal("model"),modelId:y.string(),inputs:y.array(y.string()),outputMapping:y.record(y.string(),y.unknown()),default:y.unknown()}),sT=y.object({type:y.literal("external"),endpoint:y.string(),method:y.enum(["GET","POST"]).optional(),default:y.unknown(),timeoutMs:y.number().optional()}),lT=y.discriminatedUnion("type",[rT,aT,oT,sT]),cT=y.object({include:y.array(y.string()).optional(),exclude:y.array(y.string()).optional()}),Yf=y.object({routes:cT,strategy:lT.optional()});function QB(t){return Yy.safeParse(t)}function JB(t){return lT.safeParse(t)}function e$(t){return Yf.safeParse(t)}var t$=[{defName:"activationConfig",schema:Yf},{defName:"routeFilter",schema:cT},{defName:"ruleStrategy",schema:rT},{defName:"scoreStrategy",schema:aT},{defName:"modelStrategy",schema:oT},{defName:"externalStrategy",schema:sT},{defName:"rule",schema:iT},{defName:"condition",schema:Yy}];var pt={activation:Yf.optional()},uT=y.object({color:y.string().optional(),scrimOpacity:y.number().min(0).max(1).optional(),paddingPx:y.number().optional(),radiusPx:y.number().optional()}).strict(),dT=y.enum(["top-left","top-right","bottom-left","bottom-right"]),fT=y.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),Ky=y.object({label:y.string(),actionId:y.string(),primary:y.boolean().optional()}).strict(),pT=y.object({title:y.string().optional(),body:y.string(),ctaButtons:y.array(Ky).optional()}).strict(),hT=y.object({title:y.string().optional(),body:y.string()}).strict(),gT=y.enum(["before","after","prepend","append","replace"]),mT=y.enum(["immediate","hover","click"]),vT=y.object({widgetId:y.string(),props:y.record(y.unknown()).optional(),priority:y.number().optional()}).strict(),yT=y.object({id:y.string(),action:y.any(),route:y.string().optional(),onAction:y.record(y.string()).optional()}).strict(),bT=y.enum(["auto","smooth","instant"]),Wy=y.enum(["start","center","end","nearest"]),_T=y.object({kind:y.literal("content:setText"),anchorId:y.string(),text:y.string(),label:y.string().optional()}).extend(pt).strict(),ST=y.object({kind:y.literal("content:setAttr"),anchorId:y.string(),attr:y.string(),value:y.string(),label:y.string().optional()}).extend(pt).strict(),xT=y.object({kind:y.literal("content:addClass"),anchorId:y.string(),className:y.string(),label:y.string().optional()}).extend(pt).strict(),wT=y.object({kind:y.literal("content:removeClass"),anchorId:y.string(),className:y.string(),label:y.string().optional()}).extend(pt).strict(),ET=y.object({kind:y.literal("content:setStyle"),anchorId:y.string(),styles:y.record(y.string()),label:y.string().optional()}).extend(pt).strict(),CT=y.object({kind:y.literal("content:insertHtml"),anchorId:y.string(),html:y.string(),position:gT,label:y.string().optional()}).extend(pt).strict(),AT=y.object({kind:y.literal("overlays:highlight"),anchorId:y.string(),style:uT.optional(),duration:y.number().optional(),label:y.string().optional()}).extend(pt).strict(),TT=y.object({kind:y.literal("overlays:pulse"),anchorId:y.string(),duration:y.number().optional(),label:y.string().optional()}).extend(pt).strict(),kT=y.object({kind:y.literal("overlays:badge"),anchorId:y.string(),content:y.string(),position:dT.optional(),label:y.string().optional()}).extend(pt).strict(),RT=y.object({kind:y.literal("overlays:tooltip"),anchorId:y.string(),content:pT,trigger:mT.optional(),placement:fT.optional(),waitFor:y.string().optional(),label:y.string().optional()}).extend(pt).strict(),OT=y.object({kind:y.literal("overlays:modal"),content:hT,size:y.enum(["sm","md","lg"]).optional(),blocking:y.boolean().optional(),scrim:y.object({opacity:y.number().min(0).max(1).optional()}).strict().optional(),dismiss:y.object({onEsc:y.boolean().optional(),closeButton:y.boolean().optional(),timeoutMs:y.number().min(0).optional()}).strict().optional(),ctaButtons:y.array(Ky).optional(),waitFor:y.string().optional(),label:y.string().optional()}).extend(pt).strict(),MT=y.object({kind:y.literal("navigation:scrollTo"),anchorId:y.string(),behavior:bT.optional(),block:Wy.optional(),inline:Wy.optional(),label:y.string().optional()}).extend(pt).strict(),NT=y.object({kind:y.literal("navigation:navigate"),url:y.string(),target:y.enum(["_self","_blank"]).optional(),label:y.string().optional()}).extend(pt).strict(),DT=y.object({kind:y.literal("core:mountWidget"),slot:y.string(),widget:vT,label:y.string().optional()}).extend(pt).strict(),LT=y.object({kind:y.literal("core:wait"),durationMs:y.number().min(0).optional(),event:y.string().optional(),label:y.string().optional()}).extend(pt).strict(),HT=y.object({kind:y.literal("core:sequence"),actions:y.array(y.any()),label:y.string().optional()}).extend(pt).strict(),IT=y.object({kind:y.literal("core:parallel"),actions:y.array(y.any()),waitFor:y.enum(["all","any"]).optional(),label:y.string().optional()}).extend(pt).strict(),zT=y.object({kind:y.literal("core:tour"),tourId:y.string(),steps:y.array(yT).min(1),startStep:y.string().optional(),autoStart:y.boolean().optional(),label:y.string().optional()}).extend(pt).strict(),$3=[{defName:"setText",schema:_T},{defName:"setAttr",schema:ST},{defName:"addClass",schema:xT},{defName:"removeClass",schema:wT},{defName:"setStyle",schema:ET},{defName:"insertHtml",schema:CT},{defName:"highlight",schema:AT},{defName:"pulse",schema:TT},{defName:"badge",schema:kT},{defName:"tooltip",schema:RT},{defName:"modal",schema:OT},{defName:"scrollTo",schema:MT},{defName:"navigate",schema:NT},{defName:"mountWidget",schema:DT},{defName:"wait",schema:LT},{defName:"sequence",schema:HT},{defName:"parallel",schema:IT},{defName:"tour",schema:zT}];function F3(){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 Xy(t,e){if(!e)return;let n;try{n=new URL(t).pathname}catch{n=t}if(e.exclude){for(let i of e.exclude)if(BT(n,i))return}if(e.include){for(let i of e.include)if(BT(n,i))return i;return}return n}function BT(t,e){let n=t.replace(/\/$/,"")||"/",i=e.replace(/\/$/,"")||"/";if(n===i)return!0;let r=i.replace(/:[^/]+/g,"[^/]+").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(n)}var Wf=class{constructor(e={}){V(this,"context");V(this,"previousContext");V(this,"listeners",new Set);V(this,"telemetry");V(this,"routes");V(this,"navigation");V(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=F3(),this.previousContext={...this.context},e.telemetry?.getSessionId){let n=e.telemetry.getSessionId();n&&(this.context.session.sessionId=n)}e.initialPageHistory&&(this.context.session.pageHistory=e.initialPageHistory),this.context.page.routeId=Xy(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 n=Xy(this.context.page.url,this.routes);n!==this.context.page.routeId&&this.updateContext({page:{...this.context.page,routeId:n}})}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,n=()=>{clearTimeout(e),e=setTimeout(()=>{this.updateViewport()},100)};if(window.addEventListener("resize",n),this.cleanupFns.push(()=>window.removeEventListener("resize",n)),this.navigation){let i=this.navigation.subscribe(()=>this.updatePage());this.cleanupFns.push(i)}else{let i=()=>{this.updatePage()};window.addEventListener("popstate",i),this.cleanupFns.push(()=>window.removeEventListener("popstate",i));let r=history.pushState.bind(history),a=history.replaceState.bind(history);history.pushState=(...o)=>{r(...o),queueMicrotask(()=>this.updatePage())},history.replaceState=(...o)=>{a(...o),queueMicrotask(()=>this.updatePage())},this.cleanupFns.push(()=>{history.pushState=r,history.replaceState=a})}}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:n}=document,i=Xy(e,this.routes),r={url:e,title:n,routeId:i};(r.url!==this.context.page.url||r.title!==this.context.page.title||r.routeId!==this.context.page.routeId)&&(r.url!==this.context.page.url&&this.addPageToHistory(r.url),this.updateContext({page:r}))}addPageToHistory(e){let n={url:e,ts:Date.now()},i=[...this.context.session.pageHistory||[],n];i.length>50&&i.shift(),this.context.session.pageHistory=i}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(n){console.error("[ContextManager] Listener error:",n)}}};function Qy(t={}){return new Wf(t)}var U3=y.object({url:y.string(),routeId:y.string().optional(),title:y.string().optional(),locale:y.string().optional()}),V3=y.object({url:y.string(),ts:y.number()}),j3=y.object({sessionId:y.string(),startTs:y.number(),pageHistory:y.array(V3).optional()}),q3=y.object({width:y.number(),height:y.number()}),P3=y.object({x:y.number(),y:y.number(),w:y.number(),h:y.number()}),G3=y.object({anchorId:y.string(),present:y.boolean(),visible:y.boolean().optional(),boundingBox:P3.optional()}),Z3=y.record(y.string(),y.union([y.number(),y.string(),y.boolean(),y.undefined()])),Y3=y.object({page:U3,session:j3,viewport:q3,anchors:y.array(G3).optional(),augmented:Z3.optional()});function h$(t){return Y3.safeParse(t)}function $T(t,e){let{context:n,state:i,events:r}=e;switch(t.type){case"page_url":{let{url:a}=t,o=n.page.url,s=a.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*");return new RegExp(`^${s}$`).test(o)}case"route":return n.page.routeId===t.routeId;case"anchor_visible":{let a=n.anchors?.find(o=>o.anchorId===t.anchorId);switch(t.state){case"visible":return a?.visible===!0;case"present":return a?.present===!0;case"absent":return!a?.present;default:return!1}}case"event_occurred":{if(!r)return!1;let a=t.withinMs??6e4;return r.hasRecentEvent(t.eventName,a)}case"state_equals":return!1;case"viewport":{let{width:a,height:o}=n.viewport;return!(t.minWidth!==void 0&&a<t.minWidth||t.maxWidth!==void 0&&a>t.maxWidth||t.minHeight!==void 0&&o<t.minHeight||t.maxHeight!==void 0&&o>t.maxHeight)}case"session_metric":{if(!i)return!1;let a=i.getSessionMetric(t.key),{operator:o,threshold:s}=t;switch(o){case"gte":return a>=s;case"lte":return a<=s;case"eq":return a===s;case"gt":return a>s;case"lt":return a<s;default:return!1}}case"dismissed":{if(!i)return t.inverted??!1;let a=i.isDismissed(t.key);return t.inverted?!a:a}case"cooldown_active":{if(!i)return t.inverted??!1;let a=i.isCooldownActive(t.key);return t.inverted?!a:a}case"frequency_limit":{if(!i)return t.inverted??!1;let o=i.getFrequencyCount(t.key)>=t.limit;return t.inverted?!o:o}case"event_count":{if(!e.accumulator)return!1;let a=t,o=e.accumulator.getCount(a.key,a.withinMs);switch(a.operator){case"gte":return o>=a.count;case"lte":return o<=a.count;case"eq":return o===a.count;case"gt":return o>a.count;case"lt":return o<a.count;default:return!1}}default:return console.warn("[RuleStrategy] Unknown condition type:",t.type),!1}}function FT(t,e){let n=[];for(let i of t.conditions){let r=$T(i,e);if(n.push({condition:i,result:r}),!r)return{matched:!1,conditionResults:n}}return{matched:!0,conditionResults:n}}function Kf(t,e){for(let n=0;n<t.rules.length;n++){let i=t.rules[n],{matched:r,conditionResults:a}=FT(i,e);if(r)return{value:i.value,isFallback:!1,matchInfo:{strategyType:"rules",matchedRuleIndex:n,evaluatedConditions:a}}}return{value:t.default,isFallback:!0,matchInfo:{strategyType:"rules"}}}function Xf(t,e){let{context:n}=e,i=n.augmented?.[t.field];return i===void 0||typeof i!="number"?{value:t.below,isFallback:!0,matchInfo:{strategyType:"score"}}:{value:i>=t.threshold?t.above:t.below,isFallback:!1,matchInfo:{strategyType:"score"}}}function UT(t,e){let{state:n,events:i,sessionMetrics:r,accumulator:a}=e;return{context:t,state:n?{isDismissed:o=>n.dismissals.isDismissed(o),isCooldownActive:o=>n.cooldowns.isActive(o),getFrequencyCount:o=>n.frequency.count(o),getSessionMetric:o=>r?.get(o)??0}:void 0,events:i?{hasRecentEvent:(o,s)=>i.hasRecentEvent(o,s)}:void 0,accumulator:a?{getCount:(o,s)=>a.getCount(o,s)}:void 0}}async function VT(t,e,n={}){let i=UT(e,n);switch(t.type){case"rules":return Kf(t,i);case"score":return Xf(t,i);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 jT(t,e,n={}){let i=UT(e,n);switch(t.type){case"rules":return Kf(t,i);case"score":return Xf(t,i);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 Jy(t){return{evaluate:(e,n)=>VT(e,n,t),evaluateSync:(e,n)=>jT(e,n,t)}}function eb(t){let{eventBus:e,stateStore:n}=t,i=new Map,r=new Set,a=null,o=n.ns("accumulator");function s(c){let u=!1;for(let f of i.values()){if(!f.predicate(c))continue;let h=o.get(f.stateKey)||{count:0};h.count++,f.needsTimestamps&&(h.timestamps||(h.timestamps=[]),h.timestamps.push(c.ts),h.timestamps.length>200&&(h.timestamps=h.timestamps.slice(-200))),o.set(f.stateKey,h),u=!0}if(u)for(let f of r)try{f()}catch(h){console.error("[EventAccumulator] Subscriber error:",h)}}function l(){a||i.size===0||(a=e.subscribe(s))}return{register(c,u,f=!1){let h=`ev:${c}`,g=i.get(h);if(g){f&&!g.needsTimestamps&&(g.needsTimestamps=!0);return}i.set(h,{stateKey:h,needsTimestamps:f,predicate:u}),l()},getCount(c,u){let f=`ev:${c}`,h=o.get(f);if(!h)return 0;if(u===void 0||!h.timestamps)return h.count;let g=Date.now()-u;return h.timestamps.filter(_=>_>=g).length},subscribe(c){return r.add(c),()=>{r.delete(c)}},destroy(){a&&(a(),a=null),i.clear(),r.clear()}}}function tb(t,e){return e?!(e.names&&e.names.length>0&&!e.names.includes(t.name)||e.patterns&&e.patterns.length>0&&!e.patterns.some(i=>{try{return new RegExp(i).test(t.name)}catch{return!1}})||e.sources&&e.sources.length>0&&!e.sources.includes(t.source)):!0}var Qf=class{constructor(e={}){V(this,"subscriptions",new Set);V(this,"history",[]);V(this,"maxHistorySize");this.maxHistorySize=e.maxHistorySize??100}subscribe(e,n){let i,r;typeof e=="function"?(i=void 0,r=e):(i=e,r=n);let a={filter:i,callback:r};return this.subscriptions.add(a),()=>{this.subscriptions.delete(a)}}publish(e,n,i="canvas"){let r={ts:Date.now(),name:e,source:i,props:n,schemaVersion:is};this.publishEvent(r)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let n of this.subscriptions)if(tb(e,n.filter))try{n.callback(e)}catch(i){console.error("[EventBus] Subscriber error:",i)}}getRecent(e,n){let i=this.history;return e&&(i=i.filter(r=>tb(r,e))),n&&n>0&&(i=i.slice(-n)),i}hasRecentEvent(e,n,i){let r=Date.now()-n;return this.history.some(a=>a.name===e&&a.ts>=r&&(i===void 0||a.source===i))}countRecentEvents(e,n){let i=this.history.filter(r=>tb(r,e));if(n!==void 0){let r=Date.now()-n;i=i.filter(a=>a.ts>=r)}return i.length}clearHistory(){this.history=[]}getSubscriberCount(){return this.subscriptions.size}};function Lc(t={}){return new Qf(t)}var qT={$autocapture:"ui.click",$click:_e.UI_CLICK,$scroll:_e.UI_SCROLL,$input:_e.UI_INPUT,$change:_e.UI_CHANGE,$submit:_e.UI_SUBMIT,$pageview:_e.NAV_PAGE_VIEW,$pageleave:_e.NAV_PAGE_LEAVE,$session_start:"session.start",$identify:"user.identify"};function W3(t){let e=t.event;if(typeof e!="string")return"posthog.unknown";if(qT[e])return qT[e];if(e==="$autocapture"){let n=t.properties?.$tag_name,i=t.properties?.$event_type;return i==="submit"?_e.UI_SUBMIT:i==="change"?_e.UI_CHANGE:n==="input"||n==="textarea"?_e.UI_INPUT:_e.UI_CLICK}return e.startsWith("$")?e.replace("$","posthog."):`posthog.${e}`}function K3(t){let e={},n=t.properties||{},i=n.$elements;return n.$tag_name?e.tagName=n.$tag_name:i?.[0]?.tag_name&&(e.tagName=i[0].tag_name),n.$el_text&&(e.elementText=n.$el_text),i&&(e.elements=i),n.$current_url&&(e.url=n.$current_url),n.$pathname&&(e.pathname=n.$pathname),n.$host&&(e.host=n.$host),n.$viewport_width&&(e.viewportWidth=n.$viewport_width),n.$viewport_height&&(e.viewportHeight=n.$viewport_height),n.$session_id&&(e.sessionId=n.$session_id),n.$scroll_depth&&(e.scrollDepth=n.$scroll_depth),n.$scroll_percentage&&(e.scrollPercentage=n.$scroll_percentage),e.originalEvent=t.event,e}function PT(t){let e;return typeof t.timestamp=="number"?e=t.timestamp:typeof t.timestamp=="string"?e=new Date(t.timestamp).getTime():e=Date.now(),{ts:e,name:W3(t),source:"posthog",props:K3(t),schemaVersion:is}}function GT(t){let e=t.event;return!(typeof e!="string"||["$feature_flag_called","$feature_flags","$groups","$groupidentify","$set","$set_once","$unset","$create_alias","$capture_metrics","$performance_event","$web_vitals","$exception","$dead_click","$heatmap"].includes(e))}function nb(t){return(e,n)=>{if(typeof e!="string")return;let i={event:e,properties:n,timestamp:Date.now()};if(GT(i)){let r=PT(i);t(r)}}}var ZT=y.enum(["posthog","canvas","derived"]),X3=y.object({ts:y.number(),name:y.string(),source:ZT,props:y.record(y.string(),y.unknown()).optional(),schemaVersion:y.string()}),Q3=y.object({names:y.array(y.string()).optional(),patterns:y.array(y.string()).optional(),sources:y.array(ZT).optional()});function B$(t){return X3.safeParse(t)}function $$(t){return Q3.safeParse(t)}var Hc=class{constructor(){V(this,"listeners",new Set);V(this,"capturedPushState");V(this,"capturedReplaceState");V(this,"wasNative");V(this,"destroyed",!1);V(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,n){if(!this.destroyed)for(let i of this.listeners)try{i(e,n)}catch{}}isNativeFunction(e){try{return Function.prototype.toString.call(e).includes("[native code]")}catch{return!1}}};var ib="cooldown:";function YT(t){return{set(e,n){let i=ib+e,r=Date.now()+n;t.set(i,r)},isActive(e){return this.remaining(e)>0},remaining(e){let n=ib+e,i=t.get(n);if(i===void 0)return 0;let r=i-Date.now();return r<=0?(t.remove(n),0):r},clear(e){let n=ib+e;t.remove(n)}}}var Ic="dismissed:";function WT(t,e){return{mark(n,i=!1){let r=Ic+n;(i?e:t).set(r,!0)},isDismissed(n){let i=Ic+n;return t.has(i)||e.has(i)},clear(n){let i=Ic+n;t.remove(i),e.remove(i)},clearAll(){for(let n of t.keys())n.startsWith(Ic)&&t.remove(n);for(let n of e.keys())n.startsWith(Ic)&&e.remove(n)}}}var rb="freq:";function KT(t){function e(n){let i=rb+n,r=t.get(i);if(r){if(r.resetAt&&Date.now()>=r.resetAt){t.remove(i);return}return r}}return{increment(n,i){let r=rb+n,a=e(n),o=(a?.count??0)+1,s={count:o,resetAt:a?.resetAt??(i?Date.now()+i:void 0)};return t.set(r,s),o},count(n){return e(n)?.count??0},reset(n){let i=rb+n;t.remove(i)},hasReachedLimit(n,i){return this.count(n)>=i}}}var J3="syntro";function ab(t,e){let n=`${e}:`;return{get(i){if(t)try{let r=t.getItem(n+i);if(!r)return;let a=JSON.parse(r);if(a.expiresAt&&Date.now()>=a.expiresAt){t.removeItem(n+i);return}return a.value}catch{return}},set(i,r,a){if(t)try{let o={value:r,expiresAt:a?Date.now()+a:void 0};t.setItem(n+i,JSON.stringify(o))}catch(o){console.warn("[StateStore] Failed to save:",o)}},remove(i){t&&t.removeItem(n+i)},has(i){return t?this.get(i)!==void 0:!1},keys(){if(!t)return[];let i=[];for(let r=0;r<t.length;r++){let a=t.key(r);a?.startsWith(n)&&i.push(a.slice(n.length))}return i},clear(){if(!t)return;let i=this.keys();for(let r of i)t.removeItem(n+r)}}}function ob(t){let e=new Map,n=`${t}:`;return{get(i){let r=e.get(n+i);if(r){if(r.expiresAt&&Date.now()>=r.expiresAt){e.delete(n+i);return}return r.value}},set(i,r,a){e.set(n+i,{value:r,expiresAt:a?Date.now()+a:void 0})},remove(i){e.delete(n+i)},has(i){return this.get(i)!==void 0},keys(){let i=[];for(let r of e.keys())r.startsWith(n)&&i.push(r.slice(n.length));return i},clear(){for(let i of e.keys())i.startsWith(n)&&e.delete(i)}}}var Jf=class{constructor(e={}){V(this,"session");V(this,"user");V(this,"dismissals");V(this,"cooldowns");V(this,"frequency");V(this,"namespace");V(this,"namespacedStorages",new Map);this.namespace=e.namespace??J3,typeof window<"u"?(this.session=ab(typeof sessionStorage<"u"?sessionStorage:void 0,this.namespace),this.user=ab(typeof localStorage<"u"?localStorage:void 0,this.namespace)):(this.session=ob(this.namespace),this.user=ob(this.namespace)),this.dismissals=WT(this.session,this.user),this.cooldowns=YT(this.user),this.frequency=KT(this.session)}ns(e){let n=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(n)){let i=typeof window<"u"&&typeof sessionStorage<"u"?ab(sessionStorage,n):ob(n);this.namespacedStorages.set(n,i)}return this.namespacedStorages.get(n)}};function sb(t={}){return new Jf(t)}function zc(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function ep(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var XT={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"}},Bc={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:[]},QT={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function lb(t,e,n){let i=XT[e];Object.assign(t.style,i),n&&(n.maxWidth&&(t.style.maxWidth=n.maxWidth),n.maxHeight&&(t.style.maxHeight=n.maxHeight),n.minWidth&&(t.style.minWidth=n.minWidth),n.minHeight&&(t.style.minHeight=n.minHeight))}function cb(t,e,n){let i=n.placement==="auto"?"bottom":n.placement,r=[Ad(n.offset?{mainAxis:n.offset.y,crossAxis:n.offset.x}:8)];return n.flip!==!1&&r.push(kd()),n.shift!==!1&&r.push(Td({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",Cd(e,t,async()=>{let{x:o,y:s,strategy:l}=await Rd(e,t,{placement:i,middleware:r});Object.assign(t.style,{position:l,left:`${o}px`,top:`${s}px`})})}function ub(t,e,n="append"){return t.style.position="relative",t.style.display="inline-block",n==="prepend"?e.insertBefore(t,e.firstChild):e.appendChild(t),()=>{t.remove()}}function db(t,e){return e==="none"||Bc[e].length===0?null:t.animate(Bc[e],QT)}function fb(t,e){if(e==="none"||Bc[e].length===0)return Promise.resolve();let n=[...Bc[e]].reverse(),i=t.animate(n,QT);return new Promise(r=>{i.onfinish=()=>r(),i.oncancel=()=>r()})}function pb(t,e){let n=document.createElement("div");return n.setAttribute("data-syntro-surface",t),n.setAttribute("data-syntro-mount-id",e),n.className="syntro-surface",Object.assign(n.style,{pointerEvents:"auto",boxSizing:"border-box",overflow:"auto"}),n}function hb(t){switch(zc(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 JT(t){if(typeof window.Sanitizer=="function")try{let l=new window.Sanitizer({}).sanitizeToFragment(t),c=document.createElement("div");return c.append(l),c.innerHTML}catch{}let n=document.createElement("template");n.innerHTML=t;let i=n.content,r=document.createTreeWalker(i,NodeFilter.SHOW_ELEMENT,null),a=new Set(["b","strong","i","em","u","span","div","p","br","ul","ol","li","code","pre","small","sup","sub","a","button"]),o=[];for(;r.nextNode();){let s=r.currentNode,l=s.tagName.toLowerCase();if(!a.has(l)){o.push(s);continue}for(let c of Array.from(s.attributes)){let u=c.name.toLowerCase(),f=c.value.trim().toLowerCase(),h=u.startsWith("on"),g=(u==="href"||u==="src")&&f.startsWith("javascript:");(h||g)&&s.removeAttribute(c.name)}}for(let s of o){for(;s.firstChild;)s.parentNode?.insertBefore(s.firstChild,s);s.remove()}return n.innerHTML=(i.firstChild,n.innerHTML)}var e5=0;function gb(t){let{overlayRoot:e,eventBus:n,anchorResolver:i,defaultAnimation:r="fade",widgetRegistry:a}=t,o=new Map,s=new Map,l=new Map;function c(){return`mount-${++e5}`}function u(v,S){n&&n.publish(v,S)}function f(v){let S=l.get(v);if(S){let T=w(v);for(let A of S)try{A(T)}catch(k){console.error("[Surfaces] State callback error:",k)}}}let h=new Map;function g(v,S,T){switch(S.type){case"html":v.innerHTML=JT(S.content);return;case"widget":{if(a?.has(S.widgetId)){let A=a.mount(S.widgetId,v,S.config);return T&&h.set(T,A),()=>{A.unmount(),T&&h.delete(T)}}console.warn(`[Surfaces] Widget not found: ${S.widgetId}`),v.innerHTML=`<div data-widget-id="${S.widgetId}" data-widget-missing="true">Widget: ${S.widgetId}</div>`;return}case"custom":return S.mount(v);case"react":v.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function _(v,S,T){let A=c(),k=zc(v),C=T?.priority??0,x=T?.animation??r,M=T?.exclusive??!0,z=o.get(v);if(z&&M){if(z.options.priority>C)throw new Error(`Slot ${v} is occupied by higher priority content (${z.options.priority} > ${C})`);b(z)}let U=pb(v,A);U.style.zIndex=String(hb(v));let P;if(k==="static")lb(U,v,T?.constraints),e.appendChild(U);else if(k==="inline"){let D=ep(v);if(!D)throw new Error(`Invalid inline slot: ${v}`);if(!i)throw new Error("Anchor resolver required for inline slots");let L=i(D);if(!L)throw new Error(`Anchor not found for inline slot: ${D}`);P=ub(U,L)}else if(k==="adjacent"){let D=ep(v);if(!D)throw new Error(`Invalid adjacent slot: ${v}`);if(!i)throw new Error("Anchor resolver required for adjacent slots");let L=i(D);if(!L)throw new Error(`Anchor not found for adjacent slot: ${D}`);e.appendChild(U),P=cb(U,L,T?.position??{placement:"bottom"})}let Z=g(U,S,A);db(U,x);let X={id:A,slot:v,content:S,options:{priority:C,exclusive:M,animation:x,position:T?.position??{placement:"auto"},constraints:T?.constraints??{},adaptiveId:T?.adaptiveId,autoUnmountOnRouteChange:T?.autoUnmountOnRouteChange??!0},container:U,cleanup:()=>{P?.(),Z?.()},mountedAt:Date.now()};return o.set(v,X),s.set(v,(s.get(v)??0)+1),u("surface.mounted",{slot:v,id:A,adaptiveId:T?.adaptiveId}),f(v),{id:A,update(D){let L=o.get(v);if(!L||L.id!==A)throw new Error("Mount no longer active");let de=h.get(A);if(de){if(D.type==="widget"){de.update(D.config),L.content=D;return}de.unmount(),h.delete(A)}L.container.innerHTML="";let fn=g(L.container,D,A);if(L.content=D,fn){let We=L.cleanup;L.cleanup=()=>{We?.(),fn()}}},setOptions(D){let L=o.get(v);if(!L||L.id!==A)throw new Error("Mount no longer active");D.priority!==void 0&&(L.options.priority=D.priority),D.animation!==void 0&&(L.options.animation=D.animation),D.constraints&&k==="static"&&(D.constraints.maxWidth&&(L.container.style.maxWidth=D.constraints.maxWidth),D.constraints.maxHeight&&(L.container.style.maxHeight=D.constraints.maxHeight),D.constraints.minWidth&&(L.container.style.minWidth=D.constraints.minWidth),D.constraints.minHeight&&(L.container.style.minHeight=D.constraints.minHeight)),f(v)},async unmount(){let D=o.get(v);!D||D.id!==A||await b(D)},isMounted(){return o.get(v)?.id===A},getContainer(){let D=o.get(v);return D?.id===A?D.container:null}}}async function b(v){await fb(v.container,v.options.animation),v.cleanup?.(),v.container.remove(),o.delete(v.slot),u("surface.unmounted",{slot:v.slot,id:v.id}),f(v.slot)}function w(v){let S=o.get(v);return{slot:v,occupied:!!S,currentPriority:S?.options.priority,currentAdaptiveId:S?.options.adaptiveId,mountCount:s.get(v)??0,currentMountId:S?.id}}function d(v,S){let T=l.get(v);return T||(T=new Set,l.set(v,T)),T.add(S),()=>{T?.delete(S),T?.size===0&&l.delete(v)}}function p(v,S){let T=o.get(v);return T?S!==void 0?S>=T.options.priority:!1:!0}function m(){for(let v of o.values())try{v.cleanup?.(),v.container.remove()}catch(S){console.error("[Surfaces] Error during cleanup:",S)}o.clear(),l.clear()}return{mount:_,getState:w,onStateChange:d,canMount:p,destroy:m}}var tp=class{constructor(){V(this,"widgets",new Map);V(this,"mountedWidgets",new Map);V(this,"mountIdCounter",0);V(this,"runtimeRef");V(this,"listeners",new Set)}bindRuntime(e){this.runtimeRef=e}register(e,n,i="custom",r){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:n,source:i,metadata:r}),this.notify({type:"registered",widgetId:e})}unregister(e){let n=this.widgets.get(e);return n?n.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[n,i]of this.widgets.entries())i.source===e&&this.widgets.delete(n)}get(e){return this.widgets.get(e)?.widget}getRegistration(e){return this.widgets.get(e)}has(e){return this.widgets.has(e)}mount(e,n,i){let r=this.widgets.get(e);if(!r)throw new Error(`Widget not found: ${e}`);let a=`widget-mount-${++this.mountIdCounter}`;n.setAttribute("data-widget-mount-id",a),n.setAttribute("data-widget-id",e);let o={...i,runtime:this.runtimeRef},s=r.widget.mount(n,o);return this.mountedWidgets.set(a,{cleanup:s??void 0,container:n}),{widgetId:e,container:n,unmount:()=>{let c=this.mountedWidgets.get(a);c&&(c.cleanup?.(),this.mountedWidgets.delete(a),n.removeAttribute("data-widget-mount-id"),n.removeAttribute("data-widget-id"),n.innerHTML="")},update:c=>{if(r.widget.update)r.widget.update(n,c);else{let u=this.mountedWidgets.get(a);if(u){u.cleanup?.(),n.innerHTML="";let f={...c,runtime:this.runtimeRef},h=r.widget.mount(n,f);u.cleanup=h??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(n=>n.source===e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(let n of this.listeners)try{n(e)}catch(i){console.error("[WidgetRegistry] Listener error:",i)}}destroy(){for(let[e,n]of this.mountedWidgets.entries())n.cleanup?.(),n.container.innerHTML="";this.mountedWidgets.clear()}},mb=new tp;var tk="2.0.0";function t5(t,e){if(!e)return!0;let n;try{n=new URL(t).pathname}catch{n=t}let i=n.replace(/\/$/,"")||"/";if(e.exclude){for(let r of e.exclude)if(ek(i,r))return!1}if(e.include&&e.include.length>0){for(let r of e.include)if(ek(i,r))return!0;return!1}return!0}function ek(t,e){let n=e.replace(/\/$/,"")||"/";if(t===n)return!0;let i=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/:[^/]+/g,"[^/]+");return new RegExp(`^${i}$`).test(t)}function n5(t){try{return document.querySelector(t)}catch{return null}}function vb(t={}){let{telemetry:e,sessionMetrics:n,routes:i,mode:r="production",namespace:a}=t,o=t.widgets??mb,s=t.executors??Xi,l=t.apps??Vl,c=new Hc,u=Qy({telemetry:e,routes:i,navigation:c}),f=t.events??Lc(),h=sb({namespace:a}),g=eb({eventBus:f,stateStore:h}),_=Jy({state:h,events:f,sessionMetrics:n,accumulator:g}),b=$w(),w=v=>n5(v),d=gb({overlayRoot:b,eventBus:f,anchorResolver:w,widgetRegistry:o}),p=Zy({overlayRoot:b,eventBus:f,surfaces:d,anchorResolver:w,executorRegistry:s,subscribeNavigation:v=>c.subscribe(v)}),m={telemetry:e,context:u,events:f,state:h,sessionMetrics:n,actions:p,surfaces:d,widgets:o,executors:s,apps:l,accumulator:g,navigation:c,version:tk,mode:r,async evaluate(v){return _.evaluate(v,u.get())},evaluateSync(v){return _.evaluateSync(v,u.get())},async filterTiles(v){let S=u.get().page.url,T=[];for(let A of v){let k=A.activation;if(!k){T.push(A);continue}if(!t5(S,k.routes))continue;if(!k.strategy){T.push(A);continue}(await this.evaluate(k.strategy)).value&&T.push(A)}return T},setRoutes(v){u.setRoutes(v)},destroy(){l.unbind().catch(v=>{console.error("[Runtime] Error unbinding apps registry:",v)}),g.destroy(),c.destroy(),u.destroy(),p.destroy(),d.destroy()}};return l.bind(m),o.bindRuntime(m),m}var i5=y.object({value:y.unknown(),expiresAt:y.number().optional()}),r5=y.object({count:y.number(),resetAt:y.number().optional()});function U8(t){return i5.safeParse(t)}function V8(t){return r5.safeParse(t)}var nk={growthbook:t=>Ym({...t,autoInit:!0})};function ik(t,e){let n=nk[t];if(!n)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys(nk).join(", ")}`);return n(e)}var a5=["cdn.syntrologie.com","localhost","127.0.0.1"];function o5(t){try{let e=new URL(t),n=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!n?(console.warn("[SmartCanvas] CDN URL must use HTTPS:",t),!1):a5.some(r=>e.hostname===r)?!0:(console.warn("[SmartCanvas] CDN host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid CDN URL:",t),!1}}var yb=class{constructor(e){V(this,"name","cdn");V(this,"url");V(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!o5(this.url))throw new Error(`[SmartCanvas] CDN URL not allowed: ${this.url}`)}async fetch(){let e=performance.now(),n=await fetch(this.url,{credentials:"omit",cache:"default"});if(!n.ok)throw new Error(`[SmartCanvas] Failed to fetch config from CDN (${n.status})`);let i=await n.text();if(this.integrity){let l=await s5(i),c=this.integrity.replace("sha384-","");if(l!==c)throw new Error(`[SmartCanvas] Config integrity check failed. Expected ${c}, got ${l}`)}let r=JSON.parse(i),a=performance.now()-e,o=n.headers.get("cache-control"),s=n.headers.get("age");return{config:r,meta:{source:"cdn",fetchTimeMs:a,cached:o?.includes("public")??!1,cacheAge:s?parseInt(s,10):void 0}}}};async function s5(t){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-384",n),r=new Uint8Array(i);return btoa(String.fromCharCode(...r))}function rk(t){return new yb(t)}var l5="syntro_exp",c5="syntro_var",bb=class{constructor(e){V(this,"name","experiments");V(this,"client");V(this,"featureKey");V(this,"manifestKey");V(this,"variantFlagPrefix");this.client=e.client,this.featureKey=e.featureKey??"smart-canvas-config",this.manifestKey=e.manifestKey,this.variantFlagPrefix=e.variantFlagPrefix}async fetch(){let e=performance.now();if(typeof window<"u"){let r=new URLSearchParams(window.location.search),a=r.get(l5),o=r.get(c5);if(a&&o!==null&&this.client.setForcedVariations){let s=parseInt(o,10);Number.isNaN(s)||(console.log(`[SmartCanvas] Preview mode: forcing "${a}" to variation ${s}`),this.client.setForcedVariations({[a]:s}))}}if(this.manifestKey||this.variantFlagPrefix){let r=this.fetchMultiFlag();if(r){let a=performance.now()-e;return{config:r,meta:{source:"experiments",fetchTimeMs:a,cached:!0}}}}let n=this.client.getFeatureValue?.(this.featureKey,null);if(!n||typeof n!="object")throw new Error(`[SmartCanvas] Feature "${this.featureKey}" not found or invalid. Ensure the feature is configured in your experiment platform.`);let i=performance.now()-e;return{config:n,meta:{source:"experiments",fetchTimeMs:i,cached:!0}}}fetchMultiFlag(){let e=this.getVariantFlagKeys();return!e||e.length===0?null:Ld(this.client,e)}getVariantFlagKeys(){if(this.manifestKey){let e=this.client.getFeatureValue?.(this.manifestKey,null);if(e&&typeof e=="object"){let n=e.variant_flags;if(n&&n.length>0)return n}}if(this.variantFlagPrefix&&this.client.getAllFeatures){let e=this.client.getAllFeatures();return Object.keys(e).filter(n=>n.startsWith(this.variantFlagPrefix))}return[]}};function ak(t){return new bb(t)}var u5="https://cdn.syntrologie.com/configs",ok={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return rk({baseUrl:t.baseUrl??u5,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return ak({featureKey:t.featureKey})}};function sk(t,e={}){let n=ok[t];if(!n)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys(ok).join(", ")}`);return n(e)}var lk={posthog:t=>By(t),noop:()=>tv()};function ck(t,e){let n=lk[t];if(!n)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(lk).join(", ")}`);return n(e)}var _b="syn_";function np(t){if(!t.startsWith(_b))throw new Error("Invalid Syntro token: must start with 'syn_'");let n=t.slice(_b.length).replace(/-/g,"+").replace(/_/g,"/"),i=atob(n),r=JSON.parse(i);if(r.v!==1)throw new Error(`Unsupported token version: ${r.v}`);return r}function Sb(t){let e=JSON.stringify(t),n=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return _b+n}function Qi(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{}}function d5(){if(typeof window>"u")return G("Syntro Bootstrap","isEditorMode: not in browser"),!1;let t=Oa(),n=!!(Dr()?.token&&t?.mode==="editor");return G("Syntro Bootstrap","isEditorMode:",n),n}function f5(){if(typeof window>"u")return G("Syntro Bootstrap","isAuditMode: not in browser"),!1;let t=Oa(),n=!!(Dr()?.token&&t?.mode==="audit");return G("Syntro Bootstrap","isAuditMode:",n),n}function p5(){if(typeof window>"u")return G("Syntro Bootstrap","isReviewMode: not in browser"),!1;let t=Oa(),n=!!(Dr()?.token&&t?.mode==="review");return G("Syntro Bootstrap","isReviewMode:",n),n}var uk="syntro_segment_attributes";function h5(){if(typeof window>"u")return{};try{let t=localStorage.getItem(uk);if(t){let e=JSON.parse(t);return G("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){cn("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function g5(t){if(!(typeof window>"u"))try{localStorage.setItem(uk,JSON.stringify(t)),G("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){cn("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function m5(t){if(!t)return{};let e={};for(let[n,i]of Object.entries(t))n.startsWith("in_segment_")&&(e[n]=i===!0);return e}async function v5(t){um(),G("Syntro Bootstrap","====== INIT ======"),G("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=d5(),n=f5(),i=p5(),r=e?"editor":n?"audit":i?"review":null;if(console.log(`[DIAG] Mode detection: editor=${e}, audit=${n}, review=${i}, sdkMode=${r}`),console.log("[DIAG] editorSource:",Dr()),console.log("[DIAG] editorConf:",Oa()),G("Syntro Bootstrap","SDK mode:",r??"normal"),!r&&typeof window<"u"){let x=!!window.__SYNTRO_EDITOR_PARAMS__,M=!!window.__SYNTRO_AUDIT_LEGEND__,z=!!window.__SYNTRO_REVIEW_DATA__;if(x||M||z){let U=[x&&"__SYNTRO_EDITOR_PARAMS__",M&&"__SYNTRO_AUDIT_LEGEND__",z&&"__SYNTRO_REVIEW_DATA__"].filter(Boolean);console.warn(`[Syntro Bootstrap] \u26A0 Mode detection returned null but mode-specific globals found: ${U.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&&r){let M=Oa()?.syntro_token;M?.startsWith("syn_")&&(a=M,G("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${r} mode)`))}let o;if(a)if(a.startsWith("syn_"))G("Syntro Bootstrap","Token starts with syn_, decoding..."),o=np(a),um(o.d);else if(r)G("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${r} mode)`);else throw Hd("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),Hd("Syntro Bootstrap","Token received:",a),new Error("Invalid Syntro token: must start with 'syn_'");else if(r)G("Syntro Bootstrap",`\u2713 No token, but ${r} mode - proceeding`);else throw Hd("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 s=Qi("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||Qi("VITE_SYNTRO_EXPERIMENT_HOST")||o?.eh,l=Qi("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||Qi("VITE_SYNTRO_TELEMETRY_HOST")||o?.th,c=Qi("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||Qi("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,u=h5();G("Syntro Bootstrap","Phase 1: Using cached segment attributes:",u);let f,h=Lc();console.log("[Syntro Bootstrap] EventBus created");let g=nb(x=>{h.publishEvent(x)}),_=x=>{G("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let M=m5(x);if(G("Syntro Bootstrap","Segment flags from PostHog:",M),g5(M),f){let U={...w?.getAll?.()??{},...M};G("Syntro Bootstrap","Updating GrowthBook with attributes:",U),f.setAttributes?.(U)}},b;if(o?.t){let x=o.t==="noop"?"noop":"posthog";b=ck(x,{apiKey:o.t,apiHost:l,enableFeatureFlags:!0,onFeatureFlagsLoaded:_,onCapture:g}),console.log(`[Syntro Bootstrap] Telemetry client created (${x}) with EventBus wiring`)}let w;o?.e&&(f=ik("growthbook",{clientKey:o.e,apiHost:s,attributes:u,onExperimentViewed:b?.trackExperiment?(x,M,z)=>{b.trackExperiment(x,M,z)}:void 0})),t.enableSessionMetrics&&(w=Wm({experiments:f,onMetricChange:(x,M)=>{G("Syntro Bootstrap",`Session metric changed: ${x} = ${M}`)}}),G("Syntro Bootstrap","SessionMetricTracker created"));let d="production";e?d="editor":n?d="audit":Qi("NODE_ENV")==="development"&&(d="development");let p=vb({telemetry:b,sessionMetrics:w,mode:d,events:h});G("Syntro Bootstrap","Runtime created:",{version:p.version,mode:p.mode,hasContext:!!p.context,hasEvents:!!p.events,hasState:!!p.state}),G("Syntro Bootstrap","Core app executors already registered");let m=t.cdnBase||Qi("NEXT_PUBLIC_SYNTRO_CDN_BASE")||Qi("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",v=rm({cdnBase:m,registry:p.apps,onLoadStart:x=>{G("Syntro Bootstrap",`Loading app from CDN: ${x}`)},onLoadEnd:(x,M,z)=>{M?G("Syntro Bootstrap",`App loaded successfully: ${x}`):cn("Syntro Bootstrap",`Failed to load app: ${x}`,z)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:p.apps,runtime:p,version:p.version},G("Syntro Bootstrap","Global SynOS object exposed"));let S=p.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${S.length} apps in registry:`,S.map(x=>`${x.manifest.id}(${x.state})`).join(", "));for(let x of S)if(x.state==="registered")try{await p.apps.activate(x.manifest.id),console.log(`[DIAG] Activated: ${x.manifest.id} \u2192 widgets: [${p.widgets.list().join(", ")}]`)}catch(M){console.error(`[DIAG] FAILED to activate: ${x.manifest.id}`,M),cn("Syntro Bootstrap",`Failed to auto-activate built-in app: ${x.manifest.id}`,M)}if(console.log(`[DIAG] Activation complete. Total widgets: [${p.widgets.list().join(", ")}]`),f?.refreshFeatures)try{await f.refreshFeatures(),G("Syntro Bootstrap","GrowthBook features loaded")}catch(x){cn("Syntro Bootstrap","Failed to load GrowthBook features:",x)}let T;if(t.fetcher)T=t.fetcher;else if(o?.f){let x=sk(o.f,o.o??{});T=async()=>{let M=await x.fetch();return{...M.config,tiles:M.config.tiles??[]}}}else f&&(T=es({experiments:f}));let A=new Set,k=T?async()=>{let x=await T();console.log("[Syntro Bootstrap] Config fetched:",`tiles=${x.tiles?.length??0},`,`actions=${x.actions?.length??0},`,`theme=${x.theme?.name??"none"}`),x.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",x.actions.map((U,P)=>`[${P}] ${U.kind}${U.anchorId?` anchor="${U.anchorId}"`:""}${U.label?` "${U.label}"`:""}`).join(", "));let M=x,z=v.getRequiredApps(M);return z.length>0?console.log("[Syntro Bootstrap] Required external apps:",z.join(", ")):G("Syntro Bootstrap","No external apps required (all executors are built-in)"),z.length>0&&await v.loadAppsForConfig(M).then(async P=>{let Z=P.filter(D=>D.success),X=P.filter(D=>!D.success);Z.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${Z.map(D=>D.appId).join(", ")}`);let W=X.filter(D=>!A.has(D.appId));W.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",W.map(D=>`${D.appId} (${D.error})`).join(", ")),W.forEach(D=>A.add(D.appId)));for(let D of z)if(p.apps.has(D))try{await p.apps.activate(D),console.log(`[Syntro Bootstrap] App activated: ${D}`)}catch(L){console.error(`[Syntro Bootstrap] Failed to activate app: ${D}`,L)}else console.error(`[Syntro Bootstrap] App "${D}" required by config but NOT registered.`,`Available apps: [${Array.from(p.apps.list?.()??[]).join(", ")}]`)}),x}:void 0;return{canvas:await Rm({...t.canvas,fetcher:k,integrations:{experiments:f,telemetry:b},editorUrl:c,runtime:p}),runtime:p,experiments:f,telemetry:b,sessionMetrics:w,appLoader:v}}var dk={init:v5,encodeToken:Sb,decodeToken:np};typeof window<"u"&&(window.Syntro=dk);var fk="2026-02-26T22:38:37.348Z (38fdc4fa1)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${fk}`);let t=window.SynOS,e=t?.appRegistry||Vl;window.SynOS={...t,appRegistry:e,_runtimeBuild:fk,React:pk.default,ReactDOM:{...y5,createPortal:ip.createPortal,flushSync:ip.flushSync}},kw(e)}export{Bc as ANIMATION_KEYFRAMES,Yf as ActivationConfigZ,xT as AddClassZ,G3 as AnchorStateZ,O3 as AnchorVisibleConditionZ,Od as AppRegistry,Z3 as AugmentationZ,dT as BadgePositionZ,kT as BadgeZ,P3 as BoundingBoxZ,Gl as CanvasEvents,Jm as CanvasRecipeZ,Yy as ConditionZ,Wf as ContextManager,I3 as CooldownActiveConditionZ,Ky as CtaButtonZ,bm as DEFAULT_COOLDOWN,ym as DEFAULT_TTL,lT as DecisionStrategyZ,H3 as DismissedConditionZ,is as EVENT_SCHEMA_VERSION,Qf as EventBus,B3 as EventCountConditionZ,Q3 as EventFilterZ,M3 as EventOccurredConditionZ,ZT as EventSourceZ,Zf as ExecutorRegistry,sT as ExternalStrategyZ,r5 as FrequencyEntryZ,z3 as FrequencyLimitConditionZ,O4 as HighlightStepZ,uT as HighlightStyleZ,AT as HighlightZ,CT as InsertHtmlZ,gT as InsertPositionZ,vm as MAX_VISIBLE_TOASTS,hT as ModalContentZ,OT as ModalZ,oT as ModelStrategyZ,DT as MountWidgetZ,NT as NavigateZ,Hc as NavigationMonitor,X3 as NormalizedEventZ,mm as NotificationToastStack,U3 as PageContextZ,V3 as PageHistoryEntryZ,k3 as PageUrlConditionZ,IT as ParallelZ,fT as PlacementZ,TT as PulseZ,fk as RUNTIME_SDK_BUILD,tk as RUNTIME_VERSION,wT as RemoveClassZ,R3 as RouteConditionZ,cT as RouteFilterZ,rT as RuleStrategyZ,iT as RuleZ,Y3 as RuntimeContextZ,Em as RuntimeProvider,Nr as SDK_SCHEMA_VERSION,dm as SDK_VERSION,XT as STATIC_SLOT_STYLES,aT as ScoreStrategyZ,bT as ScrollBehaviorZ,Wy as ScrollLogicalPositionZ,MT as ScrollToZ,XE as SelectorZ,HT as SequenceZ,j3 as SessionContextZ,L3 as SessionMetricConditionZ,af as SessionMetricTracker,ST as SetAttrZ,ET as SetStyleZ,_T as SetTextZ,Zw as ShadowCanvasOverlay,Vw as ShadowRootProvider,Kw as SmartCanvasApp,pm as SmartCanvasController,Tm as SmartCanvasElement,vB as SmartCanvasPortal,_e as StandardEvents,N3 as StateEqualsConditionZ,Jf as StateStore,i5 as StoredValueZ,dk as Syntro,Zl as TileCard,o6 as TileWheel,pT as TooltipContentZ,R4 as TooltipStepZ,mT as TooltipTriggerZ,RT as TooltipZ,yT as TourStepForSchemaZ,zT as TourZ,D3 as ViewportConditionZ,q3 as ViewportContextZ,LT as WaitZ,vT as WidgetConfigZ,tp as WidgetRegistry,Vl as appRegistry,lb as applyStaticSlotStyles,nm as cleanupAppContext,Zg as contentRuntime,$3 as coreActionStepSchemas,Zy as createActionEngine,tm as createAppContext,rm as createAppLoader,es as createCanvasConfigFetcher,Qy as createContextManager,Jy as createDecisionEngine,eb as createEventAccumulator,Lc as createEventBus,Ym as createGrowthBookClient,tv as createNoopClient,gB as createOverlayRecipeFetcher,By as createPostHogClient,nb as createPostHogNormalizer,Wm as createSessionMetricTracker,Rm as createSmartCanvas,Fw as createSmartCanvasController,vb as createSmartCanvasRuntime,sb as createStateStore,pb as createSurfaceContainer,gb as createSurfaces,t$ as decisionSchemas,np as decodeToken,Sb as encodeToken,VT as evaluate,$T as evaluateCondition,FT as evaluateRule,Kf as evaluateRuleStrategy,Xf as evaluateScoreStrategy,jT as evaluateSync,Xi as executorRegistry,TM as getAntiFlickerSnippet,uw as getAppIdFromActionKind,im as getAppIdFromWidgetId,d3 as getExecutor,ep as getSlotAnchorId,zc as getSlotType,hb as getSlotZIndex,Py as hasExecutor,Bd as interpolateTemplate,cw as isCoreActionKind,_m as matchEvent,u6 as needsMigration,PT as normalizePostHogEvent,em as overlaysRuntime,Wl as parseVersion,db as playEnterAnimation,fb as playExitAnimation,Pl as registerConfigPredicates,eE as registerSmartCanvasElement,fm as resolveConfigUri,cb as setupAdjacentPositioning,ub as setupInlinePositioning,GT as shouldNormalizeEvent,uN as useDecision,Sm as useNotifications,xm as useNotifyWatcher,Cm as usePageContext,Ii as useRuntime,Fd as useRuntimeContext,lN as useRuntimeEvents,cN as useRuntimeState,oN as useSessionContext,Yw as useShadowCanvasConfig,zd as useShadowRoot,sN as useViewportContext,na as validateAction,Gy as validateActions,e$ as validateActivationConfig,QB as validateCondition,c6 as validateConfig,$$ as validateEventFilter,V8 as validateFrequencyEntry,B$ as validateNormalizedEvent,dB as validateRecipe,h$ as validateRuntimeContext,U8 as validateStoredValue,JB as validateStrategy,mb as widgetRegistry};
450
450
  /*! Bundled license information:
451
451
 
452
452
  react/cjs/react.production.js: