@syntrologie/runtime-sdk 2.8.0 → 2.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CAPABILITIES.md +35 -13
- package/dist/{chunk-4J6BCKWS.js → chunk-OIDBMIRB.js} +5 -5
- package/dist/chunk-OIDBMIRB.js.map +7 -0
- package/dist/index.js +1 -1
- package/dist/react.js +1 -1
- package/dist/smart-canvas.esm.js +2 -2
- package/dist/smart-canvas.esm.js.map +2 -2
- package/dist/smart-canvas.js +5 -5
- package/dist/smart-canvas.js.map +2 -2
- package/dist/smart-canvas.min.js +2 -2
- package/dist/smart-canvas.min.js.map +2 -2
- package/dist/version.d.ts +1 -1
- package/package.json +7 -7
- package/dist/chunk-4J6BCKWS.js.map +0 -7
package/dist/smart-canvas.esm.js
CHANGED
|
@@ -181,7 +181,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let n="<p>An error
|
|
|
181
181
|
s.textContent = '.${e} { ${a} }';
|
|
182
182
|
document.head.appendChild(s);
|
|
183
183
|
document.documentElement.className += ' ${e}';
|
|
184
|
-
})();`}function Pf(t,e,a="first-match"){for(let n of e){let r=t.getFeatureValue?.(n,null);if(!r||typeof r!="object")continue;let o=r,i=o.tiles&&o.tiles.length>0,s=o.actions&&o.actions.length>0;if(i||s)return{tiles:o.tiles??[],actions:o.actions??[],fetchedAt:o.fetchedAt??new Date().toISOString(),...o.schemaVersion&&{schemaVersion:o.schemaVersion},...o.configVersion&&{configVersion:o.configVersion},...o.canvasTitle&&{canvasTitle:o.canvasTitle},...o.theme&&{theme:o.theme},...o.launcher&&{launcher:o.launcher}}}return null}var Pv=!1;function W1(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function Fv(t){if(W1()){Pv=!0;return}Pv=t??!1}function YO(){return W1()?!0:Pv}function K(t,e,a){YO()&&(a!==void 0?console.log(`[${t}]`,e,a):console.log(`[${t}]`,e))}function ya(t,e,a){a!==void 0?console.warn(`[${t}]`,e,a):console.warn(`[${t}]`,e)}function Ff(t,e,a){a!==void 0?console.error(`[${t}]`,e,a):console.error(`[${t}]`,e)}var Nv="2.
|
|
184
|
+
})();`}function Pf(t,e,a="first-match"){for(let n of e){let r=t.getFeatureValue?.(n,null);if(!r||typeof r!="object")continue;let o=r,i=o.tiles&&o.tiles.length>0,s=o.actions&&o.actions.length>0;if(i||s)return{tiles:o.tiles??[],actions:o.actions??[],fetchedAt:o.fetchedAt??new Date().toISOString(),...o.schemaVersion&&{schemaVersion:o.schemaVersion},...o.configVersion&&{configVersion:o.configVersion},...o.canvasTitle&&{canvasTitle:o.canvasTitle},...o.theme&&{theme:o.theme},...o.launcher&&{launcher:o.launcher}}}return null}var Pv=!1;function W1(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function Fv(t){if(W1()){Pv=!0;return}Pv=t??!1}function YO(){return W1()?!0:Pv}function K(t,e,a){YO()&&(a!==void 0?console.log(`[${t}]`,e,a):console.log(`[${t}]`,e))}function ya(t,e,a){a!==void 0?console.warn(`[${t}]`,e,a):console.warn(`[${t}]`,e)}function Ff(t,e,a){a!==void 0?console.error(`[${t}]`,e,a):console.error(`[${t}]`,e)}var Nv="2.10.0";var Zr="2.0";var KO=["api.syntrologie.com","cdn.syntrologie.com","localhost","127.0.0.1"];function QO(t){try{let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(console.warn("[SmartCanvas] Config URI must use HTTPS:",t),!1):KO.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 JO(t){if(typeof window>"u")return!1;try{return new URL(t).origin===window.location.origin}catch{return!1}}var X1="syntro_config_cache",eB=1440*60*1e3;function Y1(){try{return typeof localStorage<"u"&&localStorage!==null}catch{return!1}}function tB(t,e){if(Y1())try{let a={config:t,timestamp:Date.now(),sdkVersion:e};localStorage.setItem(X1,JSON.stringify(a))}catch{}}function aB(t){if(!Y1())return null;try{let e=localStorage.getItem(X1);if(!e)return null;let a=JSON.parse(e);return!a.config||typeof a.timestamp!="number"||!a.sdkVersion||a.sdkVersion!==t||Date.now()-a.timestamp>eB?null:a.config}catch{return null}}var Hv=({configUri:t,experiments:e,featureKey:a="smart-canvas-config-uri"})=>{if(t)return t;let n=e?.getFeatureValue?.(a,null);if(n)return n};function nB(t,e,a){if(e){let n=t.getFeatureValue?.(e,null);if(n&&typeof n=="object"){let r=n.variant_flags;if(r&&r.length>0)return r}}if(t.getAllFeatures){let n=t.getAllFeatures();return a?Object.keys(n).filter(r=>r.startsWith(a)):Object.keys(n)}return[]}var ys=({configUri:t,experiments:e,featureKey:a,credentials:n,configFeatureKey:r="smart-canvas-config",manifestKey:o,variantFlagPrefix:i,sdkVersion:s})=>async()=>{if(e&&r){let c=e.getFeatureValue?.(r,null);if(c&&typeof c=="object")return K("SmartCanvas Config","Resolved config directly from feature flag",c),c}if(e&&(o||i||e.getAllFeatures)){let c=nB(e,o,i);if(c.length>0){let d=Pf(e,c);if(d)return K("SmartCanvas Config","Resolved config from variant flags",d),d}}let l=Hv({configUri:t,experiments:e,featureKey:a});if(!l)return K("SmartCanvas Config","No config available \u2014 returning empty config"),{tiles:[],actions:[],fetchedAt:new Date().toISOString()};if(!QO(l))throw new Error(`SmartCanvas: config URI not allowed: ${l}`);let u=n??(JO(l)?"include":"omit");try{let c=await fetch(l,{credentials:u,headers:{"X-SDK-Version":Nv,"X-SDK-Schema-Version":Zr}});if(!c.ok)throw new Error(`SmartCanvas: failed to fetch config (${c.status})`);let d=await c.json();return K("SmartCanvas Config","Fetched config from URI",d),s&&tB(d,s),d}catch(c){if(s){let d=aB(s);if(d)return K("SmartCanvas Config","Serving config from offline cache"),d}throw c}};var rB=["cdn.syntrologie.com","api.syntrologie.com","dev-api.syntrologie.com","localhost","127.0.0.1",".syntrologie.com"];function K1(t){if(typeof window>"u")return null;let a=new URLSearchParams(window.location.search).get(t);if(!a)return null;try{let n=a.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(n))}catch(n){return ya("Syntro Runtime",`Failed to decode ${t}:`,n),null}}var xs,bs;function mu(){if(xs==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.token)xs={token:t.token,api_base:t.apiBase||""},console.log(`[DIAG] getEditorSource: from __SYNTRO_EDITOR_PARAMS__ (token=${xs.token.slice(0,15)}...)`);else{let e=K1("editor_source");e&&(xs=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 xs??null}function Nf(){if(bs==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.mode)bs={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=${bs.mode})`);else{let e=K1("editor_conf");e&&(bs=e),console.log(`[DIAG] getEditorConf: from URL param \u2192 ${e?`mode=${e.mode}`:"NULL"}`)}}return bs??null}function oB(t){K("Syntro Runtime","Validating editor URL:",t);try{if(t.startsWith("/"))return K("Syntro Runtime","\u2713 Relative URL allowed (same-origin):",t),!0;let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(ya("Syntro Runtime","\u274C Editor URL must use HTTPS:",t),!1):rB.some(r=>r.startsWith(".")?e.hostname.endsWith(r)||e.hostname===r.slice(1):e.hostname===r)?(K("Syntro Runtime","\u2713 Editor URL validated"),!0):(ya("Syntro Runtime","\u274C Editor URL host not in allowlist:",e.hostname),!1)}catch(e){return ya("Syntro Runtime",`\u274C Invalid editor URL: ${t}`,e),!1}}var Hf=()=>{let t=Nf();return!mu()?.token||!t?.mode?null:t.mode};function iB(){return mu()?.token??null}function sB(){return mu()?.api_base??null}var hu=null,Q1=async t=>{if(K("Syntro Runtime","====== LOAD EDITOR SDK ======"),typeof window>"u"){K("Syntro Runtime","Not in browser - skipping editor SDK load");return}if(window.SyntroEditor){K("Syntro Runtime","Editor SDK already loaded (window.SyntroEditor exists)");return}if(hu)return K("Syntro Runtime","Editor SDK load already in progress, waiting..."),hu;let e=typeof t=="string"?{editorUrl:t}:t??{};if(e.editorUrl==="skip"){K("Syntro Runtime",'editorUrl="skip" \u2014 deferring to caller'),K("Syntro Runtime","================================");return}let a=sB(),r=(a?`${a}/api/editor/sdk/editor-sdk.js`:null)||e.editorUrl;if(!r){ya("Syntro Runtime","\u274C No editor SDK URL available (no api_base, no editorUrl option)"),K("Syntro Runtime","================================");return}let o=iB();if(!o){ya("Syntro Runtime","\u274C No token found in editor_source."),K("Syntro Runtime","================================");return}let i=`${r}?token=${encodeURIComponent(o)}`;if(K("Syntro Runtime","Editor URL:",i),K("Syntro Runtime","Options:",{hasIntegrity:!!e.integrity,hasEditorUrl:!!r,hasApiBase:!!a,tokenPrefix:`${o.slice(0,10)}...`}),!oB(r)){console.error("[Syntro Runtime] \u274C BLOCKED: Editor from untrusted URL:",r),K("Syntro Runtime","================================");return}return K("Syntro Runtime","\u2713 URL validated, injecting script tag..."),hu=new Promise((s,l)=>{let u=document.createElement("script");u.src=i,u.async=!0,e.integrity&&(u.integrity=e.integrity,u.crossOrigin="anonymous",K("Syntro Runtime","SRI integrity check enabled")),u.onload=()=>{K("Syntro Runtime","\u2713 Editor SDK script loaded successfully"),K("Syntro Runtime","================================"),s()},u.onerror=c=>{console.error("[Syntro Runtime] \u274C Failed to load Editor SDK:",c),console.error("[Syntro Runtime] URL attempted:",i),K("Syntro Runtime","================================"),hu=null,l(c)},document.head.appendChild(u),K("Syntro Runtime","Script tag appended to <head>")}),hu};var lB=new Set(["tag_name","$el_text"]);function uB(t){return lB.has(t)||t.startsWith("attr__")}function J1(t,e){return t.equals!==void 0?e===t.equals:t.contains!==void 0?typeof e=="string"&&e.includes(t.contains):!1}function cB(t){let{events:e,match:a}=t;return n=>{if(!e.includes(n.name))return!1;if(a){for(let[r,o]of Object.entries(a))if(uB(r)){let i=n.props?.elements;if(!i||!i.some(l=>J1(o,l[r])))return!1}else if(!J1(o,n.props?.[r]))return!1}return!0}}function ek(t,e){for(let a of t.rules)for(let n of a.conditions)if(n.type==="event_count"&&n.key){let r=n.counter,o=r?cB(r):()=>!0,i=typeof n.withinMs=="number";e.register(n.key,o,i)}}function Uf(t,e,a){for(let n of t){let r=n.props;if(!r)continue;let o=r.actions;if(o)for(let i of o)i.triggerWhen?.type==="rules"&&ek(i.triggerWhen,e)}if(a)for(let n of a){let r=n;r.triggerWhen?.type==="rules"&&ek(r.triggerWhen,e)}}var mn=null;function ak(t){mn&&mn!==t?t.appendChild(mn):mn=t;let e=t.getRootNode();e instanceof ShadowRoot&&dB(e)}function nk(){return mn||(mn=document.createElement("div"),mn.id="syntro-overlays",Object.assign(mn.style,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"}),document.body.appendChild(mn)),mn}var tk=!1;function dB(t){if(tk)return;let e=`
|
|
185
185
|
:host {
|
|
186
186
|
--syntro-surface: var(--sc-overlay-background, #0f1318);
|
|
187
187
|
--syntro-fg: var(--sc-overlay-text-color, #cbd0d7);
|
|
@@ -516,7 +516,7 @@ ${l}
|
|
|
516
516
|
`).replace(/\r/g,`
|
|
517
517
|
`)).length,r=0;r<n;r++){var i=t.charCodeAt(r),s=null;i<128?a++:s=i>127&&i<2048?String.fromCharCode(i>>6|192,63&i|128):String.fromCharCode(i>>12|224,i>>6&63|128,63&i|128),dr(s)||(a>e&&(o+=t.substring(e,a)),o+=s,e=a=r+1)}return a>e&&(o+=t.substring(e,t.length)),o},N4=!!Qy||!!Ky,uA="text/plain",$p=function(t,e,a){var n;a===void 0&&(a=!0);var[r,o]=t.split("?"),i=Z({},e),s=(n=o?.split("&").map((u=>{var c,[d,f]=u.split("="),h=a&&(c=i[d])!==null&&c!==void 0?c:f;return delete i[d],d+"="+h})))!==null&&n!==void 0?n:[],l=t4(i);return l&&s.push(l),r+"?"+s.join("&")},ac=(t,e)=>JSON.stringify(t,((a,n)=>typeof n=="bigint"?n.toString():n),e),Gy=t=>{var{data:e,compression:a}=t;if(e){if(a===cr.GZipJS){var n=P4((function(l,u){var c=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var d=new Ua(l.length+(l.length>>>1)),f=0,h=function(m){d[f++]=m},S=0;S<c;++S){if(f+5>d.length){var x=new Ua(f+8+(c-S<<1));x.set(d),d=x}var b=l.charCodeAt(S);b<128||u?h(b):b<2048?(h(192|b>>>6),h(128|63&b)):b>55295&&b<57344?(h(240|(b=65536+(1047552&b)|1023&l.charCodeAt(++S))>>>18),h(128|b>>>12&63),h(128|b>>>6&63),h(128|63&b)):(h(224|b>>>12),h(128|b>>>6&63),h(128|63&b))}return CE(d,0,f)})(ac(e)),{mtime:0}),r=new Blob([n],{type:uA});return{contentType:uA,body:r,estimatedSize:r.size}}if(a===cr.Base64){var o=(function(l){var u,c,d,f,h,S="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",x=0,b=0,m="",g=[];if(!l)return l;l=F4(l);do u=(h=l.charCodeAt(x++)<<16|l.charCodeAt(x++)<<8|l.charCodeAt(x++))>>18&63,c=h>>12&63,d=h>>6&63,f=63&h,g[b++]=S.charAt(u)+S.charAt(c)+S.charAt(d)+S.charAt(f);while(x<l.length);switch(m=g.join(""),l.length%3){case 1:m=m.slice(0,-2)+"==";break;case 2:m=m.slice(0,-1)+"="}return m})(ac(e)),i=(l=>"data="+encodeURIComponent(typeof l=="string"?l:ac(l)))(o);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var s=ac(e);return{contentType:"application/json",body:s,estimatedSize:new Blob([s]).size}}},kp=[];Ky&&kp.push({transport:"fetch",method:t=>{var e,a,{contentType:n,body:r,estimatedSize:o}=(e=Gy(t))!==null&&e!==void 0?e:{},i=new Headers;Pe(t.headers,(function(c,d){i.append(d,c)})),n&&i.append("Content-Type",n);var s=t.url,l=null;if(EI){var u=new EI;l={signal:u.signal,timeout:setTimeout((()=>u.abort()),t.timeout)}}Ky(s,Z({method:t?.method||"GET",headers:i,keepalive:t.method==="POST"&&(o||0)<52428.8,body:r,signal:(a=l)==null?void 0:a.signal},t.fetchOptions)).then((c=>c.text().then((d=>{var f={statusCode:c.status,text:d};if(c.status===200)try{f.json=JSON.parse(d)}catch(h){$.error(h)}t.callback==null||t.callback(f)})))).catch((c=>{$.error(c),t.callback==null||t.callback({statusCode:0,text:c})})).finally((()=>l?clearTimeout(l.timeout):null))}}),Qy&&kp.push({transport:"XHR",method:t=>{var e,a=new Qy;a.open(t.method||"GET",t.url,!0);var{contentType:n,body:r}=(e=Gy(t))!==null&&e!==void 0?e:{};Pe(t.headers,(function(o,i){a.setRequestHeader(i,o)})),n&&a.setRequestHeader("Content-Type",n),t.timeout&&(a.timeout=t.timeout),t.disableXHRCredentials||(a.withCredentials=!0),a.onreadystatechange=()=>{if(a.readyState===4){var o={statusCode:a.status,text:a.responseText};if(a.status===200)try{o.json=JSON.parse(a.responseText)}catch{}t.callback==null||t.callback(o)}},a.send(r)}}),Sa!=null&&Sa.sendBeacon&&kp.push({transport:"sendBeacon",method:t=>{var e=$p(t.url,{beacon:"1"});try{var a,{contentType:n,body:r}=(a=Gy(t))!==null&&a!==void 0?a:{},o=typeof r=="string"?new Blob([r],{type:n}):r;Sa.sendBeacon(e,o)}catch{}}});var Vp=function(t,e){if(!(function(a){try{new RegExp(a)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function cA(t,e,a){return ac({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:a})}var _E={exact:(t,e)=>e.some((a=>t.some((n=>a===n)))),is_not:(t,e)=>e.every((a=>t.every((n=>a!==n)))),regex:(t,e)=>e.some((a=>t.some((n=>Vp(a,n))))),not_regex:(t,e)=>e.every((a=>t.every((n=>!Vp(a,n))))),icontains:(t,e)=>e.map(wp).some((a=>t.map(wp).some((n=>a.includes(n))))),not_icontains:(t,e)=>e.map(wp).every((a=>t.map(wp).every((n=>!a.includes(n)))))},wp=t=>t.toLowerCase();function wE(t,e){return!t||Object.entries(t).every((a=>{var[n,r]=a,o=e?.[n];if(z(o)||dr(o))return!1;var i=[String(o)],s=_E[r.operator];return!!s&&s(r.values,i)}))}var Zy=pt("[Error tracking]"),qx=class{constructor(e){var a,n;this.Jt=[],this.Kt=new nx([new ox,new fx,new sx,new ix,new cx,new ux,new lx,new dx],FN("web:javascript",DN,PN)),this._instance=e,this.Jt=(a=(n=this._instance.persistence)==null?void 0:n.get_property(hx))!==null&&a!==void 0?a:[]}onRemoteConfig(e){var a,n,r,o=(a=(n=e.errorTracking)==null?void 0:n.suppressionRules)!==null&&a!==void 0?a:[],i=(r=e.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Jt=o,this._instance.persistence&&this._instance.persistence.register({[hx]:this.Jt,[UI]:i})}get Yt(){var e,a=!!this._instance.get_property(UI),n=this._instance.config.error_tracking.captureExtensionExceptions;return(e=n??a)!==null&&e!==void 0&&e}buildProperties(e,a){return this.Kt.buildFromUnknown(e,{syntheticException:a?.syntheticException,mechanism:{handled:a?.handled}})}sendExceptionEvent(e){var a=e.$exception_list;if(this.Xt(a)){if(this.Qt(a))return void Zy.info("Skipping exception capture because a suppression rule matched");if(!this.Yt&&this.Zt(a))return void Zy.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ti(a))return void Zy.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 a=e.reduce(((n,r)=>{var{type:o,value:i}=r;return ft(o)&&o.length>0&&n.$exception_types.push(o),ft(i)&&i.length>0&&n.$exception_values.push(i),n}),{$exception_types:[],$exception_values:[]});return this.Jt.some((n=>{var r=n.values.map((o=>{var i,s=_E[o.operator],l=Oe(o.value)?o.value:[o.value],u=(i=a[o.key])!==null&&i!==void 0?i:[];return l.length>0&&s(l,u)}));return n.type==="OR"?r.some(Boolean):r.every(Boolean)}))}Zt(e){return e.flatMap((a=>{var n,r;return(n=(r=a.stacktrace)==null?void 0:r.frames)!==null&&n!==void 0?n:[]})).some((a=>a.filename&&a.filename.startsWith("chrome-extension://")))}ti(e){if(e.length>0){var a,n,r,o,i=(a=(n=e[0].stacktrace)==null?void 0:n.frames)!==null&&a!==void 0?a:[],s=i[i.length-1];return(r=s==null||(o=s.filename)==null?void 0:o.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}Xt(e){return!Te(e)&&Oe(e)}},nn=pt("[FeatureFlags]"),Zu=pt("[FeatureFlags]",{debugEnabled:!0}),Wy="$active_feature_flags",Us="$override_feature_flags",dA="$feature_flag_payloads",Wu="$override_feature_flag_payloads",fA="$feature_flag_request_id",pA="$feature_flag_evaluated_at",hA=t=>{var e={};for(var[a,n]of Lp(t||{}))n&&(e[a]=n);return e},H4=t=>{var e=t.flags;return e?(t.featureFlags=Object.fromEntries(Object.keys(e).map((a=>{var n;return[a,(n=e[a].variant)!==null&&n!==void 0?n:e[a].enabled]}))),t.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter((a=>e[a].enabled)).filter((a=>{var n;return(n=e[a].metadata)==null?void 0:n.payload})).map((a=>{var n;return[a,(n=e[a].metadata)==null?void 0:n.payload]})))):nn.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),t},U4=(function(t){return t.FeatureFlags="feature_flags",t.Recordings="recordings",t})({}),$x=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((a=>{var n=a&&typeof a=="string"&&a.trim().length>0;return n||nn.error("Invalid evaluation environment found:",a,"Expected non-empty string"),n})):[]}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(mx),a=this._instance.get_property(Us),n=this._instance.get_property(Wu);if(!n&&!a)return e||{};var r=at({},e||{}),o=[...new Set([...Object.keys(n||{}),...Object.keys(a||{})])];for(var i of o){var s,l,u=r[i],c=a?.[i],d=z(c)?(s=u?.enabled)!==null&&s!==void 0&&s:!!c,f=z(c)?u.variant:typeof c=="string"?c:void 0,h=n?.[i],S=Z({},u,{enabled:d,variant:d?f??u?.variant:void 0});d!==u?.enabled&&(S.original_enabled=u?.enabled),f!==u?.variant&&(S.original_variant=u?.variant),h&&(S.metadata=Z({},u?.metadata,{payload:h,original_payload:u==null||(l=u.metadata)==null?void 0:l.payload})),r[i]=S}return this.ii||(nn.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:n,finalDetails:r}),this.ii=!0),r}getFlagVariants(){var e=this._instance.get_property(Vs),a=this._instance.get_property(Us);if(!a)return e||{};for(var n=at({},e),r=Object.keys(a),o=0;o<r.length;o++)n[r[o]]=a[r[o]];return this.ii||(nn.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:a,finalFlags:n}),this.ii=!0),n}getFlagPayloads(){var e=this._instance.get_property(dA),a=this._instance.get_property(Wu);if(!a)return e||{};for(var n=at({},e||{}),r=Object.keys(a),o=0;o<r.length;o++)n[r[o]]=a[r[o]];return this.ii||(nn.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:a,finalPayloads:n}),this.ii=!0),n}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 a;if(this.di(),!this._instance.O())if(this.ri)this.ni=!0;else{var n={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:Z({},((a=this._instance.persistence)==null?void 0:a.get_initial_props())||{},this._instance.get_property(ec)||{}),group_properties:this._instance.get_property(yi)};(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(n.disable_flags=!0),this.ui()&&(n.evaluation_environments=this.li());var r=this._instance.config.__preview_remote_config,o=r?"/flags/?v=2":"/flags/?v=2&config=true",i=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",s=this._instance.requestRouter.endpointFor("flags",o+i);r&&(n.timezone=yE()),this.ri=!0,this._instance.ci({method:"POST",url:s,data:n,compression:this._instance.config.disable_compression?void 0:cr.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:l=>{var u,c,d=!0;if(l.statusCode===200&&(this.ni||(this.$anon_distinct_id=void 0),d=!1),this.ri=!1,this.oi||(this.oi=!0,this._instance.fi((c=l.json)!==null&&c!==void 0?c:{})),!n.disable_flags||this.ni)if(this.ai=!d,l.json&&(u=l.json.quotaLimited)!=null&&u.includes(U4.FeatureFlags))nn.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 f;n.disable_flags||this.receivedFeatureFlags((f=l.json)!==null&&f!==void 0?f:{},d),this.ni&&(this.ni=!1,this.vi())}}})}}getFeatureFlag(e,a){if(a===void 0&&(a={}),this.ei||this.getFlags()&&this.getFlags().length>0){var n=this.getFlagVariants()[e],r=""+n,o=this._instance.get_property(fA)||void 0,i=this._instance.get_property(pA)||void 0,s=this._instance.get_property(Rp)||{};if((a.send_event||!("send_event"in a))&&(!(e in s)||!s[e].includes(r))){var l,u,c,d,f,h,S,x,b;Oe(s[e])?s[e].push(r):s[e]=[r],(l=this._instance.persistence)==null||l.register({[Rp]:s});var m=this.getFeatureFlagDetails(e),g={$feature_flag:e,$feature_flag_response:n,$feature_flag_payload:this.getFeatureFlagPayload(e)||null,$feature_flag_request_id:o,$feature_flag_evaluated_at:i,$feature_flag_bootstrapped_response:((u=this._instance.config.bootstrap)==null||(u=u.featureFlags)==null?void 0:u[e])||null,$feature_flag_bootstrapped_payload:((c=this._instance.config.bootstrap)==null||(c=c.featureFlagPayloads)==null?void 0:c[e])||null,$used_bootstrap_value:!this.ai};z(m==null||(d=m.metadata)==null?void 0:d.version)||(g.$feature_flag_version=m.metadata.version);var v,y=(f=m==null||(h=m.reason)==null?void 0:h.description)!==null&&f!==void 0?f:m==null||(S=m.reason)==null?void 0:S.code;y&&(g.$feature_flag_reason=y),m!=null&&(x=m.metadata)!=null&&x.id&&(g.$feature_flag_id=m.metadata.id),z(m?.original_variant)&&z(m?.original_enabled)||(g.$feature_flag_original_response=z(m.original_variant)?m.original_enabled:m.original_variant),m!=null&&(b=m.metadata)!=null&&b.original_payload&&(g.$feature_flag_original_payload=m==null||(v=m.metadata)==null?void 0:v.original_payload),this._instance.capture("$feature_flag_called",g)}return n}nn.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,a){var n=this._instance.config.token,r={distinct_id:this._instance.get_distinct_id(),token:n};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:cr.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:o=>{var i,s=(i=o.json)==null?void 0:i.featureFlagPayloads;a(s?.[e]||void 0)}})}isFeatureEnabled(e,a){if(a===void 0&&(a={}),this.ei||this.getFlags()&&this.getFlags().length>0){var n=this.getFeatureFlag(e,a);return z(n)?void 0:!!n}nn.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((a=>a!==e))}receivedFeatureFlags(e,a){if(this._instance.persistence){this.ei=!0;var n=this.getFlagVariants(),r=this.getFlagPayloads(),o=this.getFlagsWithDetails();(function(i,s,l,u,c){l===void 0&&(l={}),u===void 0&&(u={}),c===void 0&&(c={});var d=H4(i),f=d.flags,h=d.featureFlags,S=d.featureFlagPayloads;if(h){var x=i.requestId,b=i.evaluatedAt;if(Oe(h)){nn.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var g=0;g<h.length;g++)m[h[g]]=!0;s&&s.register({[Wy]:h,[Vs]:m})}else{var v=h,y=S,_=f;i.errorsWhileComputingFlags&&(v=Z({},l,v),y=Z({},u,y),_=Z({},c,_)),s&&s.register(Z({[Wy]:Object.keys(hA(v)),[Vs]:v||{},[dA]:y||{},[mx]:_||{}},x?{[fA]:x}:{},b?{[pA]:b}:{}))}}})(e,this._instance.persistence,n,r,o),this.pi(a)}}override(e,a){a===void 0&&(a=!1),nn.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:a})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return nn.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(Us),this._instance.persistence.unregister(Wu),this.pi(),Zu.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var a,n=e;if(this.ii=!!((a=n.suppressWarning)!==null&&a!==void 0&&a),"flags"in n){if(n.flags===!1)this._instance.persistence.unregister(Us),Zu.info("Flag overrides cleared");else if(n.flags){if(Oe(n.flags)){for(var r={},o=0;o<n.flags.length;o++)r[n.flags[o]]=!0;this._instance.persistence.register({[Us]:r})}else this._instance.persistence.register({[Us]:n.flags});Zu.info("Flag overrides set",{flags:n.flags})}}return"payloads"in n&&(n.payloads===!1?(this._instance.persistence.unregister(Wu),Zu.info("Payload overrides cleared")):n.payloads&&(this._instance.persistence.register({[Wu]:n.payloads}),Zu.info("Payload overrides set",{payloads:n.payloads}))),void this.pi()}this.pi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ei){var{flags:a,flagVariants:n}=this.gi();e(a,n)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,a,n){var r,o=(this._instance.get_property(Ju)||[]).find((u=>u.flagKey===e)),i={["$feature_enrollment/"+e]:a},s={$feature_flag:e,$feature_enrollment:a,$set:i};o&&(s.$early_access_feature_name=o.name),n&&(s.$feature_enrollment_stage=n),this._instance.capture("$feature_enrollment_update",s),this.setPersonPropertiesForFlags(i,!1);var l=Z({},this.getFlagVariants(),{[e]:a});(r=this._instance.persistence)==null||r.register({[Wy]:Object.keys(hA(l)),[Vs]:l}),this.pi()}getEarlyAccessFeatures(e,a,n){a===void 0&&(a=!1);var r=this._instance.get_property(Ju),o=n?"&"+n.map((i=>"stage="+i)).join("&"):"";if(r&&!a)return e(r);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+o),method:"GET",callback:i=>{var s,l;if(i.json){var u=i.json.earlyAccessFeatures;return(s=this._instance.persistence)==null||s.unregister(Ju),(l=this._instance.persistence)==null||l.register({[Ju]:u}),e(u)}}})}gi(){var e=this.getFlags(),a=this.getFlagVariants();return{flags:e.filter((n=>a[n])),flagVariants:Object.keys(a).filter((n=>a[n])).reduce(((n,r)=>(n[r]=a[r],n)),{})}}pi(e){var{flags:a,flagVariants:n}=this.gi();this.featureFlagEventHandlers.forEach((r=>r(a,n,{errorsLoading:e})))}setPersonPropertiesForFlags(e,a){a===void 0&&(a=!0);var n=this._instance.get_property(ec)||{};this._instance.register({[ec]:Z({},n,e)}),a&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(ec)}setGroupPropertiesForFlags(e,a){a===void 0&&(a=!0);var n=this._instance.get_property(yi)||{};Object.keys(n).length!==0&&Object.keys(n).forEach((r=>{n[r]=Z({},n[r],e[r]),delete e[r]})),this._instance.register({[yi]:Z({},n,e)}),a&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var a=this._instance.get_property(yi)||{};this._instance.register({[yi]:Z({},a,{[e]:{}})})}else this._instance.unregister(yi)}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}},z4=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],oc=class{constructor(e,a){this.F=e,this.props={},this.mi=!1,this.yi=(n=>{var r="";return n.token&&(r=n.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),n.persistence_name?"ph_"+n.persistence_name:"ph_"+r+"_posthog"})(e),this.Y=this.bi(e),this.load(),e.debug&&$.info("Persistence loaded",e.persistence,Z({},this.props)),this.update_config(e,e,a),this.save()}isDisabled(){return!!this.wi}bi(e){z4.indexOf(e.persistence.toLowerCase())===-1&&($.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var a=e.persistence.toLowerCase();return a==="localstorage"&&Xe.H()?Xe:a==="localstorage+cookie"&&bp.H()?bp:a==="sessionstorage"&&At.H()?At:a==="memory"?u4:a==="cookie"?Cn:bp.H()?bp:Cn}properties(){var e={};return Pe(this.props,(function(a,n){if(n===Vs&&yt(a))for(var r=Object.keys(a),o=0;o<r.length;o++)e["$feature/"+r[o]]=a[r[o]];else s=n,l=!1,(dr(i=jN)?l:AI&&i.indexOf===AI?i.indexOf(s)!=-1:(Pe(i,(function(u){if(l||(l=u===s))return Ep})),l))||(e[n]=a);var i,s,l})),e}load(){if(!this.wi){var e=this.Y.W(this.yi);e&&(this.props=at({},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,a,n){if(yt(e)){z(a)&&(a="None"),this.xi=z(n)?this.$i:n;var r=!1;if(Pe(e,((o,i)=>{this.props.hasOwnProperty(i)&&this.props[i]!==a||(this.props[i]=o,r=!0)})),r)return this.save(),!0}return!1}register(e,a){if(yt(e)){this.xi=z(a)?this.$i:a;var n=!1;if(Pe(e,((r,o)=>{e.hasOwnProperty(o)&&this.props[o]!==r&&(this.props[o]=r,n=!0)})),n)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=fE(this.F.custom_campaign_params,this.F.mask_personal_data_properties,this.F.custom_personal_data_properties);$s(sb(e))||this.register(e),this.mi=!0}}update_search_keyword(){var e;this.register((e=q?.referrer)?hE(e):{})}update_referrer_info(){var e;this.register_once({$referrer:mE(),$referring_domain:q!=null&&q.referrer&&((e=Pp(q.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[xx]||this.props[bx]||this.register_once({[Mp]:gE(this.F.mask_personal_data_properties,this.F.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};Pe([bx,xx],(i=>{var s=this.props[i];s&&Pe(s,(function(l,u){e["$initial_"+Jy(u)]=l}))}));var a,n,r=this.props[Mp];if(r){var o=(a=vE(r),n={},Pe(a,(function(i,s){n["$initial_"+Jy(s)]=i})),n);at(e,o)}return e}safe_merge(e){return Pe(this.props,(function(a,n){n in e||(e[n]=a)})),e}update_config(e,a,n){if(this.$i=this.xi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!n),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==a.persistence){var r=this.bi(e),o=this.props;this.clear(),this.Y=r,this.props=o,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,a){var n=this.props[Qu]||{};n[e]=a,this.props[Qu]=n,this.save()}remove_event_timer(e){var a=(this.props[Qu]||{})[e];return z(a)||(delete this.props[Qu][e],this.save()),a}get_property(e){return this.props[e]}set_property(e,a){this.props[e]=a,this.save()}},Xu=(function(t){return t.Activation="events",t.Cancellation="cancelEvents",t})({}),K$=(function(t){return t.Button="button",t.Tab="tab",t.Selector="selector",t})({}),Q$=(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})({}),J$=(function(t){return t.Top="top",t.Left="left",t.Right="right",t.Bottom="bottom",t})({}),Xy=(function(t){return t.Popover="popover",t.API="api",t.Widget="widget",t.ExternalSurvey="external_survey",t})({}),eV=(function(t){return t.Open="open",t.MultipleChoice="multiple_choice",t.SingleChoice="single_choice",t.Rating="rating",t.Link="link",t})({}),tV=(function(t){return t.NextQuestion="next_question",t.End="end",t.ResponseBased="response_based",t.SpecificQuestion="specific_question",t})({}),aV=(function(t){return t.Once="once",t.Recurring="recurring",t.Always="always",t})({}),Ip=(function(t){return t.SHOWN="survey shown",t.DISMISSED="survey dismissed",t.SENT="survey sent",t})({}),mA=(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})({}),LE=(function(t){return t.Popover="popover",t.Inline="inline",t})({}),fc=class{constructor(){this.ki={},this.ki={}}on(e,a){return this.ki[e]||(this.ki[e]=[]),this.ki[e].push(a),()=>{this.ki[e]=this.ki[e].filter((n=>n!==a))}}emit(e,a){for(var n of this.ki[e]||[])n(a);for(var r of this.ki["*"]||[])r(e,a)}};function zs(t,e,a){if(Te(t))return!1;switch(a){case"exact":return t===e;case"contains":var n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(n,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}var Vx=class{constructor(e){this.Pi=new fc,this.Ti=(a,n)=>this.Ri(a,n)&&this.Ii(a,n)&&this.Fi(a,n)&&this.Ci(a,n),this.Ri=(a,n)=>n==null||!n.event||a?.event===n?.event,this._instance=e,this.Mi=new Set,this.Oi=new Set}init(){var e;if(!z((e=this._instance)==null?void 0:e.Ai)){var a;(a=this._instance)==null||a.Ai(((n,r)=>{this.on(n,r)}))}}register(e){var a,n;if(!z((a=this._instance)==null?void 0:a.Ai)&&(e.forEach((i=>{var s,l;(s=this.Oi)==null||s.add(i),(l=i.steps)==null||l.forEach((u=>{var c;(c=this.Mi)==null||c.add(u?.event||"")}))})),(n=this._instance)!=null&&n.autocapture)){var r,o=new Set;e.forEach((i=>{var s;(s=i.steps)==null||s.forEach((l=>{l!=null&&l.selector&&o.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(o)}}on(e,a){var n;a!=null&&e.length!=0&&(this.Mi.has(e)||this.Mi.has(a?.event))&&this.Oi&&((n=this.Oi)==null?void 0:n.size)>0&&this.Oi.forEach((r=>{this.Di(a,r)&&this.Pi.emit("actionCaptured",r.name)}))}ji(e){this.onAction("actionCaptured",(a=>e(a)))}Di(e,a){if(a?.steps==null)return!1;for(var n of a.steps)if(this.Ti(e,n))return!0;return!1}onAction(e,a){return this.Pi.on(e,a)}Ii(e,a){if(a!=null&&a.url){var n,r=e==null||(n=e.properties)==null?void 0:n.$current_url;if(!r||typeof r!="string"||!zs(r,a.url,a.url_matching||"contains"))return!1}return!0}Fi(e,a){return!!this.Li(e,a)&&!!this.Ni(e,a)&&!!this.Ui(e,a)}Li(e,a){var n;if(a==null||!a.href)return!0;var r=this.zi(e);if(r.length>0)return r.some((s=>zs(s.href,a.href,a.href_matching||"exact")));var o,i=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!i&&zs((o=i.match(/(?::|")href="(.*?)"/))?o[1]:"",a.href,a.href_matching||"exact")}Ni(e,a){var n;if(a==null||!a.text)return!0;var r=this.zi(e);if(r.length>0)return r.some((u=>zs(u.text,a.text,a.text_matching||"exact")||zs(u.$el_text,a.text,a.text_matching||"exact")));var o,i,s,l=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!l&&(o=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!Te(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),i=a.text,s=a.text_matching||"exact",o.some((u=>zs(u,i,s))))}Ui(e,a){var n,r;if(a==null||!a.selector)return!0;var o=e==null||(n=e.properties)==null?void 0:n.$element_selectors;if(o!=null&&o.includes(a.selector))return!0;var i=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(a.selector_regex&&i)try{return new RegExp(a.selector_regex).test(i)}catch{return!1}return!1}zi(e){var a;return(e==null||(a=e.properties)==null?void 0:a.$elements)==null?[]:e?.properties.$elements}Ci(e,a){return a==null||!a.properties||a.properties.length===0||wE(a.properties.reduce(((n,r)=>{var o=Oe(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return n[r.key]={values:o,operator:r.operator||"exact"},n}),{}),e?.properties)}},Le=pt("[Surveys]"),jx="seenSurvey_",q4=(t,e)=>{var a="$survey_"+e+"/"+t.id;return t.current_iteration&&t.current_iteration>0&&(a="$survey_"+e+"/"+t.id+"/"+t.current_iteration),a},gA=t=>{var e=""+jx+t.id;return t.current_iteration&&t.current_iteration>0&&(e=""+jx+t.id+"_"+t.current_iteration),e},$4=[Xy.Popover,Xy.Widget,Xy.API],V4={ignoreConditions:!1,ignoreDelay:!1,displayType:LE.Popover},Gx=class{constructor(e){this._instance=e,this.Hi=new Map,this.Bi=new Map,this.qi=new Map}Wi(e,a){return!!e&&wE(e.propertyFilters,a?.properties)}Gi(e,a){var n=new Map;return e.forEach((r=>{var o;(o=r.conditions)==null||(o=o[a])==null||(o=o.values)==null||o.forEach((i=>{if(i!=null&&i.name){var s=n.get(i.name)||[];s.push(r.id),n.set(i.name,s)}}))})),n}Vi(e,a,n){var r,o=(n===Xu.Activation?this.Hi:this.Bi).get(e),i=[];return(r=this._instance)==null||r.getSurveys((s=>{i=s.filter((l=>o?.includes(l.id)))})),i.filter((s=>{var l,u=(l=s.conditions)==null||(l=l[n])==null||(l=l.values)==null?void 0:l.find((c=>c.name===e));return this.Wi(u,a)}))}register(e){var a;z((a=this._instance)==null?void 0:a.Ai)||(this.Ji(e),this.Ki(e))}Ki(e){var a=e.filter((n=>{var r,o;return((r=n.conditions)==null?void 0:r.actions)&&((o=n.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0}));a.length!==0&&(this.Yi==null&&(this.Yi=new Vx(this._instance),this.Yi.init(),this.Yi.ji((n=>{this.onAction(n)}))),a.forEach((n=>{var r,o,i,s,l;n.conditions&&(r=n.conditions)!=null&&r.actions&&(o=n.conditions)!=null&&(o=o.actions)!=null&&o.values&&((i=n.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0&&((s=this.Yi)==null||s.register(n.conditions.actions.values),(l=n.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.qi.get(u.name);c&&c.push(n.id),this.qi.set(u.name,c||[n.id])}})))})))}Ji(e){var a,n=e.filter((o=>{var i,s;return((i=o.conditions)==null?void 0:i.events)&&((s=o.conditions)==null||(s=s.events)==null||(s=s.values)==null?void 0:s.length)>0})),r=e.filter((o=>{var i,s;return((i=o.conditions)==null?void 0:i.cancelEvents)&&((s=o.conditions)==null||(s=s.cancelEvents)==null||(s=s.values)==null?void 0:s.length)>0}));(n.length!==0||r.length!==0)&&((a=this._instance)==null||a.Ai(((o,i)=>{this.onEvent(o,i)})),this.Hi=this.Gi(e,Xu.Activation),this.Bi=this.Gi(e,Xu.Cancellation))}onEvent(e,a){var n,r=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[xp])||[];if(Ip.SHOWN===e&&a&&r.length>0){var o;Le.info("survey event matched, removing survey from activated surveys",{event:e,eventPayload:a,existingActivatedSurveys:r});var i=a==null||(o=a.properties)==null?void 0:o.$survey_id;if(i){var s=r.indexOf(i);s>=0&&(r.splice(s,1),this.Xi(r))}}else{if(this.Bi.has(e)){var l=this.Vi(e,a,Xu.Cancellation);l.length>0&&(Le.info("cancel event matched, cancelling surveys",{event:e,surveysToCancel:l.map((c=>c.id))}),l.forEach((c=>{var d,f=r.indexOf(c.id);f>=0&&r.splice(f,1),(d=this._instance)==null||d.cancelPendingSurvey(c.id)})),this.Xi(r))}if(this.Hi.has(e)){Le.info("survey event name matched",{event:e,eventPayload:a,surveys:this.Hi.get(e)});var u=this.Vi(e,a,Xu.Activation);this.Xi(r.concat(u.map((c=>c.id))||[]))}}}onAction(e){var a,n=((a=this._instance)==null||(a=a.persistence)==null?void 0:a.props[xp])||[];this.qi.has(e)&&this.Xi(n.concat(this.qi.get(e)||[]))}Xi(e){var a;Le.info("updating activated surveys",{activatedSurveys:e}),(a=this._instance)==null||(a=a.persistence)==null||a.register({[xp]:[...new Set(e)]})}getSurveys(){var e,a=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[xp];return a||[]}getEventToSurveys(){return this.Hi}Qi(){return this.Yi}},Zx=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 a=e.surveys;if(Te(a))return Le.warn("Flags not loaded yet. Not loading surveys.");var n=Oe(a);this.Zi=n?a.length>0:a,Le.info("flags response received, isSurveysEnabled: "+this.Zi),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],a=0;a<localStorage.length;a++){var n=localStorage.key(a);(n!=null&&n.startsWith(jx)||n!=null&&n.startsWith("inProgressSurvey_"))&&e.push(n)}e.forEach((r=>localStorage.removeItem(r)))}loadIfEnabled(){if(!this._surveyManager)if(this.ie)Le.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)Le.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())Le.info("Not loading surveys in cookieless mode without consent.");else{var e=te?.__PosthogExtensions__;if(e){if(!z(this.Zi)||this._instance.config.advanced_enable_surveys){var a=this.Zi||this._instance.config.advanced_enable_surveys;this.ie=!0;try{var n=e.generateSurveys;if(n)return void this.re(n,a);var r=e.loadExternalDependency;if(!r)return void this.se("PostHog loadExternalDependency extension not found.");r(this._instance,"surveys",(o=>{o||!e.generateSurveys?this.se("Could not load surveys script",o):this.re(e.generateSurveys,a)}))}catch(o){throw this.se("Error initializing surveys",o),o}finally{this.ie=!1}}}else Le.error("PostHog Extensions not found.")}}re(e,a){this._surveyManager=e(this._instance,a),this._surveyEventReceiver=new Gx(this._instance),Le.info("Surveys loaded successfully"),this.ne({isLoaded:!0})}se(e,a){Le.error(e,a),this.ne({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.ee.push(e),this._surveyManager&&this.ne({isLoaded:!0}),()=>{this.ee=this.ee.filter((a=>a!==e))}}getSurveys(e,a){if(a===void 0&&(a=!1),this._instance.config.disable_surveys)return Le.info("Disabled. Not loading surveys."),e([]);var n=this._instance.get_property(gx);if(n&&!a)return e(n,{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 o;this.te=!1;var i=r.statusCode;if(i!==200||!r.json){var s="Surveys API could not be loaded, status: "+i;return Le.error(s),e([],{isLoaded:!1,error:s})}var l,u=r.json.surveys||[],c=u.filter((d=>(function(f){return!(!f.start_date||f.end_date)})(d)&&((function(f){var h;return!((h=f.conditions)==null||(h=h.events)==null||(h=h.values)==null||!h.length)})(d)||(function(f){var h;return!((h=f.conditions)==null||(h=h.actions)==null||(h=h.values)==null||!h.length)})(d))));return c.length>0&&((l=this._surveyEventReceiver)==null||l.register(c)),(o=this._instance.persistence)==null||o.register({[gx]:u}),e(u,{isLoaded:!0})}})}catch(r){throw this.te=!1,r}}ne(e){for(var a of this.ee)try{if(!e.isLoaded)return a([],e);this.getSurveys(a)}catch(n){Le.error("Error in survey callback",n)}}getActiveMatchingSurveys(e,a){if(a===void 0&&(a=!1),!Te(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,a);Le.warn("init was not called")}oe(e){var a=null;return this.getSurveys((n=>{var r;a=(r=n.find((o=>o.id===e)))!==null&&r!==void 0?r:null})),a}ae(e){if(Te(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var a=typeof e=="string"?this.oe(e):e;return a?this._surveyManager.checkSurveyEligibility(a):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(Te(this._surveyManager))return Le.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var a=this.ae(e);return{visible:a.eligible,disabledReason:a.reason}}canRenderSurveyAsync(e,a){return Te(this._surveyManager)?(Le.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise((n=>{this.getSurveys((r=>{var o,i=(o=r.find((l=>l.id===e)))!==null&&o!==void 0?o:null;if(i){var s=this.ae(i);n({visible:s.eligible,disabledReason:s.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),a)}))}renderSurvey(e,a){var n;if(Te(this._surveyManager))Le.warn("init was not called");else{var r=typeof e=="string"?this.oe(e):e;if(r!=null&&r.id)if($4.includes(r.type)){var o=q?.querySelector(a);if(o)return(n=r.appearance)!=null&&n.surveyPopupDelaySeconds?(Le.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var i,s;Le.info("Rendering survey "+r.id+" with delay of "+((i=r.appearance)==null?void 0:i.surveyPopupDelaySeconds)+" seconds"),(s=this._surveyManager)==null||s.renderSurvey(r,o),Le.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,o);Le.warn("Survey element not found")}else Le.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Le.warn("Survey not found")}}displaySurvey(e,a){var n;if(Te(this._surveyManager))Le.warn("init was not called");else{var r=this.oe(e);if(r){var o=r;if((n=r.appearance)!=null&&n.surveyPopupDelaySeconds&&a.ignoreDelay&&(o=Z({},r,{appearance:Z({},r.appearance,{surveyPopupDelaySeconds:0})})),a.ignoreConditions===!1){var i=this.canRenderSurvey(r);if(!i.visible)return void Le.warn("Survey is not eligible to be displayed: ",i.disabledReason)}a.displayType!==LE.Inline?this._surveyManager.handlePopoverSurvey(o):this.renderSurvey(o,a.selector)}else Le.warn("Survey not found")}}cancelPendingSurvey(e){Te(this._surveyManager)?Le.warn("init was not called"):this._surveyManager.cancelSurvey(e)}},vA=pt("[RateLimiter]"),Wx=class{constructor(e){var a,n;this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=r=>{var o=r.text;if(o&&o.length)try{(JSON.parse(o).quota_limited||[]).forEach((i=>{vA.info((i||"events")+" is quota limited."),this.serverLimits[i]=new Date().getTime()+6e4}))}catch(i){return void vA.warn('could not rate limit - continuing. Error: "'+i?.message+'"',{text:o})}},this.instance=e,this.captureEventsPerSecond=((a=e.config.rate_limiting)==null?void 0:a.events_per_second)||10,this.captureEventsBurstLimit=Math.max(((n=e.config.rate_limiting)==null?void 0:n.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond),this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}clientRateLimitContext(e){var a,n,r;e===void 0&&(e=!1);var o=new Date().getTime(),i=(a=(n=this.instance.persistence)==null?void 0:n.get_property(yx))!==null&&a!==void 0?a:{tokens:this.captureEventsBurstLimit,last:o};i.tokens+=(o-i.last)/1e3*this.captureEventsPerSecond,i.last=o,i.tokens>this.captureEventsBurstLimit&&(i.tokens=this.captureEventsBurstLimit);var s=i.tokens<1;return s||e||(i.tokens=Math.max(0,i.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(yx,i),{isRateLimited:s,remainingTokens:i.tokens}}isServerRateLimited(e){var a=this.serverLimits[e||"events"]||!1;return a!==!1&&new Date().getTime()<a}},vi=pt("[RemoteConfig]"),Xx=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=te._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}le(e){var a,n;(a=te.__PosthogExtensions__)!=null&&a.loadExternalDependency?(n=te.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"remote-config",(()=>e(this.remoteConfig))):(vi.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:a=>{e(a.json)}})}load(){try{if(this.remoteConfig)return vi.info("Using preloaded remote config",this.remoteConfig),void this.fi(this.remoteConfig);if(this._instance.O())return void vi.warn("Remote config is disabled. Falling back to local config.");this.le((e=>{if(!e)return vi.info("No config found after loading remote JS config. Falling back to JSON."),void this.ue((a=>{this.fi(a)}));this.fi(e)}))}catch(e){vi.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()):vi.info("__preview_remote_config is disabled. Logging config instead",e):vi.error("Failed to fetch remote config from PostHog.")}},Yx=3e3,Kx=class{constructor(e,a){this.he=!0,this.ve=[],this.de=bn(a?.flush_interval_ms||Yx,250,5e3,$.createLogger("flush interval"),Yx),this.ce=e}enqueue(e){this.ve.push(e),this.fe||this.pe()}unload(){this.ge();var e=this.ve.length>0?this._e():{},a=Object.values(e);[...a.filter((n=>n.url.indexOf("/e")===0)),...a.filter((n=>n.url.indexOf("/e")!==0))].map((n=>{this.ce(Z({},n,{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 a=this._e(),n=function(){var o=a[r],i=new Date().getTime();o.data&&Oe(o.data)&&Pe(o.data,(s=>{s.offset=Math.abs(s.timestamp-i),delete s.timestamp})),e.ce(o)};for(var r in a)n()}}),this.de))}ge(){clearTimeout(this.fe),this.fe=void 0}_e(){var e={};return Pe(this.ve,(a=>{var n,r=a,o=(r?r.batchKey:null)||r.url;z(e[o])&&(e[o]=Z({},r,{data:[]})),(n=e[o].data)==null||n.push(r.data)})),this.ve=[],e}},j4=["retriesPerformedSoFar"],Qx=class{constructor(e){this.me=!1,this.ye=3e3,this.ve=[],this._instance=e,this.ve=[],this.be=!0,!z(E)&&"onLine"in E.navigator&&(this.be=E.navigator.onLine,this.we=()=>{this.be=!0,this.Dt()},this.xe=()=>{this.be=!1},lt(E,"online",this.we),lt(E,"offline",this.xe))}get length(){return this.ve.length}retriableRequest(e){var{retriesPerformedSoFar:a}=e,n=_A(e,j4);_n(a)&&a>0&&(n.url=$p(n.url,{retry_count:a})),this._instance.ci(Z({},n,{callback:r=>{r.statusCode!==200&&(r.statusCode<400||r.statusCode>=500)&&(a??0)<10?this.Se(Z({retriesPerformedSoFar:a},n)):n.callback==null||n.callback(r)}}))}Se(e){var a=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=a+1;var n=(function(i){var s=3e3*Math.pow(2,i),l=s/2,u=Math.min(18e5,s),c=(Math.random()-.5)*(u-l);return Math.ceil(u+c)})(a),r=Date.now()+n;this.ve.push({retryAt:r,requestOptions:e});var o="Enqueued failed request for retry in "+n;navigator.onLine||(o+=" (Browser is offline)"),$.warn(o),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(),a=[],n=this.ve.filter((o=>o.retryAt<e||(a.push(o),!1)));if(this.ve=a,n.length>0)for(var{requestOptions:r}of n)this.retriableRequest(r)}unload(){for(var{requestOptions:e}of(this.$e&&(clearTimeout(this.$e),this.$e=void 0),this.me=!1,z(E)||(this.we&&(E.removeEventListener("online",this.we),this.we=void 0),this.xe&&(E.removeEventListener("offline",this.xe),this.xe=void 0)),this.ve))try{this._instance.ci(Z({},e,{transport:"sendBeacon"}))}catch(a){$.error(a)}this.ve=[]}},Jx=class{constructor(e){this.ke=()=>{var a,n,r,o;this.Pe||(this.Pe={});var i=this.scrollElement(),s=this.scrollY(),l=i?Math.max(0,i.scrollHeight-i.clientHeight):0,u=s+(i?.clientHeight||0),c=i?.scrollHeight||0;this.Pe.lastScrollY=Math.ceil(s),this.Pe.maxScrollY=Math.max(s,(a=this.Pe.maxScrollY)!==null&&a!==void 0?a:0),this.Pe.maxScrollHeight=Math.max(l,(n=this.Pe.maxScrollHeight)!==null&&n!==void 0?n:0),this.Pe.lastContentY=u,this.Pe.maxContentY=Math.max(u,(r=this.Pe.maxContentY)!==null&&r!==void 0?r:0),this.Pe.maxContentHeight=Math.max(c,(o=this.Pe.maxContentHeight)!==null&&o!==void 0?o:0)},this._instance=e}getContext(){return this.Pe}resetContext(){var e=this.Pe;return setTimeout(this.ke,0),e}startMeasuringScrollPosition(){lt(E,"scroll",this.ke,{capture:!0}),lt(E,"scrollend",this.ke,{capture:!0}),lt(E,"resize",this.ke)}scrollElement(){if(!this._instance.config.scroll_root_selector)return E?.document.documentElement;var e=Oe(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var a of e){var n=E?.document.querySelector(a);if(n)return n}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return E&&(E.scrollY||E.pageYOffset||E.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return E&&(E.scrollX||E.pageXOffset||E.document.documentElement.scrollLeft)||0}},G4=t=>gE(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties),jp=class{constructor(e,a,n,r){this.Te=o=>{var i=this.Re();if(!i||i.sessionId!==o){var s={sessionId:o,props:this.Ie(this._instance)};this.Fe.register({[vx]:s})}},this._instance=e,this.Ce=a,this.Fe=n,this.Ie=r||G4,this.Ce.onSessionId(this.Te)}Re(){return this.Fe.props[vx]}getSetOnceProps(){var e,a=(e=this.Re())==null?void 0:e.props;return a?"r"in a?vE(a):{$referring_domain:a.referringDomain,$pathname:a.initialPathName,utm_source:a.utm_source,utm_campaign:a.utm_campaign,utm_medium:a.utm_medium,utm_content:a.utm_content,utm_term:a.utm_term}:{}}getSessionProps(){var e={};return Pe(sb(this.getSetOnceProps()),((a,n)=>{n==="$current_url"&&(n="url"),e["$session_entry_"+Jy(n)]=a})),e}},Yy=pt("[SessionId]"),Gp=class{on(e,a){return this.Me.on(e,a)}constructor(e,a,n){var r;if(this.Oe=[],this.Ae=void 0,this.Me=new fc,this.De=(c,d)=>Math.abs(c-d)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.F=e.config,this.Fe=e.persistence,this.je=void 0,this.Le=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.Ne=a||ho,this.Ue=n||ho;var o=this.F.persistence_name||this.F.token,i=this.F.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*bn(i,60,36e3,Yy.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.ze(),this.He="ph_"+o+"_window_id",this.Be="ph_"+o+"_primary_window_exists",this.qe()){var s=At.W(this.He),l=At.W(this.Be);s&&!l?this.je=s:At.V(this.He),At.G(this.Be,!0)}if((r=this.F.bootstrap)!=null&&r.sessionID)try{var u=(c=>{var d=c.replace(/-/g,"");if(d.length!==32)throw new Error("Not a valid UUID");if(d[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(d.substring(0,12),16)})(this.F.bootstrap.sessionID);this.We(this.F.bootstrap.sessionID,new Date().getTime(),u)}catch(c){Yy.error("Invalid sessionID in bootstrap",c)}this.Ge()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return z(this.Oe)&&(this.Oe=[]),this.Oe.push(e),this.Le&&e(this.Le,this.je),()=>{this.Oe=this.Oe.filter((a=>a!==e))}}qe(){return this.F.persistence!=="memory"&&!this.Fe.wi&&At.H()}Ve(e){e!==this.je&&(this.je=e,this.qe()&&At.G(this.He,e))}Je(){return this.je?this.je:this.qe()?At.W(this.He):null}We(e,a,n){e===this.Le&&a===this._sessionActivityTimestamp&&n===this._sessionStartTimestamp||(this._sessionStartTimestamp=n,this._sessionActivityTimestamp=a,this.Le=e,this.Fe.register({[Tp]:[a,e,n]}))}Ke(){var e=this.Fe.props[Tp];return Oe(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&&E&&(E.removeEventListener("beforeunload",this.Ae,{capture:!1}),this.Ae=void 0),this.Oe=[]}Ge(){this.Ae=()=>{this.qe()&&At.V(this.Be)},lt(E,"beforeunload",this.Ae,{capture:!1})}checkAndGetSessionAndWindowId(e,a){if(e===void 0&&(e=!1),a===void 0&&(a=null),this.F.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var n=a||new Date().getTime(),[r,o,i]=this.Ke(),s=this.Je(),l=_n(i)&&i>0&&Math.abs(n-i)>864e5,u=!1,c=!o,d=!c&&!e&&this.De(n,r);c||d||l?(o=this.Ne(),s=this.Ue(),Yy.info("new session ID generated",{sessionId:o,windowId:s,changeReason:{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}}),i=n,u=!0):s||(s=this.Ue(),u=!0);var f=r===0||!e||l?n:r,h=i===0?new Date().getTime():i;return this.Ve(s),this.We(o,f,h),e||this.ze(),u&&this.Oe.forEach((S=>S(o,s,u?{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}:void 0))),{sessionId:o,windowId:s,sessionStartTimestamp:h,changeReason:u?{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:r}}ze(){clearTimeout(this.Ye),this.Ye=setTimeout((()=>{var[e]=this.Ke();if(this.De(new Date().getTime(),e)){var a=this.Le;this.resetSessionId(),this.Me.emit("forcedIdleReset",{idleSessionId:a})}}),1.1*this.sessionTimeoutMs)}},Z4=["$set_once","$set"],fo=pt("[SiteApps]"),eb=class{constructor(e){this._instance=e,this.Xe=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Qe(e,a){if(a){var n=this.globalsForEvent(a);this.Xe.push(n),this.Xe.length>1e3&&(this.Xe=this.Xe.slice(10))}}get siteAppLoaders(){var e;return(e=te._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 a,n,r,o,i,s,l;if(!e)throw new Error("Event payload is required");var u={},c=this._instance.get_property("$groups")||[],d=this._instance.get_property("$stored_group_properties")||{};for(var[f,h]of Object.entries(d))u[f]={id:c[f],type:f,properties:h};var{$set_once:S,$set:x}=e;return{event:Z({},_A(e,Z4),{properties:Z({},e.properties,x?{$set:Z({},(a=(n=e.properties)==null?void 0:n.$set)!==null&&a!==void 0?a:{},x)}:{},S?{$set_once:Z({},(r=(o=e.properties)==null?void 0:o.$set_once)!==null&&r!==void 0?r:{},S)}:{}),elements_chain:(i=(s=e.properties)==null?void 0:s.$elements_chain)!==null&&i!==void 0?i:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:u}}setupSiteApp(e){var a=this.apps[e.id],n=()=>{var s;!a.errored&&this.Xe.length&&(fo.info("Processing "+this.Xe.length+" events for site app with id "+e.id),this.Xe.forEach((l=>a.processEvent==null?void 0:a.processEvent(l))),a.processedBuffer=!0),Object.values(this.apps).every((l=>l.processedBuffer||l.errored))&&((s=this.Ze)==null||s.call(this))},r=!1,o=s=>{a.errored=!s,a.loaded=!0,fo.info("Site app with id "+e.id+" "+(s?"loaded":"errored")),r&&n()};try{var{processEvent:i}=e.init({posthog:this._instance,callback:s=>{o(s)}});i&&(a.processEvent=i),r=!0}catch(s){fo.error("Error while initializing PostHog app with config id "+e.id,s),o(!1)}if(r&&a.loaded)try{n()}catch(s){fo.error("Error while processing buffered events PostHog app with config id "+e.id,s),a.errored=!0}}tr(){var e=this.siteAppLoaders||[];for(var a of e)this.apps[a.id]={id:a.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of e)this.setupSiteApp(n)}ir(e){if(Object.keys(this.apps).length!==0){var a=this.globalsForEvent(e);for(var n of Object.values(this.apps))try{n.processEvent==null||n.processEvent(a)}catch(r){fo.error("Error while processing event "+e.event+" for site app "+n.id,r)}}}onRemoteConfig(e){var a,n,r,o=this;if((a=this.siteAppLoaders)!=null&&a.length)return this.isEnabled?(this.tr(),void this._instance.on("eventCaptured",(u=>this.ir(u)))):void fo.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.Ze)==null||n.call(this),(r=e.siteApps)!=null&&r.length)if(this.isEnabled){var i=function(u){var c;te["__$$ph_site_app_"+u]=o._instance,(c=te.__PosthogExtensions__)==null||c.loadSiteApp==null||c.loadSiteApp(o._instance,l,(d=>{if(d)return fo.error("Error while initializing PostHog app with config id "+u,d)}))};for(var{id:s,url:l}of e.siteApps)i(s)}else fo.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},kE=function(t,e){if(!t)return!1;var a=t.userAgent;if(a&&MI(a,e))return!0;try{var n=t?.userAgentData;if(n!=null&&n.brands&&n.brands.some((r=>MI(r?.brand,e))))return!0}catch{}return!!t.webdriver},nc=(function(t){return t.US="us",t.EU="eu",t.CUSTOM="custom",t})({}),yA="i.posthog.com",tb=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,a=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return a||(a=this.apiHost.replace("."+yA,".posthog.com")),a==="https://app.posthog.com"?"https://us.posthog.com":a}get region(){return this.er[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.er[this.apiHost]=nc.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.er[this.apiHost]=nc.EU:this.er[this.apiHost]=nc.CUSTOM),this.er[this.apiHost]}endpointFor(e,a){if(a===void 0&&(a=""),a&&(a=a[0]==="/"?a:"/"+a),e==="ui")return this.uiHost+a;if(e==="flags")return this.flagsApiHost+a;if(this.region===nc.CUSTOM)return this.apiHost+a;var n=yA+a;switch(e){case"assets":return"https://"+this.region+"-assets."+n;case"api":return"https://"+this.region+"."+n}}},W4={icontains:(t,e)=>!!E&&e.href.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>!!E&&e.href.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>!!E&&Vp(e.href,t),not_regex:(t,e)=>!!E&&!Vp(e.href,t),exact:(t,e)=>e.href===t,is_not:(t,e)=>e.href!==t},ab=class t{constructor(e){var a=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(n){n===void 0&&(n=!1),a.getWebExperiments((r=>{t.rr("retrieved web experiments from the server"),a.sr=new Map,r.forEach((o=>{if(o.feature_flag_key){var i;a.sr&&(t.rr("setting flag key ",o.feature_flag_key," to web experiment ",o),(i=a.sr)==null||i.set(o.feature_flag_key,o));var s=a._instance.getFeatureFlag(o.feature_flag_key);ft(s)&&o.variants[s]&&a.nr(o.name,s,o.variants[s].transforms)}else if(o.variants)for(var l in o.variants){var u=o.variants[l];t.ar(u)&&a.nr(o.name,l,u.transforms)}}))}),n)},this._instance=e,this._instance.onFeatureFlags((n=>{this.onFeatureFlags(n)}))}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(Te(this.sr))return this.sr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();t.rr("applying feature flags",e),e.forEach((a=>{var n;if(this.sr&&(n=this.sr)!=null&&n.has(a)){var r,o=this._instance.getFeatureFlag(a),i=(r=this.sr)==null?void 0:r.get(a);o&&i!=null&&i.variants[o]&&this.nr(i.name,o,i.variants[o].transforms)}}))}}previewWebExperiment(){var e=t.getWindowLocation();if(e!=null&&e.search){var a=Fp(e?.search,"__experiment_id"),n=Fp(e?.search,"__experiment_variant");a&&n&&(t.rr("previewing web experiments "+a+" && "+n),this.getWebExperiments((r=>{this.lr(parseInt(a),n,r)}),!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,a,n){if(this._instance.config.disable_web_experiments&&!n)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!a)return e(r);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:o=>{if(o.statusCode!==200||!o.json)return e([]);var i=o.json.experiments||[];return e(i)}})}lr(e,a,n){var r=n.filter((o=>o.id===e));r&&r.length>0&&(t.rr("Previewing web experiment ["+r[0].name+"] with variant ["+a+"]"),this.nr(r[0].name,a,r[0].variants[a].transforms))}static ar(e){return!Te(e.conditions)&&t.ur(e)&&t.hr(e)}static ur(e){var a;if(Te(e.conditions)||Te((a=e.conditions)==null?void 0:a.url))return!0;var n,r,o,i=t.getWindowLocation();return!!i&&((n=e.conditions)==null||!n.url||W4[(r=(o=e.conditions)==null?void 0:o.urlMatchType)!==null&&r!==void 0?r:"icontains"](e.conditions.url,i))}static getWindowLocation(){return E?.location}static hr(e){var a;if(Te(e.conditions)||Te((a=e.conditions)==null?void 0:a.utm))return!0;var n=fE();if(n.utm_source){var r,o,i,s,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((o=e.conditions)==null||(o=o.utm)==null?void 0:o.utm_campaign)==n.utm_campaign,h=(i=e.conditions)==null||(i=i.utm)==null||!i.utm_source||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_source)==n.utm_source,S=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==n.utm_medium,x=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==n.utm_term;return f&&S&&x&&h}return!1}static rr(e){for(var a=arguments.length,n=new Array(a>1?a-1:0),r=1;r<a;r++)n[r-1]=arguments[r];$.info("[WebExperiments] "+e,n)}nr(e,a,n){this._is_bot()?t.rr("Refusing to render web experiment since the viewer is a likely bot"):a!=="control"?n.forEach((r=>{if(r.selector){var o;t.rr("applying transform of variant "+a+" for experiment "+e+" ",r);var i=(o=document)==null?void 0:o.querySelectorAll(r.selector);i?.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 Sa&&this._instance?kE(Sa,this._instance.config.custom_blocked_useragents):void 0}},X4=pt("[PostHog ExternalIntegrations]"),Y4={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},nb=class{constructor(e){this._instance=e}it(e,a){var n;(n=te.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,e,(r=>{if(r)return X4.error("failed to load script",r);a()}))}startIfEnabledOrStop(){var e=this,a=function(i){var s,l,u;!r||(s=te.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[i]||e.it(Y4[i],(()=>{var c;(c=te.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[i])==null||c.start(e._instance)})),!r&&(l=te.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[i]&&((u=te.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[i])==null||u.stop())};for(var[n,r]of Object.entries((o=this._instance.config.integrations)!==null&&o!==void 0?o:{})){var o;a(n)}}},rb="[SessionRecording]",Yu=pt(rb),Zp=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 Yu.error("started without valid sessionManager"),new Error(rb+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(rb+' cannot be used with cookieless_mode="always"')}get cr(){var e,a=!((e=this._instance.get_property(Ny))==null||!e.enabled),n=!this._instance.config.disable_session_recording,r=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return E&&a&&n&&!r}startIfEnabledOrStop(e){var a;if(!this.cr||(a=this.vr)==null||!a.isStarted){var n=!z(Object.assign)&&!z(Array.from);this.cr&&n?(this.gr(e),Yu.info("starting")):this.stopRecording()}}gr(e){var a,n,r;this.cr&&(te!=null&&(a=te.__PosthogExtensions__)!=null&&(a=a.rrweb)!=null&&a.record&&(n=te.__PosthogExtensions__)!=null&&n.initSessionRecording?this._r(e):(r=te.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.mr,(o=>{if(o)return Yu.error("could not load recorder",o);this._r(e)})))}stopRecording(){var e,a;(e=this.pr)==null||e.call(this),this.pr=void 0,(a=this.vr)==null||a.stop()}yr(){var e;(e=this._instance.persistence)==null||e.unregister(DA)}br(e){if(this._instance.persistence){var a,n,r=this._instance.persistence,o=()=>{var i=e.sessionRecording===!1?void 0:e.sessionRecording,s=i?.sampleRate,l=Te(s)?null:parseFloat(s);Te(l)&&this.yr();var u=i?.minimumDurationMilliseconds;r.register({[Ny]:Z({enabled:!!i},i,{networkPayloadCapture:Z({capturePerformance:e.capturePerformance},i?.networkPayloadCapture),canvasRecording:{enabled:i?.recordCanvas,fps:i?.canvasFps,quality:i?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:z(u)?null:u,endpoint:i?.endpoint,triggerMatchType:i?.triggerMatchType,masking:i?.masking,urlTriggers:i?.urlTriggers})})};o(),(a=this.pr)==null||a.call(this),this.pr=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(o)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.br(e),this.dr=!0,this.startIfEnabledOrStop()):this.dr=!0:Yu.info("skipping remote config with no sessionRecording",e)}log(e,a){var n;a===void 0&&(a="log"),(n=this.vr)!=null&&n.log?this.vr.log(e,a):Yu.warn("log called before recorder was ready")}get mr(){var e,a,n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(Ny);return(n==null||(a=n.scriptConfig)==null?void 0:a.script)||"lazy-recorder"}_r(e){var a,n;if((a=te.__PosthogExtensions__)==null||!a.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.vr||(this.vr=(n=te.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance),this.vr._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.vr.start(e)}onRRwebEmit(e){var a;(a=this.vr)==null||a.onRRwebEmit==null||a.onRRwebEmit(e)}overrideLinkedFlag(){var e,a;this.vr||(a=this._instance.persistence)==null||a.register({$replay_override_linked_flag:!0}),(e=this.vr)==null||e.overrideLinkedFlag()}overrideSampling(){var e,a;this.vr||(a=this._instance.persistence)==null||a.register({$replay_override_sampling:!0}),(e=this.vr)==null||e.overrideSampling()}overrideTrigger(e){var a,n;this.vr||(n=this._instance.persistence)==null||n.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(a=this.vr)==null||a.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.vr)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,a){var n;return!((n=this.vr)==null||!n.tryAddCustomEvent(e,a))}},ic={},ob=()=>{},qs="posthog",IE=!N4&&na?.indexOf("MSIE")===-1&&na?.indexOf("Mozilla")===-1,xA=t=>{var e;return Z({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:VN(q?.location),persistence:"localStorage+cookie",persistence_name:"",loaded:ob,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:ra&&ft(ra?.search)&&ra.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:(E==null||(e=E.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:a=>{var n="Bad HTTP status: "+a.statusCode+" "+a.text;$.error(n)},get_device_id:a=>a,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:Yx},error_tracking:{},_onCapture:ob,__preview_eager_load_replay:!1},(a=>({rageclick:!(a&&a>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(a&&a>="2025-05-24")||"history_change",session_recording:a&&a>="2025-11-30"?{strictMinimumDuration:!0}:{}}))(t))},bA=t=>{var e={};z(t.process_person)||(e.person_profiles=t.process_person),z(t.xhr_headers)||(e.request_headers=t.xhr_headers),z(t.cookie_name)||(e.persistence_name=t.cookie_name),z(t.disable_cookie)||(e.disable_persistence=t.disable_cookie),z(t.store_google)||(e.save_campaign_params=t.store_google),z(t.verbose)||(e.debug=t.verbose);var a=at({},e,t);return Oe(t.property_blacklist)&&(z(t.property_denylist)?a.property_denylist=t.property_blacklist:Oe(t.property_denylist)?a.property_denylist=[...t.property_blacklist,...t.property_denylist]:$.error("Invalid value for property_denylist config: "+t.property_denylist)),a},ib=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}},Wp=class t{get decideEndpointWasHit(){var e,a;return(e=(a=this.featureFlags)==null?void 0:a.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,a;return(e=(a=this.featureFlags)==null?void 0:a.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new ib,this.Sr=!1,this.version=sr.LIB_VERSION,this.Er=new fc,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=xA(),this.SentryIntegration=Ex,this.sentryIntegration=e=>(function(a,n){var r=XA(a,n);return{name:WA,processEvent:o=>r(o)}})(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 $x(this),this.toolbar=new Tx(this),this.scrollManager=new Jx(this),this.pageViewManager=new Fx(this),this.surveys=new Zx(this),this.experiments=new ab(this),this.exceptions=new qx(this),this.rateLimiter=new Wx(this),this.requestRouter=new tb(this),this.consent=new kx(this),this.externalIntegrations=new nb(this),this.people={set:(e,a,n)=>{var r=ft(e)?{[e]:a}:e;this.setPersonProperties(r),n?.({})},set_once:(e,a,n)=>{var r=ft(e)?{[e]:a}:e;this.setPersonProperties(void 0,r),n?.({})}},this.on("eventCaptured",(e=>$.info('send "'+e?.event+'"',e)))}init(e,a,n){if(n&&n!==qs){var r,o=(r=ic[n])!==null&&r!==void 0?r:new t;return o._init(e,a,n),ic[n]=o,ic[qs][n]=o,o}return this._init(e,a,n)}_init(e,a,n){var r;if(a===void 0&&(a={}),z(e)||ex(e))return $.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},a.debug=this.Rr(a.debug),this.Ir=a,this.Fr=[],a.person_profiles&&(this.Pr=a.person_profiles),this.set_config(at({},xA(a.defaults),bA(a),{name:n,token:e})),this.config.on_xhr_error&&$.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=a.disable_compression?void 0:cr.GZipJS;var o=this.Cr();this.persistence=new oc(this.config,o),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new oc(Z({},this.config,{persistence:"sessionStorage"}),o);var i=Z({},this.persistence.props),s=Z({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Mr=new Kx((g=>this.Or(g)),this.config.request_queue_config),this.Ar=new Qx(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 Gp(this),this.sessionPropsManager=new jp(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)),sr.DEBUG=sr.DEBUG||this.config.debug,sr.DEBUG&&$.info("Starting in debug mode",{this:this,config:a,thisC:Z({},this.config),p:i,s}),((r=a.bootstrap)==null?void 0:r.distinctID)!==void 0){var u,c,d=this.config.get_device_id(ho()),f=(u=a.bootstrap)!=null&&u.isIdentifiedID?d:a.bootstrap.distinctID;this.persistence.set_property(lr,(c=a.bootstrap)!=null&&c.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:a.bootstrap.distinctID,$device_id:f})}if(this.jr()){var h,S,x=Object.keys(((h=a.bootstrap)==null?void 0:h.featureFlags)||{}).filter((g=>{var v;return!((v=a.bootstrap)==null||(v=v.featureFlags)==null||!v[g])})).reduce(((g,v)=>{var y;return g[v]=((y=a.bootstrap)==null||(y=y.featureFlags)==null?void 0:y[v])||!1,g}),{}),b=Object.keys(((S=a.bootstrap)==null?void 0:S.featureFlagPayloads)||{}).filter((g=>x[g])).reduce(((g,v)=>{var y,_;return(y=a.bootstrap)!=null&&(y=y.featureFlagPayloads)!=null&&y[v]&&(g[v]=(_=a.bootstrap)==null||(_=_.featureFlagPayloads)==null?void 0:_[v]),g}),{});this.featureFlags.receivedFeatureFlags({featureFlags:x,featureFlagPayloads:b})}if(l)this.register_once({distinct_id:qu,$device_id:null},"");else if(!this.get_distinct_id()){var m=this.config.get_device_id(ho());this.register_once({distinct_id:m,$device_id:m},""),this.persistence.set_property(lr,"anonymous")}return lt(E,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),a.segment?f4(this,(()=>this.Lr())):this.Lr(),mo(this.config._onCapture)&&this.config._onCapture!==ob&&($.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(g=>this.config._onCapture(g.event,g)))),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 a=performance.now();this.historyAutocapture=new Ax(this),this.historyAutocapture.startIfEnabled();var n=[];n.push((()=>{new Rx(this).startIfEnabledOrStop()})),n.push((()=>{var r;this.siteApps=new eb(this),(r=this.siteApps)==null||r.init()})),e||n.push((()=>{this.sessionRecording=new Zp(this),this.sessionRecording.startIfEnabledOrStop()})),this.config.disable_scroll_properties||n.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),n.push((()=>{this.autocapture=new Cx(this),this.autocapture.startIfEnabled()})),n.push((()=>{this.surveys.loadIfEnabled()})),n.push((()=>{this.heatmaps=new Px(this),this.heatmaps.startIfEnabled()})),n.push((()=>{this.webVitalsAutocapture=new Bx(this)})),n.push((()=>{this.exceptionObserver=new Ix(this),this.exceptionObserver.startIfEnabled()})),n.push((()=>{this.deadClicksAutocapture=new Hp(this,d4),this.deadClicksAutocapture.startIfEnabled()})),n.push((()=>{if(this.Nr){var r=this.Nr;this.Nr=void 0,this.fi(r)}})),this.Ur(n,a)}Ur(e,a){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-a>=30&&e.length>0)return void setTimeout((()=>{this.Ur(e,a)}),0);var n=e.shift();if(n)try{n()}catch(o){$.error("Error initializing extension:",o)}}var r=Math.round(performance.now()-a);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:r}),this.config.__preview_deferred_init_extensions&&$.info("PostHog extensions initialized ("+r+"ms)")}fi(e){var a,n,r,o,i,s,l,u;if(!q||!q.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=pe(e.supportedCompression,cr.GZipJS)?cr.GZipJS:pe(e.supportedCompression,cr.Base64)?cr.Base64:void 0),(a=e.analytics)!=null&&a.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Pr?this.Pr:"identified_only"}),(n=this.siteApps)==null||n.onRemoteConfig(e),(r=this.sessionRecording)==null||r.onRemoteConfig(e),(o=this.autocapture)==null||o.onRemoteConfig(e),(i=this.heatmaps)==null||i.onRemoteConfig(e),this.surveys.onRemoteConfig(e),(s=this.webVitalsAutocapture)==null||s.onRemoteConfig(e),(l=this.exceptionObserver)==null||l.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(u=this.deadClicksAutocapture)==null||u.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 Xx(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()&&vo(this.__request_queue,(e=>this.Or(e))),this.__request_queue=[],this.zr()}_handle_unload(){var e,a;this.config.request_batching?(this.Br()&&this.capture("$pageleave"),(e=this.Mr)==null||e.unload(),(a=this.Ar)==null||a.unload()):this.Br()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}ci(e){this.__loaded&&(IE?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=$p(e.url,{ip:this.config.ip?1:0}),e.headers=Z({},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,(a=>{var n,r,o,i=Z({},a);i.timeout=i.timeout||6e4,i.url=$p(i.url,{_:new Date().getTime().toString(),ver:sr.LIB_VERSION,compression:i.compression});var s=(n=i.transport)!==null&&n!==void 0?n:"fetch",l=kp.filter((c=>!i.disableTransport||!c.transport||!i.disableTransport.includes(c.transport))),u=(r=(o=TA(l,(c=>c.transport===s)))==null?void 0:o.method)!==null&&r!==void 0?r:l[0].method;if(!u)throw new Error("No available transport method");u(i)})(Z({},e,{callback:a=>{var n,r;this.rateLimiter.checkForLimiting(a),a.statusCode>=400&&((n=(r=this.config).on_request_error)==null||n.call(r,a)),e.callback==null||e.callback(a)}}))))}Or(e){this.Ar?this.Ar.retriableRequest(e):this.ci(e)}_execute_array(e){var a,n=[],r=[],o=[];vo(e,(s=>{s&&(a=s[0],Oe(a)?o.push(s):mo(s)?s.call(this):Oe(s)&&a==="alias"?n.push(s):Oe(s)&&a.indexOf("capture")!==-1&&mo(this[a])?o.push(s):r.push(s))}));var i=function(s,l){vo(s,(function(u){if(Oe(u[0])){var c=l;Pe(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else this[u[0]].apply(this,u.slice(1))}),l)};i(n,this),i(r,this),i(o,this)}jr(){var e,a;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((a=this.config.bootstrap)==null?void 0:a.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,a,n){var r;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Mr){if(this.is_capturing())if(!z(e)&&ft(e)){var o=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(o&&!this.config.__preview_capture_bot_pageviews)){var i=n!=null&&n.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(i==null||!i.isRateLimited){a!=null&&a.$current_url&&!ft(a?.$current_url)&&($.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),a==null||delete a.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var s=new Date,l=n?.timestamp||s,u=ho(),c={uuid:u,event:e,properties:this.calculateEventProperties(e,a||{},l,u)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&o&&(c.event="$bot_pageview",c.properties.$browser_type="bot"),i&&(c.properties.$lib_rate_limit_remaining_tokens=i.remainingTokens),n?.$set&&(c.$set=n?.$set);var d,f=this.qr(n?.$set_once);if(f&&(c.$set_once=f),(c=qN(c,n!=null&&n._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,z(n?.timestamp)||(c.properties.$event_time_override_provided=!0,c.properties.$event_time_override_system_time=s),e===Ip.DISMISSED||e===Ip.SENT){var h=a?.[mA.SURVEY_ID],S=a?.[mA.SURVEY_ITERATION];d={id:h,current_iteration:S},localStorage.getItem(gA(d))||localStorage.setItem(gA(d),"true"),c.$set=Z({},c.$set,{[q4({id:h,current_iteration:S},e===Ip.SENT?"responded":"dismissed")]:!0})}var x=Z({},c.properties.$set,c.$set);if($s(x)||this.setPersonPropertiesForFlags(x),!Te(this.config.before_send)){var b=this.Wr(c);if(!b)return;c=b}this.Er.emit("eventCaptured",c);var m={method:"POST",url:(r=n?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:c,compression:"best-available",batchKey:n?._batchKey};return!this.config.request_batching||n&&(n==null||!n._batchKey)||n!=null&&n.send_instantly?this.Or(m):this.Mr.enqueue(m),c}$.critical("This capture call is ignored due to client rate limiting.")}}else $.error("No event name provided to posthog.capture")}else $.uninitializedWarning("posthog.capture")}Ai(e){return this.on("eventCaptured",(a=>e(a.event,a)))}calculateEventProperties(e,a,n,r,o){if(n=n||new Date,!this.persistence||!this.sessionPersistence)return a;var i=o?void 0:this.persistence.remove_event_timer(e),s=Z({},a);if(s.token=this.config.token,s.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(s.$cookieless_mode=!0),e==="$snapshot"){var l=Z({},this.persistence.properties(),this.sessionPersistence.properties());return s.distinct_id=l.distinct_id,(!ft(s.distinct_id)&&!_n(s.distinct_id)||ex(s.distinct_id))&&$.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),s}var u,c=A4(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:d,windowId:f}=this.sessionManager.checkAndGetSessionAndWindowId(o,n.getTime());s.$session_id=d,s.$window_id=f}this.sessionPropsManager&&at(s,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&at(s,this.sessionRecording.sdkDebugProperties),s.$sdk_debug_retry_queue_size=(h=this.Ar)==null?void 0:h.length}catch(m){s.$sdk_debug_error_capturing_properties=String(m)}if(this.requestRouter.region===nc.CUSTOM&&(s.$lib_custom_api_host=this.config.api_host),u=e!=="$pageview"||o?e!=="$pageleave"||o?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(n):this.pageViewManager.doPageView(n,r),s=at(s,u),e==="$pageview"&&q&&(s.title=q.title),!z(i)){var S=n.getTime()-i;s.$duration=parseFloat((S/1e3).toFixed(3))}na&&this.config.opt_out_useragent_filter&&(s.$browser_type=this._is_bot()?"bot":"browser"),(s=at({},c,this.persistence.properties(),this.sessionPersistence.properties(),s)).$is_identified=this._isIdentified(),Oe(this.config.property_denylist)?Pe(this.config.property_denylist,(function(m){delete s[m]})):$.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var x=this.config.sanitize_properties;x&&($.error("sanitize_properties is deprecated. Use before_send instead"),s=x(s,e));var b=this.Gr();return s.$process_person_profile=b,b&&!o&&this.Vr("_calculate_event_properties"),s}qr(e){var a;if(!this.persistence||!this.Gr()||this.Sr)return e;var n=this.persistence.get_initial_props(),r=(a=this.sessionPropsManager)==null?void 0:a.getSetOnceProps(),o=at({},n,r||{},e||{}),i=this.config.sanitize_properties;return i&&($.error("sanitize_properties is deprecated. Use before_send instead"),o=i(o,"$set_once")),this.Sr=!0,$s(o)?void 0:o}register(e,a){var n;(n=this.persistence)==null||n.register(e,a)}register_once(e,a,n){var r;(r=this.persistence)==null||r.register_once(e,a,n)}register_for_session(e){var a;(a=this.sessionPersistence)==null||a.register(e)}unregister(e){var a;(a=this.persistence)==null||a.unregister(e)}unregister_for_session(e){var a;(a=this.sessionPersistence)==null||a.unregister(e)}Jr(e,a){this.register({[e]:a})}getFeatureFlag(e,a){return this.featureFlags.getFeatureFlag(e,a)}getFeatureFlagPayload(e){var a=this.featureFlags.getFeatureFlagPayload(e);try{return JSON.parse(a)}catch{return a}}isFeatureEnabled(e,a){return this.featureFlags.isFeatureEnabled(e,a)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateEarlyAccessFeatureEnrollment(e,a,n){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,a,n)}getEarlyAccessFeatures(e,a,n){return a===void 0&&(a=!1),this.featureFlags.getEarlyAccessFeatures(e,a,n)}on(e,a){return this.Er.on(e,a)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var a,n;return(a=(n=this.sessionManager)==null?void 0:n.onSessionId(e))!==null&&a!==void 0?a:()=>{}}getSurveys(e,a){a===void 0&&(a=!1),this.surveys.getSurveys(e,a)}getActiveMatchingSurveys(e,a){a===void 0&&(a=!1),this.surveys.getActiveMatchingSurveys(e,a)}renderSurvey(e,a){this.surveys.renderSurvey(e,a)}displaySurvey(e,a){a===void 0&&(a=V4),this.surveys.displaySurvey(e,a)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,a){return a===void 0&&(a=!1),this.surveys.canRenderSurveyAsync(e,a)}identify(e,a,n){if(!this.__loaded||!this.persistence)return $.uninitializedWarning("posthog.identify");if(_n(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!==qu){if(this.Vr("posthog.identify")){var r=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var o=r;this.register_once({$had_persisted_distinct_id:!0,$device_id:o},"")}e!==r&&e!==this.get_property(Ku)&&(this.unregister(Ku),this.register({distinct_id:e}));var i=(this.persistence.get_property(lr)||"anonymous")==="anonymous";e!==r&&i?(this.persistence.set_property(lr,"identified"),this.setPersonPropertiesForFlags(Z({},n||{},a||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:r},{$set:a||{},$set_once:n||{}}),this.Tr=cA(e,a,n),this.featureFlags.setAnonymousDistinctId(r)):(a||n)&&this.setPersonProperties(a,n),e!==r&&(this.reloadFeatureFlags(),this.unregister(Rp))}}else $.critical('The string "'+qu+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else $.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,a){if((e||a)&&this.Vr("posthog.setPersonProperties")){var n=cA(this.get_distinct_id(),e,a);this.Tr!==n?(this.setPersonPropertiesForFlags(Z({},a||{},e||{})),this.capture("$set",{$set:e||{},$set_once:a||{}}),this.Tr=n):$.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,a,n){if(e&&a){if(this.Vr("posthog.group")){var r=this.getGroups();r[e]!==a&&this.resetGroupPropertiesForFlags(e),this.register({$groups:Z({},r,{[e]:a})}),n&&(this.capture("$groupidentify",{$group_type:e,$group_key:a,$group_set:n}),this.setGroupPropertiesForFlags({[e]:n})),r[e]===a||n||this.reloadFeatureFlags()}}else $.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,a){a===void 0&&(a=!0),this.featureFlags.setPersonPropertiesForFlags(e,a)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,a){a===void 0&&(a=!0),this.Vr("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,a)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var a,n,r,o;if($.info("reset"),!this.__loaded)return $.uninitializedWarning("posthog.reset");var i=this.get_property("$device_id");if(this.consent.reset(),(a=this.persistence)==null||a.clear(),(n=this.sessionPersistence)==null||n.clear(),this.surveys.reset(),this.featureFlags.reset(),(r=this.persistence)==null||r.set_property(lr,"anonymous"),(o=this.sessionManager)==null||o.resetSessionId(),this.Tr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:qu,$device_id:null},"");else{var s=this.config.get_device_id(ho());this.register_once({distinct_id:s,$device_id:e?s:i},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,a;return(e=(a=this.sessionManager)==null?void 0:a.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:a,sessionStartTimestamp:n}=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+a);if(e!=null&&e.withTimestamp&&n){var o,i=(o=e.timestampLookBack)!==null&&o!==void 0?o:10;if(!n)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-n)/1e3)-i,0)}return r}alias(e,a){return e===this.get_property(RA)?($.critical("Attempting to create alias for existing People user - aborting."),-2):this.Vr("posthog.alias")?(z(a)&&(a=this.get_distinct_id()),e!==a?(this.Jr(Ku,e),this.capture("$create_alias",{alias:e,distinct_id:a})):($.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var a=Z({},this.config);if(yt(e)){var n,r,o,i,s;at(this.config,bA(e));var l=this.Cr();(n=this.persistence)==null||n.update_config(this.config,a,l),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new oc(Z({},this.config,{persistence:"sessionStorage"}),l);var u=this.Rr(this.config.debug);go(u)&&(this.config.debug=u),go(this.config.debug)&&(this.config.debug?(sr.DEBUG=!0,Xe.H()&&Xe.G("ph_debug","true"),$.info("set_config",{config:e,oldConfig:a,newConfig:Z({},this.config)})):(sr.DEBUG=!1,Xe.H()&&Xe.V("ph_debug"))),(r=this.sessionRecording)==null||r.startIfEnabledOrStop(),(o=this.autocapture)==null||o.startIfEnabled(),(i=this.heatmaps)==null||i.startIfEnabled(),this.surveys.loadIfEnabled(),this.Kr(),(s=this.externalIntegrations)==null||s.startIfEnabledOrStop()}}startSessionRecording(e){var a=e===!0,n={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};if(Object.values(n).some(Boolean)){var r,o,i,s,l;(r=this.sessionManager)==null||r.checkAndGetSessionAndWindowId(),n.sampling&&((o=this.sessionRecording)==null||o.overrideSampling()),n.linked_flag&&((i=this.sessionRecording)==null||i.overrideLinkedFlag()),n.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),n.event_trigger&&((l=this.sessionRecording)==null||l.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,a){var n=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:n});return this.exceptions.sendExceptionEvent(Z({},r,a))}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var a;return(a=this.persistence)==null?void 0:a.props[e]}getSessionProperty(e){var a;return(a=this.sessionPersistence)==null?void 0:a.props[e]}toString(){var e,a=(e=this.config.name)!==null&&e!==void 0?e:qs;return a!==qs&&(a=qs+"."+a),a}_isIdentified(){var e,a;return((e=this.persistence)==null?void 0:e.get_property(lr))==="identified"||((a=this.sessionPersistence)==null?void 0:a.get_property(lr))==="identified"}Gr(){var e,a;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&$s(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Ku])&&((a=this.persistence)==null||(a=a.props)==null||!a[Dp]))}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(Dp,!0),!0)}Cr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),a=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!a}Kr(){var e,a,n,r,o=this.Cr();return((e=this.persistence)==null?void 0:e.wi)!==o&&((n=this.persistence)==null||n.set_disabled(o)),((a=this.sessionPersistence)==null?void 0:a.wi)!==o&&((r=this.sessionPersistence)==null||r.set_disabled(o)),o}opt_in_capturing(e){var a;if(this.config.cookieless_mode!=="always"){var n,r;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(n=this.sessionManager)==null||n.destroy(),this.sessionManager=new Gp(this),this.persistence&&(this.sessionPropsManager=new jp(this,this.sessionManager,this.persistence)),this.sessionRecording=new Zp(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.Kr(),this.zr(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(z(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,a;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:qu,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(a=this.sessionRecording)==null||a.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===ur.GRANTED?"granted":e===ur.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 Sa?kE(Sa,this.config.custom_blocked_useragents):void 0}Hr(){q&&(q.visibilityState==="visible"?this.$r||(this.$r=!0,this.capture("$pageview",{title:q.title},{send_instantly:!0}),this.kr&&(q.removeEventListener("visibilitychange",this.kr),this.kr=null)):this.kr||(this.kr=this.Hr.bind(this),lt(q,"visibilitychange",this.kr)))}debug(e){e===!1?(E?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(E?.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,a,n,r,o,i,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):(n="advanced_disable_decide",r=!1,o=$,i=(a="advanced_disable_flags")in(e=l)&&!z(e[a]),s=n in e&&!z(e[n]),i?e[a]:s?(o&&o.warn("Config field '"+n+"' is deprecated. Please use '"+a+"' instead. The old field will be removed in a future major version."),e[n]):r)}Wr(e){if(Te(this.config.before_send))return e;var a=Oe(this.config.before_send)?this.config.before_send:[this.config.before_send],n=e;for(var r of a){if(n=r(n),Te(n)){var o="Event '"+e.event+"' was rejected in beforeSend function";return LN(e.event)?$.warn(o+". This can cause unexpected behavior."):$.info(o),null}n.properties&&!$s(n.properties)||$.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return n}getPageViewId(){var e;return(e=this.pageViewManager.Vt)==null?void 0:e.pageViewId}captureTraceFeedback(e,a){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:a})}captureTraceMetric(e,a,n){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:a,$ai_metric_value:String(n)})}Rr(e){var a=go(e)&&!e,n=Xe.H()&&Xe.q("ph_debug")==="true";return!a&&(!!n||e)}};(function(t,e){for(var a=0;a<e.length;a++)t.prototype[e[a]]=zN(t.prototype[e[a]])})(Wp,["identify"]);var SA,AE=(SA=ic[qs]=new Wp,(function(){function t(){t.done||(t.done=!0,IE=!1,Pe(ic,(function(e){e._dom_loaded()})))}q!=null&&q.addEventListener?q.readyState==="complete"?t():lt(q,"DOMContentLoaded",t,{capture:!1}):E&&$.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),SA);var vb=class{constructor(e={}){this.options=e;B(this,"client");B(this,"featureFlagsCallback");B(this,"captureCallback");B(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 a=e.consent;a.getStatus()==="granted"&&this.initPostHog(),this.consentUnsub=a.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 a=e.enableFeatureFlags??!0,n=`syntro_${e.apiKey.slice(-6)||"sdk"}`;this.client=AE.init(e.apiKey,{api_host:e.apiHost??"https://telemetry.syntrologie.com",advanced_disable_feature_flags:!a,advanced_disable_feature_flags_on_first_load:!a,autocapture:e.autocapture??!0,capture_pageview:e.capturePageview??!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(a&&this.featureFlagsCallback){r.onFeatureFlags(()=>{let i=this.getAllFeatureFlags();i&&this.featureFlagsCallback&&this.featureFlagsCallback(i)});let o=this.getAllFeatureFlags();o&&Object.keys(o).length>0&&this.featureFlagsCallback(o)}this.captureCallback&&r.on("eventCaptured",o=>{let i=typeof o=="string"?o:o?.event,s=typeof o=="string"?void 0:o?.properties;typeof i=="string"&&this.captureCallback?.(i,s)})}},n)}getAllFeatureFlags(){return this.client?.featureFlags?.getFlagVariants?.()}getSegmentFlags(){let e=this.getAllFeatureFlags();if(!e)return{};let a={};for(let[n,r]of Object.entries(e))n.startsWith("in_segment_")&&(a[n]=r===!0);return a}identify(e,a){this.client?.identify(e,a)}alias(e,a){this.client?.alias(e,a)}track(e,a){this.client?.capture(e,a)}trackCanvasOpened(e){this.track("shadow_canvas_opened",{surface:e})}trackCanvasClosed(e){this.track("shadow_canvas_closed",{surface:e})}trackRectangleViewed(e,a){this.track("shadow_canvas_rectangle_viewed",{rectangleId:e,surface:a})}trackAction(e,a,n){this.track("shadow_canvas_action",{action:e,rectangleId:a,surface:n})}register(e){this.client?.register?.(e)}getSessionId(){return this.client?.get_session_id?.()}startSessionRecording(){this.client?.startSessionRecording?.()}trackExperiment(e,a,n){let r=`$experiment_${e}`;this.register({[r]:n??`variation_${a}`,[`${r}_id`]:a}),this.track("$experiment_started",{$experiment_key:e,$experiment_variation_id:a,$experiment_variation_name:n??`variation_${a}`})}setPersonProperties(e){this.client?.capture("$set",{$set:e})}setPersonPropertiesOnce(e){this.client?.capture("$set",{$set_once:e})}getDistinctId(){return this.client?.get_distinct_id?.()}};function yb(t={}){return new vb(t)}var xb=async(t,e)=>{let a=[];if(e.applyAction)for(let n of t.actions){let r=await e.applyAction(n);a.push(r)}return{cleanup:async()=>{for(let n=a.length-1;n>=0;n--)try{await a[n].revert()}catch{}}}},bb=async(t,e)=>{let a=[];if(e.applyAction){let n=t.actions.map(r=>e.applyAction(r));if(t.waitFor==="any"){let r=await Promise.race(n);a.push(r);let o=await Promise.allSettled(n);for(let i of o)i.status==="fulfilled"&&i.value!==r&&a.push(i.value)}else{let r=await Promise.all(n);a.push(...r)}}return{cleanup:async()=>{for(let n of a)try{await n.revert()}catch{}}}},Sb=async(t,e)=>{let a,n,r=!1,o={cleanup:()=>{r=!0,n&&clearTimeout(n),a&&a()}};return t.event&&e.subscribeEvent?await new Promise(i=>{a=e.subscribeEvent(t.event,()=>{r||i()}),t.durationMs!==void 0&&(n=setTimeout(()=>{r||i()},t.durationMs))}):t.durationMs!==void 0&&await new Promise(i=>{n=setTimeout(()=>{r||i()},t.durationMs)}),o};var Qp=class{constructor(){B(this,"executors",new Map);for(let{kind:e,executor:a}of ev)this.registerCore(e,a);for(let{kind:e,executor:a}of fv)this.registerCore(e,a);this.registerCore("core:mountWidget",async()=>{throw new Error("core:mountWidget must be handled by ActionEngine")}),this.registerCore("core:sequence",xb),this.registerCore("core:parallel",bb),this.registerCore("core:wait",Sb)}registerCore(e,a,n){this.executors.set(e,{kind:e,executor:a,schema:n,source:"core",isBuiltIn:!0})}register(e,a,n,r="custom",o=!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:a,schema:n,source:r,isBuiltIn:o})}unregister(e){let a=this.executors.get(e);return a?a.isBuiltIn?(console.warn(`[ExecutorRegistry] Cannot unregister built-in executor: ${e}`),!1):(this.executors.delete(e),!0):!1}unregisterBySource(e){for(let[a,n]of this.executors.entries())n.source===e&&this.executors.delete(a)}get(e){return this.executors.get(e)?.executor}getRegistration(e){return this.executors.get(e)}has(e){return this.executors.has(e)}validate(e){let a=[];if(!e||typeof e!="object")return a.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:a,warnings:[]};let{kind:n}=e;if(!n||typeof n!="string")return a.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:a,warnings:[]};let r=this.executors.get(n);if(!r)return a.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${n}`,field:"kind"}),{valid:!1,errors:a,warnings:[]};if(r.schema){let o=r.schema.safeParse(e);if(!o.success){for(let i of o.error.issues)a.push({code:"SCHEMA_VALIDATION_ERROR",message:i.message,field:i.path.join(".")});return{valid:!1,errors:a,warnings:[]}}}return{valid:!0,errors:[],warnings:[]}}list(){return Array.from(this.executors.keys())}listRegistrations(){return Array.from(this.executors.values())}getBuiltInKinds(){return Array.from(this.executors.entries()).filter(([,e])=>e.isBuiltIn).map(([e])=>e)}getCustomKinds(){return Array.from(this.executors.entries()).filter(([,e])=>!e.isBuiltIn).map(([e])=>e)}},fr=new Qp;function K4(t){return fr.get(t)}function Cb(t){return fr.has(t)}var Q4=new Set(["onclick","onerror","onload","onmouseover","onfocus","onblur","onchange","onsubmit","onkeydown","onkeyup","onkeypress"]),EE=5e4,TE=50;function bo(t){let e=[],a=[];if(!t||typeof t!="object")return e.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:e,warnings:a};let{kind:n}=t;if(!n||typeof n!="string")return e.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:e,warnings:a};if(!Cb(n)&&n!=="core:mountWidget"){let r=fr.list();return console.error(`[ActionValidation] Unknown action kind: "${n}". Registered kinds (${r.length}): [${r.join(", ")}]. This usually means the app that provides "${n}" hasn't been activated yet, or the executor was never registered in ExecutorRegistry.`),e.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${n}`,field:"kind"}),{valid:!1,errors:e,warnings:a}}switch(n){case"overlays:highlight":case"overlays:pulse":case"navigation:scrollTo":xo(t,e,a);break;case"overlays:badge":xo(t,e,a),J4(t,e,a);break;case"overlays:tooltip":xo(t,e,a),e3(t,e,a);break;case"overlays:modal":d3(t,e,a);break;case"content:insertHtml":xo(t,e,a),t3(t,e,a);break;case"content:setText":xo(t,e,a),a3(t,e,a);break;case"content:setAttr":xo(t,e,a),n3(t,e,a);break;case"content:addClass":case"content:removeClass":xo(t,e,a),r3(t,e,a);break;case"content:setStyle":xo(t,e,a),o3(t,e,a);break;case"core:mountWidget":i3(t,e,a);break;case"core:wait":s3(t,e,a);break;case"core:sequence":l3(t,e,a);break;case"core:parallel":u3(t,e,a);break;case"core:tour":f3(t,e,a);break;case"navigation:navigate":c3(t,e,a);break}return{valid:e.length===0,errors:e,warnings:a}}function xo(t,e,a){let n=t.anchorId;if(!n||typeof n!="object"){e.push({code:"MISSING_ANCHOR_ID",message:"Action requires an 'anchorId' object with a 'selector' string",field:"anchorId"});return}if(!n.selector||typeof n.selector!="string"?e.push({code:"MISSING_ANCHOR_SELECTOR",message:"anchorId requires a 'selector' string",field:"anchorId.selector"}):n.selector.length>200&&a.push({code:"LONG_ANCHOR_ID",message:"Anchor selector is unusually long",suggestion:"Consider using a shorter, more descriptive selector"}),n.route===void 0||n.route===null)e.push({code:"MISSING_ANCHOR_ROUTE",message:`anchorId requires a 'route' (string or array of strings). Use "**" for all routes.`,field:"anchorId.route"});else{let r=Array.isArray(n.route)?n.route:[n.route];for(let o of r)if(typeof o!="string"){e.push({code:"INVALID_ANCHOR_ROUTE",message:"anchorId.route must be a string or array of strings",field:"anchorId.route"});break}}}function J4(t,e,a){!t.content||typeof t.content!="string"?e.push({code:"MISSING_CONTENT",message:"Badge action requires 'content' property",field:"content"}):t.content.length>100&&a.push({code:"LONG_BADGE_CONTENT",message:"Badge content is quite long",suggestion:"Keep badge content short (under 100 characters)"})}function e3(t,e,a){if(!t.content||typeof t.content!="object"){e.push({code:"MISSING_CONTENT",message:"Tooltip action requires 'content' object",field:"content"});return}(!t.content.body||typeof t.content.body!="string")&&e.push({code:"MISSING_BODY",message:"Tooltip content requires 'body' property",field:"content.body"})}function t3(t,e,a){!t.html||typeof t.html!="string"?e.push({code:"MISSING_HTML",message:"insertHtml action requires 'html' property",field:"html"}):t.html.length>EE&&e.push({code:"HTML_TOO_LONG",message:`HTML content exceeds maximum length of ${EE}`,field:"html"});let n=["before","after","prepend","append","replace"];(!t.position||!n.includes(t.position))&&e.push({code:"INVALID_POSITION",message:`Position must be one of: ${n.join(", ")}`,field:"position"})}function a3(t,e,a){(t.text===void 0||t.text===null)&&e.push({code:"MISSING_TEXT",message:"setText action requires 'text' property",field:"text"})}function n3(t,e,a){!t.attr||typeof t.attr!="string"?e.push({code:"MISSING_ATTR",message:"setAttr action requires 'attr' property",field:"attr"}):(Q4.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 r3(t,e,a){!t.className||typeof t.className!="string"?e.push({code:"MISSING_CLASS_NAME",message:"Class action requires 'className' property",field:"className"}):/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t.className)||a.push({code:"INVALID_CLASS_NAME",message:"Class name contains unusual characters",suggestion:"Use alphanumeric characters, hyphens, and underscores"})}function o3(t,e,a){if(!t.styles||typeof t.styles!="object")e.push({code:"MISSING_STYLES",message:"setStyle action requires 'styles' object",field:"styles"});else{let n=Object.keys(t.styles).length;n>TE&&e.push({code:"TOO_MANY_STYLES",message:`Too many styles (${n}). Maximum is ${TE}`,field:"styles"});for(let[r,o]of Object.entries(t.styles))typeof o=="string"&&o.includes("expression(")&&e.push({code:"DANGEROUS_STYLE",message:`Style expressions are not allowed: ${r}`,field:`styles.${r}`})}}function i3(t,e,a){(!t.slot||typeof t.slot!="string")&&e.push({code:"MISSING_SLOT",message:"mountWidget action requires 'slot' property",field:"slot"}),!t.widget||typeof t.widget!="object"?e.push({code:"MISSING_WIDGET",message:"mountWidget action requires 'widget' object",field:"widget"}):(!t.widget.widgetId||typeof t.widget.widgetId!="string")&&e.push({code:"MISSING_WIDGET_ID",message:"Widget must have a 'widgetId' property",field:"widget.widgetId"})}function s3(t,e,a){t.durationMs===void 0&&!t.event&&e.push({code:"MISSING_WAIT_CONFIG",message:"wait action requires either 'durationMs' or 'event' property"}),t.durationMs!==void 0&&t.durationMs<0&&e.push({code:"INVALID_DURATION",message:"durationMs must be a positive number",field:"durationMs"}),t.event!==void 0&&typeof t.event!="string"&&e.push({code:"INVALID_EVENT",message:"event must be a string",field:"event"})}function l3(t,e,a){if(!t.actions||!Array.isArray(t.actions)){e.push({code:"MISSING_ACTIONS",message:"sequence action requires 'actions' array",field:"actions"});return}t.actions.length===0&&a.push({code:"EMPTY_SEQUENCE",message:"sequence has no actions",suggestion:"Add at least one action to the sequence"});for(let n=0;n<t.actions.length;n++){let r=bo(t.actions[n]);for(let o of r.errors)e.push({...o,field:`actions[${n}]${o.field?`.${o.field}`:""}`});for(let o of r.warnings)a.push(o)}}function u3(t,e,a){if(!t.actions||!Array.isArray(t.actions)){e.push({code:"MISSING_ACTIONS",message:"parallel action requires 'actions' array",field:"actions"});return}t.actions.length===0&&a.push({code:"EMPTY_PARALLEL",message:"parallel has no actions",suggestion:"Add at least one action to the parallel group"}),t.waitFor&&!["all","any"].includes(t.waitFor)&&e.push({code:"INVALID_WAIT_FOR",message:"waitFor must be 'all' or 'any'",field:"waitFor"});for(let n=0;n<t.actions.length;n++){let r=bo(t.actions[n]);for(let o of r.errors)e.push({...o,field:`actions[${n}]${o.field?`.${o.field}`:""}`});for(let o of r.warnings)a.push(o)}}function c3(t,e,a){if(!t.url||typeof t.url!="string")e.push({code:"MISSING_URL",message:"navigate action requires 'url' property",field:"url"});else{let n=t.url.trim().toLowerCase();n.startsWith("javascript:")&&e.push({code:"DANGEROUS_URL",message:"javascript: URLs are not allowed",field:"url"}),n.startsWith("data:")&&a.push({code:"DATA_URL",message:"data: URLs may have limited support",suggestion:"Consider using a regular URL instead"})}}function d3(t,e,a){if(!t.content||typeof t.content!="object"){e.push({code:"MISSING_CONTENT",message:"Modal action requires 'content' object",field:"content"});return}if((!t.content.body||typeof t.content.body!="string")&&e.push({code:"MISSING_BODY",message:"Modal content requires 'body' property",field:"content.body"}),t.size&&!["sm","md","lg"].includes(t.size)&&e.push({code:"INVALID_SIZE",message:"Modal size must be 'sm', 'md', or 'lg'",field:"size"}),t.ctaButtons)if(!Array.isArray(t.ctaButtons))e.push({code:"INVALID_CTA_BUTTONS",message:"ctaButtons must be an array",field:"ctaButtons"});else for(let n=0;n<t.ctaButtons.length;n++){let r=t.ctaButtons[n];(!r.label||typeof r.label!="string")&&e.push({code:"MISSING_BUTTON_LABEL",message:`CTA button at index ${n} requires 'label' property`,field:`ctaButtons[${n}].label`}),(!r.actionId||typeof r.actionId!="string")&&e.push({code:"MISSING_BUTTON_ACTION_ID",message:`CTA button at index ${n} requires 'actionId' property`,field:`ctaButtons[${n}].actionId`})}}function f3(t,e,a){if((!t.tourId||typeof t.tourId!="string")&&e.push({code:"MISSING_TOUR_ID",message:"Tour action requires 'tourId' property",field:"tourId"}),!t.steps||!Array.isArray(t.steps)){e.push({code:"MISSING_STEPS",message:"Tour action requires 'steps' array",field:"steps"});return}t.steps.length===0&&e.push({code:"EMPTY_STEPS",message:"Tour must have at least one step",field:"steps"});let n=new Set;for(let r=0;r<t.steps.length;r++){let o=t.steps[r];if(!o.id||typeof o.id!="string"?e.push({code:"MISSING_STEP_ID",message:`Step at index ${r} requires 'id' property`,field:`steps[${r}].id`}):(n.has(o.id)&&e.push({code:"DUPLICATE_STEP_ID",message:`Duplicate step ID: ${o.id}`,field:`steps[${r}].id`}),n.add(o.id)),!o.action)e.push({code:"MISSING_STEP_ACTION",message:`Step at index ${r} requires 'action' property`,field:`steps[${r}].action`});else{let i=bo(o.action);for(let s of i.errors)e.push({...s,field:`steps[${r}].action${s.field?`.${s.field}`:""}`});for(let s of i.warnings)a.push(s)}if(o.onAction)for(let[i,s]of Object.entries(o.onAction))s!=="end"&&!t.steps.some(l=>l.id===s)&&a.push({code:"UNKNOWN_TARGET_STEP",message:`Step "${o.id}" references unknown target step: ${s}`,suggestion:`Make sure step "${s}" exists in the tour`})}}function _b(t){let e=[],a=[];if(!Array.isArray(t))return console.error("[ActionValidation] validateActions called with non-array:",typeof t),e.push({code:"INVALID_ACTIONS",message:"Actions must be an array"}),{valid:!1,errors:e,warnings:a};for(let n=0;n<t.length;n++){let r=bo(t[n]);if(!r.valid){let o=t[n];console.error(`[ActionValidation] Action [${n}] failed validation:`,`kind="${o?.kind??"undefined"}"`,r.errors.map(i=>`${i.code}: ${i.message}`).join("; "),o)}for(let o of r.errors)e.push({...o,field:o.field?`[${n}].${o.field}`:`[${n}]`});for(let o of r.warnings)a.push({...o,suggestion:o.suggestion?`Action ${n}: ${o.suggestion}`:void 0})}return e.length>0&&console.error(`[ActionValidation] Batch validation failed: ${e.length} error(s) in ${t.length} action(s).`,e.map(n=>`${n.field??"?"}: ${n.message}`).join(" | ")),{valid:e.length===0,errors:e,warnings:a}}var p3=0;function wb(t){let{overlayRoot:e,eventBus:a,surfaces:n,anchorResolver:r,waitForAnchor:o,adaptiveId:i,executorRegistry:s=fr,subscribeNavigation:l,runtime:u}=t,c=new Map,d=new Map;function f(){return`action-${++p3}`}function h(C,I){a&&a.publish(C,I)}function S(){return{overlayRoot:e,resolveAnchor:r,waitForAnchor:o,generateId:f,publishEvent:h,adaptiveId:i,applyAction:g,subscribeEvent:a?(C,I)=>a.subscribe({names:[C]},w=>I(w.props)):void 0,subscribeNavigation:l}}async function x(C,I){if(!n)throw new Error("Surfaces provider required for core:mountWidget actions");let w=n.mount(C.slot,{type:"widget",widgetId:C.widget.widgetId,config:C.widget.props},{priority:C.widget.priority});return I.publishEvent("action.applied",{id:I.generateId(),kind:"core:mountWidget",slot:C.slot,widgetId:C.widget.widgetId}),{cleanup:()=>{w.unmount()},updateFn:k=>{if("widget"in k&&k.widget){let T=k.widget;T.props&&w.update({type:"widget",widgetId:C.widget.widgetId,config:T.props})}}}}async function b(C,I){if(C.kind==="core:mountWidget")return x(C,I);let w=s.get(C.kind);if(!w){let k="list"in s?s.list():"(list unavailable)";throw console.error(`[ActionEngine] No executor for kind="${C.kind}".`,`Registered: [${k}]`),new Error(`No executor for action kind: ${C.kind}`)}return w(C,I)}function m(C,I,w,k){if(!u)return;let T=[],D=async()=>{let M=c.get(C);if(!M)return;let F=u.evaluateSync(w).value;if(M.state==="applied"&&!F){try{await M.cleanup()}catch(U){console.error(`[ActionEngine] Error reverting conditional action ${C}:`,U)}M.state="deferred",M.cleanup=()=>{},M.updateFn=void 0,h("action.deferred",{id:C,kind:I.kind})}else if(M.state==="deferred"&&F)try{let U=S(),j=await b(I,U);M.state="applied",M.cleanup=j.cleanup,M.updateFn=j.updateFn,M.appliedTs=Date.now(),h("action.applied",{id:C,kind:I.kind,anchorId:"anchorId"in I?I.anchorId:void 0})}catch(U){console.error(`[ActionEngine] Error applying deferred action ${C}:`,U),M.state="failed"}};u.context&&T.push(u.context.subscribe(D)),u.accumulator&&T.push(u.accumulator.subscribe(D)),d.set(C,T)}async function g(C){let I=bo(C);if(!I.valid){let F=I.errors.map(U=>U.message).join("; ");throw console.error(`[ActionEngine] Validation failed for action kind="${C?.kind}":`,F,C),new Error(`Action validation failed: ${F}`)}let w=f(),k=C.triggerWhen;if(k&&u&&!u.evaluateSync(k).value){let U={id:w,action:C,adaptiveId:i,appliedTs:Date.now(),state:"deferred",cleanup:()=>{}};c.set(w,U);let j={id:w,action:C,async revert(){let N=c.get(w);if(!N)return;let X=d.get(w);if(X){for(let ye of X)ye();d.delete(w)}N.state="reverted",c.delete(w)},isApplied(){return c.get(w)?.state==="applied"},async update(N){let X=c.get(w);if(!X||X.state!=="applied")throw new Error("Cannot update action that is not applied");if(X.updateFn)await X.updateFn(N);else throw new Error(`Action kind ${C.kind} does not support updates`)},getState(){return c.get(w)?.state??"reverted"}};return m(w,C,k,j),j}let T=S(),D=await b(C,T),M={id:w,action:C,adaptiveId:i,appliedTs:Date.now(),state:"applied",cleanup:D.cleanup,updateFn:D.updateFn};c.set(w,M),h("action.applied",{id:w,kind:C.kind,anchorId:"anchorId"in C?C.anchorId:void 0});let P={id:w,action:C,async revert(){let F=c.get(w);if(!F||F.state!=="applied")return;let U=d.get(w);if(U){for(let j of U)j();d.delete(w)}try{await F.cleanup(),F.state="reverted",h("action.reverted",{id:w,kind:C.kind})}catch(j){console.warn(`[ActionEngine] Cleanup error for ${C.kind} (${w}), ignoring:`,j),F.state="reverted",h("action.reverted",{id:w,kind:C.kind})}finally{c.delete(w)}},isApplied(){return c.get(w)?.state==="applied"},async update(F){let U=c.get(w);if(!U||U.state!=="applied")throw new Error("Cannot update action that is not applied");if(U.updateFn)await U.updateFn(F);else throw new Error(`Action kind ${C.kind} does not support updates`)},getState(){return c.get(w)?.state??"reverted"}};return k&&u&&m(w,C,k,P),P}async function v(C){console.log(`[ActionEngine] applyBatch: ${C.length} action(s)`,C.map(M=>M.kind).join(", "));let I=_b(C);if(!I.valid){let M=I.errors.map(P=>P.message).join("; ");throw console.error(`[ActionEngine] Batch validation FAILED for ${C.length} action(s):`,M,`
|
|
518
518
|
Actions:`,C.map((P,F)=>` [${F}] ${P.kind} ${P.anchorId?`anchor="${P.anchorId.selector}"`:""} ${P.label?`label="${P.label}"`:""}`).join(`
|
|
519
|
-
`)),new Error(`Batch validation failed: ${M}`)}let w=f(),k=[],T=[];try{for(let M of C){let P=await g(M);k.push(P),T.push(P)}}catch(M){console.error(`[ActionEngine] Batch apply FAILED at action ${T.length+1}/${C.length}.`,`Successfully applied: ${T.length}. Rolling back...`,M);for(let P of T)try{await P.revert()}catch{}throw M}return{id:w,handles:k,async revertAll(){for(let M=k.length-1;M>=0;M--)try{await k[M].revert()}catch(P){console.error(`[ActionEngine] Error reverting action ${k[M].id}:`,P)}},isApplied(){return k.every(M=>M.isApplied())}}}function y(C){return bo(C)}function _(){return Array.from(c.values()).map(C=>({id:C.id,action:C.action,adaptiveId:C.adaptiveId,appliedTs:C.appliedTs,state:C.state}))}function L(){for(let C of d.values())for(let I of C)try{I()}catch{}d.clear();for(let C of c.values())if(C.state==="applied")try{C.cleanup()}catch(I){console.error("[ActionEngine] Error during cleanup:",I)}c.clear()}return{apply:g,applyBatch:v,validate:y,getActive:_,destroy:L}}var h3=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),Lb=p.object({type:p.literal("page_url"),url:p.string()}),kb=p.object({type:p.literal("route"),routeId:p.string()}),Ib=p.object({type:p.literal("anchor_visible"),anchorId:p.string(),state:p.enum(["visible","present","absent"])}),Ab=p.object({type:p.literal("event_occurred"),eventName:p.string(),withinMs:p.number().optional()}),Eb=p.object({type:p.literal("state_equals"),key:p.string(),value:p.unknown()}),Tb=p.object({type:p.literal("viewport"),minWidth:p.number().optional(),maxWidth:p.number().optional(),minHeight:p.number().optional(),maxHeight:p.number().optional()}),Rb=p.object({type:p.literal("session_metric"),key:p.string(),operator:p.enum(["gte","lte","eq","gt","lt"]),threshold:p.number()}),Mb=p.object({type:p.literal("dismissed"),key:p.string(),inverted:p.boolean().optional()}),Db=p.object({type:p.literal("cooldown_active"),key:p.string(),inverted:p.boolean().optional()}),Ob=p.object({type:p.literal("frequency_limit"),key:p.string(),limit:p.number(),inverted:p.boolean().optional()}),gc=p.object({equals:p.union([p.string(),p.number(),p.boolean()]).optional(),contains:p.string().optional()}),vc=p.object({events:p.array(p.string()).min(1),match:p.record(p.string(),gc).optional()}),Bb=p.object({type:p.literal("event_count"),key:p.string(),operator:p.enum(["gte","lte","eq","gt","lt"]),count:p.number().int().min(0),withinMs:p.number().positive().optional(),counter:vc.optional()}),So=p.discriminatedUnion("type",[Lb,kb,Ib,Ab,Eb,Tb,Rb,Mb,Db,Ob,Bb]),yc=p.object({conditions:p.array(So),value:p.unknown()}),xc=p.object({type:p.literal("rules"),rules:p.array(yc),default:p.unknown()}),bc=p.object({type:p.literal("score"),field:p.string(),threshold:p.number(),above:p.unknown(),below:p.unknown()}),Sc=p.object({type:p.literal("model"),modelId:p.string(),inputs:p.array(p.string()),outputMapping:p.record(p.string(),p.unknown()),default:p.unknown()}),Cc=p.object({type:p.literal("external"),endpoint:p.string(),method:p.enum(["GET","POST"]).optional(),default:p.unknown(),timeoutMs:p.number().optional()}),_c=p.discriminatedUnion("type",[xc,bc,Sc,Cc]),Jp=_c.nullable().optional(),m3=p.object({events:p.array(p.string()),urlContains:p.string().optional(),props:p.record(p.union([p.string(),p.number(),p.boolean()])).optional()}),g3=p.object({title:p.string().optional(),body:p.string().optional(),icon:p.string().optional()}).nullable().optional();var RE=p.object({include:p.array(p.string()).optional().describe("URL patterns where this tile appears. Supports *, **, :param wildcards. Use sparingly \u2014 mostly to isolate to specific webapp functionality. Omit to appear on all routes."),exclude:p.array(p.string()).optional().describe("URL patterns where this tile should NOT appear. Evaluated before include.")}),eh=p.object({routes:RE,onlyIfPopulated:p.boolean().optional().describe("When true, tile is hidden if none of its props.actions[] have an active triggerWhen. Useful for tiles with all-deferred FAQ questions or nav tips. Default: false.")});function TV(t){return So.safeParse(t)}function RV(t){return _c.safeParse(t)}function MV(t){return eh.safeParse(t)}var DV=[{defName:"matchOp",schema:gc},{defName:"counterDef",schema:vc},{defName:"activationConfig",schema:eh},{defName:"routeFilter",schema:RE},{defName:"ruleStrategy",schema:xc},{defName:"scoreStrategy",schema:bc},{defName:"modelStrategy",schema:Sc},{defName:"externalStrategy",schema:Cc},{defName:"rule",schema:yc},{defName:"condition",schema:So}];var Pb=p.object({tileId:p.string(),itemId:p.string().optional()}).strict(),v3=p.object({on:p.string(),title:p.string(),body:p.string().optional(),icon:p.string().optional(),ttl:p.number().optional(),cooldown:p.number().optional(),deepLink:Pb.optional()}).strict(),y3=p.object({id:p.string(),title:p.string().optional(),subtitle:p.string().optional(),icon:p.string().optional(),priority:p.number().optional(),widget:p.string(),props:p.record(p.unknown()).optional(),activation:eh.optional(),notifications:p.array(v3).optional()}).strict(),x3=p.object({position:p.enum(["left","right"]).optional(),layout:p.enum(["overlay","push"]).optional(),background:p.string().optional(),blur:p.string().optional(),border:p.string().optional(),width:p.string().optional(),transitionDuration:p.string().optional(),transitionEasing:p.string().optional(),transitionFade:p.string().optional()}),b3=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),color:p.string().optional(),size:p.string().optional(),shadow:p.string().optional(),borderRadius:p.string().optional()}),S3=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),shadow:p.string().optional(),titleColor:p.string().optional(),textColor:p.string().optional(),iconBackground:p.string().optional(),iconShadow:p.string().optional(),headerPadding:p.string().optional(),bodyPadding:p.string().optional(),gap:p.string().optional()}),C3=p.object({background:p.string().optional(),textColor:p.string().optional(),titleColor:p.string().optional(),arrowColor:p.string().optional(),arrowSize:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),scrimOpacity:p.string().optional(),highlightRing:p.string().optional()}),_3=p.object({background:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),successColor:p.string().optional(),warningColor:p.string().optional(),errorColor:p.string().optional(),iconBackground:p.string().optional(),progressGradient:p.string().optional()}),w3=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),itemDivider:p.string().optional(),itemGap:p.string().optional(),itemPadding:p.string().optional(),itemFontSize:p.string().optional(),bodyPadding:p.string().optional(),bodyFontSize:p.string().optional(),categoryPadding:p.string().optional(),categoryGap:p.string().optional(),categoryFontSize:p.string().optional(),searchBackground:p.string().optional(),searchColor:p.string().optional(),chevronColor:p.string().optional()}),L3=p.object({mode:p.enum(["dark","light"]).optional(),fontFamily:p.string().optional(),colorPrimary:p.string().optional(),colorPrimaryHover:p.string().optional(),borderRadius:p.string().optional(),canvas:x3.optional(),launcher:b3.optional(),tile:S3.optional(),overlay:C3.optional(),notification:_3.optional(),content:w3.optional()}).strict(),k3=p.object({enabled:p.boolean().optional(),label:p.string().optional(),icon:p.string().optional(),position:p.string().optional(),animate:p.boolean().optional(),animationStyle:p.enum(["pulse","bounce","glow"]).optional(),notificationCount:p.number().optional()}).strict(),NV=p.object({schemaVersion:p.string().optional(),fetchedAt:p.string().datetime(),configVersion:p.string().optional(),canvasTitle:p.string().optional(),tiles:p.array(y3),actions:p.array(p.any()),theme:L3.optional(),launcher:k3.optional(),meta:p.object({verificationSteps:p.array(p.union([p.string(),p.object({text:p.string(),check:So.optional()})])).optional()}).passthrough().optional()}).strict();var xt={triggerWhen:Jp},za=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),ME=p.object({color:p.string().optional(),scrimOpacity:p.number().min(0).max(1).optional(),paddingPx:p.number().optional(),radiusPx:p.number().optional()}).strict(),DE=p.enum(["top-left","top-right","bottom-left","bottom-right"]),OE=p.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),Nb=p.object({label:p.string(),actionId:p.string(),primary:p.boolean().optional()}).strict(),BE=p.object({title:p.string().optional(),body:p.string(),ctaButtons:p.array(Nb).optional()}).strict(),PE=p.object({title:p.string().optional(),body:p.string()}).strict(),FE=p.enum(["before","after","prepend","append","replace"]),NE=p.enum(["immediate","hover","click"]),HE=p.object({widgetId:p.string(),props:p.record(p.unknown()).optional(),priority:p.number().optional()}).strict(),UE=p.object({id:p.string(),action:p.any(),route:p.string().optional(),onAction:p.record(p.string()).optional()}).passthrough(),zE=p.enum(["auto","smooth","instant"]),Fb=p.enum(["start","center","end","nearest"]),qE=p.object({kind:p.literal("content:setText"),anchorId:za,text:p.string(),label:p.string().optional()}).extend(xt).strict(),$E=p.object({kind:p.literal("content:setAttr"),anchorId:za,attr:p.string(),value:p.string(),label:p.string().optional()}).extend(xt).strict(),VE=p.object({kind:p.literal("content:addClass"),anchorId:za,className:p.string(),label:p.string().optional()}).extend(xt).strict(),jE=p.object({kind:p.literal("content:removeClass"),anchorId:za,className:p.string(),label:p.string().optional()}).extend(xt).strict(),GE=p.object({kind:p.literal("content:setStyle"),anchorId:za,styles:p.record(p.string()),label:p.string().optional()}).extend(xt).strict(),ZE=p.object({kind:p.literal("content:insertHtml"),anchorId:za,html:p.string(),position:FE,deepLink:Pb.optional(),label:p.string().optional()}).extend(xt).strict(),WE=p.object({kind:p.literal("overlays:highlight"),anchorId:za,style:ME.optional(),duration:p.number().optional(),label:p.string().optional()}).extend(xt).strict(),XE=p.object({kind:p.literal("overlays:pulse"),anchorId:za,duration:p.number().optional(),label:p.string().optional()}).extend(xt).strict(),YE=p.object({kind:p.literal("overlays:badge"),anchorId:za,content:p.string(),position:DE.optional(),label:p.string().optional()}).extend(xt).strict(),KE=p.object({kind:p.literal("overlays:tooltip"),anchorId:za,content:BE,trigger:NE.optional(),placement:OE.optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(xt).strict(),QE=p.object({kind:p.literal("overlays:modal"),content:PE,size:p.enum(["sm","md","lg"]).optional(),blocking:p.boolean().optional(),scrim:p.object({opacity:p.number().min(0).max(1).optional()}).strict().optional(),dismiss:p.object({onEsc:p.boolean().optional(),closeButton:p.boolean().optional(),timeoutMs:p.number().min(0).optional()}).strict().optional(),ctaButtons:p.array(Nb).optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(xt).strict(),JE=p.object({kind:p.literal("navigation:scrollTo"),anchorId:za,behavior:zE.optional(),block:Fb.optional(),inline:Fb.optional(),label:p.string().optional()}).extend(xt).strict(),eT=p.object({kind:p.literal("navigation:navigate"),url:p.string(),target:p.enum(["_self","_blank"]).optional(),label:p.string().optional()}).extend(xt).strict(),tT=p.object({kind:p.literal("core:mountWidget"),slot:p.string(),widget:HE,label:p.string().optional()}).extend(xt).strict(),aT=p.object({kind:p.literal("core:wait"),durationMs:p.number().min(0).optional(),event:p.string().optional(),label:p.string().optional()}).extend(xt).strict(),nT=p.object({kind:p.literal("core:sequence"),actions:p.array(p.any()),label:p.string().optional()}).extend(xt).strict(),rT=p.object({kind:p.literal("core:parallel"),actions:p.array(p.any()),waitFor:p.enum(["all","any"]).optional(),label:p.string().optional()}).extend(xt).strict(),oT=p.object({kind:p.literal("core:tour"),tourId:p.string(),steps:p.array(UE).min(1),startStep:p.string().optional(),autoStart:p.boolean().optional(),label:p.string().optional()}).extend(xt).passthrough(),I3=[{defName:"setText",schema:qE},{defName:"setAttr",schema:$E},{defName:"addClass",schema:VE},{defName:"removeClass",schema:jE},{defName:"setStyle",schema:GE},{defName:"insertHtml",schema:ZE},{defName:"highlight",schema:WE},{defName:"pulse",schema:XE},{defName:"badge",schema:YE},{defName:"tooltip",schema:KE},{defName:"modal",schema:QE},{defName:"scrollTo",schema:JE},{defName:"navigate",schema:eT},{defName:"mountWidget",schema:tT},{defName:"wait",schema:aT},{defName:"sequence",schema:nT},{defName:"parallel",schema:rT},{defName:"tour",schema:oT}];function Hb(t){let e=t?.root??(typeof document<"u"?document.body:null),a=t?.defaultTimeoutMs??5e3,n=new Map,r=new Map,o=null,i=!1;function s(b){if(!e)return null;try{return e.matches(b)?e:e.querySelector(b)}catch{return null}}function l(){for(let[b,m]of n){let g=s(b);if(g){for(let v of m)clearTimeout(v.timer),v.resolve(g);n.delete(b)}}for(let[b,m]of r){let g=s(b);if(g){for(let v of m)v.cancelled||v.cb(g);r.delete(b)}}n.size===0&&r.size===0&&c()}function u(){o||i||typeof MutationObserver>"u"||!e||(o=new MutationObserver(()=>{l()}),o.observe(e,{childList:!0,subtree:!0}))}function c(){o&&(o.disconnect(),o=null)}function d(b,m){let g=n.get(b);g&&(g.delete(m),g.size===0&&n.delete(b)),n.size===0&&r.size===0&&c()}function f(b,m){if(i)return Promise.reject(new Error("AnchorResolver destroyed"));let g=s(b);if(g)return Promise.resolve(g);let v=m??a;return new Promise((y,_)=>{let L={resolve:y,reject:_,timer:setTimeout(()=>{d(b,L),_(new Error(`waitFor("${b}") timed out after ${v}ms`))},v)},C=n.get(b);C||(C=new Set,n.set(b,C)),C.add(L),u()})}function h(b,m){if(i)return()=>{};let g=s(b);if(g)return m(g),()=>{};let v={cb:m,cancelled:!1},y=r.get(b);return y||(y=new Set,r.set(b,y)),y.add(v),u(),()=>{v.cancelled=!0;let _=r.get(b);_&&(_.delete(v),_.size===0&&r.delete(b)),n.size===0&&r.size===0&&c()}}function S(){let b=0;for(let m of n.values())b+=m.size;return b}function x(){i=!0,c();let b=new Error("AnchorResolver destroyed");for(let m of n.values())for(let g of m)clearTimeout(g.timer),g.reject(b);n.clear(),r.clear()}return{resolve:s,waitFor:f,onAppear:h,pendingCount:S,destroy:x}}function A3(){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 Ub(t,e){if(!e)return;let a;try{a=new URL(t).pathname}catch{a=t}if(e.exclude){for(let n of e.exclude)if(iT(a,n))return}if(e.include){for(let n of e.include)if(iT(a,n))return n;return}return a}function iT(t,e){let a=t.replace(/\/$/,"")||"/",n=e.replace(/\/$/,"")||"/";if(a===n)return!0;let r=n.replace(/:[^/]+/g,"[^/]+").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(a)}var th=class{constructor(e){B(this,"context");B(this,"previousContext");B(this,"listeners",new Set);B(this,"telemetry");B(this,"routes");B(this,"navigation");B(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=A3(),this.previousContext={...this.context},e.telemetry?.getSessionId){let a=e.telemetry.getSessionId();a&&(this.context.session.sessionId=a)}e.initialPageHistory&&(this.context.session.pageHistory=e.initialPageHistory),this.context.page.routeId=Ub(this.context.page.url,this.routes),this.addPageToHistory(this.context.page.url),typeof window<"u"&&this.setupBrowserListeners()}get(){return{...this.context}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setRoutes(e){this.routes=e;let a=Ub(this.context.page.url,this.routes);a!==this.context.page.routeId&&this.updateContext({page:{...this.context.page,routeId:a}})}setAnchors(e){this.updateContext({anchors:e})}setSessionId(e){e!==this.context.session.sessionId&&this.updateContext({session:{...this.context.session,sessionId:e}})}destroy(){for(let e of this.cleanupFns)e();this.cleanupFns=[],this.listeners.clear()}setupBrowserListeners(){let e,a=()=>{clearTimeout(e),e=setTimeout(()=>{this.updateViewport()},100)};window.addEventListener("resize",a),this.cleanupFns.push(()=>window.removeEventListener("resize",a));let n=this.navigation.subscribe(()=>this.updatePage());this.cleanupFns.push(n)}updateViewport(){let e={width:window.innerWidth,height:window.innerHeight};(e.width!==this.context.viewport.width||e.height!==this.context.viewport.height)&&this.updateContext({viewport:e})}updatePage(){let e=window.location.href,{title:a}=document,n=Ub(e,this.routes),r={url:e,title:a,routeId:n};(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 a={url:e,ts:Date.now()},n=[...this.context.session.pageHistory||[],a];n.length>50&&n.shift(),this.context.session.pageHistory=n}updateContext(e){this.previousContext={...this.context},this.context={...this.context,...e},this.notifyListeners()}notifyListeners(){for(let e of this.listeners)try{e(this.context,this.previousContext)}catch(a){console.error("[ContextManager] Listener error:",a)}}};function zb(t){return new th(t)}var E3=p.object({url:p.string(),routeId:p.string().optional(),title:p.string().optional(),locale:p.string().optional()}),T3=p.object({url:p.string(),ts:p.number()}),R3=p.object({sessionId:p.string(),startTs:p.number(),pageHistory:p.array(T3).optional()}),M3=p.object({width:p.number(),height:p.number()}),D3=p.object({x:p.number(),y:p.number(),w:p.number(),h:p.number()}),O3=p.object({anchorId:p.string(),present:p.boolean(),visible:p.boolean().optional(),boundingBox:D3.optional()}),B3=p.record(p.string(),p.union([p.number(),p.string(),p.boolean(),p.undefined()])),P3=p.object({page:E3,session:R3,viewport:M3,anchors:p.array(O3).optional(),augmented:B3.optional()});function t8(t){return P3.safeParse(t)}function sT(t,e){let{context:a,state:n,events:r}=e;switch(t.type){case"page_url":{let{url:o}=t,i=a.page.url.split("?")[0].split("#")[0],s=o.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*");return new RegExp(`^${s}$`).test(i)}case"route":return a.page.routeId===t.routeId;case"anchor_visible":{let o=a.anchors?.find(i=>i.anchorId===t.anchorId);switch(t.state){case"visible":return o?.visible===!0;case"present":return o?.present===!0;case"absent":return!o?.present;default:return!1}}case"event_occurred":{if(!r)return!1;let o=t.withinMs??6e4;return r.hasRecentEvent(t.eventName,o)}case"state_equals":return n?.getValue?n.getValue(t.key)===t.value:!1;case"viewport":{let{width:o,height:i}=a.viewport;return!(t.minWidth!==void 0&&o<t.minWidth||t.maxWidth!==void 0&&o>t.maxWidth||t.minHeight!==void 0&&i<t.minHeight||t.maxHeight!==void 0&&i>t.maxHeight)}case"session_metric":{if(!n)return!1;let o=n.getSessionMetric(t.key),{operator:i,threshold:s}=t;switch(i){case"gte":return o>=s;case"lte":return o<=s;case"eq":return o===s;case"gt":return o>s;case"lt":return o<s;default:return!1}}case"dismissed":{if(!n)return t.inverted??!1;let o=n.isDismissed(t.key);return t.inverted?!o:o}case"cooldown_active":{if(!n)return t.inverted??!1;let o=n.isCooldownActive(t.key);return t.inverted?!o:o}case"frequency_limit":{if(!n)return t.inverted??!1;let i=n.getFrequencyCount(t.key)>=t.limit;return t.inverted?!i:i}case"event_count":{if(!e.accumulator)return!1;let o=t,i=e.accumulator.getCount(o.key,o.withinMs);switch(o.operator){case"gte":return i>=o.count;case"lte":return i<=o.count;case"eq":return i===o.count;case"gt":return i>o.count;case"lt":return i<o.count;default:return!1}}default:return console.warn("[RuleStrategy] Unknown condition type:",t.type),!1}}function lT(t,e){let a=[];for(let n of t.conditions){let r=sT(n,e);if(a.push({condition:n,result:r}),!r)return{matched:!1,conditionResults:a}}return{matched:!0,conditionResults:a}}function ah(t,e){for(let a=0;a<t.rules.length;a++){let n=t.rules[a],{matched:r,conditionResults:o}=lT(n,e);if(r)return{value:n.value,isFallback:!1,matchInfo:{strategyType:"rules",matchedRuleIndex:a,evaluatedConditions:o}}}return{value:t.default,isFallback:!0,matchInfo:{strategyType:"rules"}}}function nh(t,e){let{context:a}=e,n=a.augmented?.[t.field];return n===void 0||typeof n!="number"?{value:t.below,isFallback:!0,matchInfo:{strategyType:"score"}}:{value:n>=t.threshold?t.above:t.below,isFallback:!1,matchInfo:{strategyType:"score"}}}function uT(t,e){let{state:a,events:n,sessionMetrics:r,accumulator:o}=e;return{context:t,state:a?{isDismissed:i=>a.dismissals.isDismissed(i),isCooldownActive:i=>a.cooldowns.isActive(i),getFrequencyCount:i=>a.frequency.count(i),getSessionMetric:i=>r?.get(i)??0,getValue:i=>a.session.get(i)??a.user.get(i)}:void 0,events:n?{hasRecentEvent:(i,s)=>n.hasRecentEvent(i,s)}:void 0,accumulator:o?{getCount:(i,s)=>o.getCount(i,s)}:void 0}}async function cT(t,e,a={}){let n=uT(e,a);switch(t.type){case"rules":return ah(t,n);case"score":return nh(t,n);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 dT(t,e,a={}){let n=uT(e,a);switch(t.type){case"rules":return ah(t,n);case"score":return nh(t,n);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 qb(t){return{evaluate:(e,a)=>cT(e,a,t),evaluateSync:(e,a)=>dT(e,a,t)}}function $b(t){let{eventBus:e,stateStore:a}=t,n=new Map,r=new Set,o=null,i=a.ns("accumulator");function s(u){let c=!1;for(let d of n.values()){if(!d.predicate(u))continue;let f=i.get(d.stateKey)||{count:0};f.count++,d.needsTimestamps&&(f.timestamps||(f.timestamps=[]),f.timestamps.push(u.ts),f.timestamps.length>200&&(f.timestamps=f.timestamps.slice(-200))),i.set(d.stateKey,f),c=!0}if(c)for(let d of r)try{d()}catch(f){console.error("[EventAccumulator] Subscriber error:",f)}}function l(){o||n.size===0||(o=e.subscribe(s))}return{register(u,c,d=!1){let f=`ev:${u}`,h=n.get(f);if(h){d&&!h.needsTimestamps&&(h.needsTimestamps=!0);return}n.set(f,{stateKey:f,needsTimestamps:d,predicate:c}),l()},getCount(u,c){let d=`ev:${u}`,f=i.get(d);if(!f)return 0;if(c===void 0||!f.timestamps)return f.count;let h=Date.now()-c;return f.timestamps.filter(S=>S>=h).length},subscribe(u){return r.add(u),()=>{r.delete(u)}},destroy(){o&&(o(),o=null),n.clear(),r.clear()}}}function Vb(t,e){return e?!(e.names&&e.names.length>0&&!e.names.includes(t.name)||e.patterns&&e.patterns.length>0&&!e.patterns.some(n=>{try{return new RegExp(n).test(t.name)}catch{return!1}})||e.sources&&e.sources.length>0&&!e.sources.includes(t.source)):!0}var rh=class{constructor(e={}){B(this,"subscriptions",new Set);B(this,"history",[]);B(this,"maxHistorySize");this.maxHistorySize=e.maxHistorySize??100}subscribe(e,a){let n,r;typeof e=="function"?(n=void 0,r=e):(n=e,r=a);let o={filter:n,callback:r};return this.subscriptions.add(o),()=>{this.subscriptions.delete(o)}}publish(e,a,n="canvas"){let r={ts:Date.now(),name:e,source:n,props:a,schemaVersion:Cs};this.publishEvent(r)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let a of this.subscriptions)if(Vb(e,a.filter))try{a.callback(e)}catch(n){console.error("[EventBus] Subscriber error:",n)}}getRecent(e,a){let n=this.history;return e&&(n=n.filter(r=>Vb(r,e))),a&&a>0&&(n=n.slice(-a)),n}hasRecentEvent(e,a,n){let r=Date.now()-a;return this.history.some(o=>o.name===e&&o.ts>=r&&(n===void 0||o.source===n))}countRecentEvents(e,a){let n=this.history.filter(r=>Vb(r,e));if(a!==void 0){let r=Date.now()-a;n=n.filter(o=>o.ts>=r)}return n.length}clearHistory(){this.history=[]}getSubscriberCount(){return this.subscriptions.size}};function wc(t={}){return new rh(t)}var fT={$autocapture:"ui.click",$click:we.UI_CLICK,$scroll:we.UI_SCROLL,$input:we.UI_INPUT,$change:we.UI_CHANGE,$submit:we.UI_SUBMIT,$pageview:we.NAV_PAGE_VIEW,$pageleave:we.NAV_PAGE_LEAVE,$session_start:"session.start",$identify:"user.identify"};function F3(t){let e=t.event;if(typeof e!="string")return"posthog.unknown";if(fT[e])return fT[e];if(e==="$autocapture"){let a=t.properties?.$tag_name,n=t.properties?.$event_type;return n==="submit"?we.UI_SUBMIT:n==="change"?we.UI_CHANGE:a==="input"||a==="textarea"?we.UI_INPUT:we.UI_CLICK}return e.startsWith("$")?e.replace("$","posthog."):`posthog.${e}`}var pT=new Set(["a","button","input","select","textarea"]);function N3(t,e){if(e&&pT.has(e)||!t)return e;for(let a of t){let n=a.tag_name;if(n&&pT.has(n))return n}return e}function H3(t){let e={},a=t.properties||{},n=a.$elements,r=a.$tag_name??n?.[0]?.tag_name,o=t.event==="$autocapture"||t.event==="$click";return e.tagName=o?N3(n,r):r,a.$el_text&&(e.elementText=a.$el_text),n&&(e.elements=n),a.$current_url&&(e.url=a.$current_url),a.$pathname&&(e.pathname=a.$pathname),a.$host&&(e.host=a.$host),a.$viewport_width&&(e.viewportWidth=a.$viewport_width),a.$viewport_height&&(e.viewportHeight=a.$viewport_height),a.$session_id&&(e.sessionId=a.$session_id),a.$scroll_depth&&(e.scrollDepth=a.$scroll_depth),a.$scroll_percentage&&(e.scrollPercentage=a.$scroll_percentage),e.originalEvent=t.event,e}function hT(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:F3(t),source:"posthog",props:H3(t),schemaVersion:Cs}}function mT(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 jb(t){return(e,a)=>{if(typeof e!="string")return;let n={event:e,properties:a,timestamp:Date.now()};if(mT(n)){let r=hT(n);t(r)}}}var gT=p.enum(["posthog","canvas","derived"]),U3=p.object({ts:p.number(),name:p.string(),source:gT,props:p.record(p.string(),p.unknown()).optional(),schemaVersion:p.string()}),z3=p.object({names:p.array(p.string()).optional(),patterns:p.array(p.string()).optional(),sources:p.array(gT).optional()});function L8(t){return U3.safeParse(t)}function k8(t){return z3.safeParse(t)}var Lc=class{constructor(){B(this,"listeners",new Set);B(this,"capturedPushState");B(this,"capturedReplaceState");B(this,"wasNative");B(this,"destroyed",!1);B(this,"onPopState",()=>{this.notify(window.location.href,"popstate")});this.wasNative=this.isNativeFunction(history.pushState),this.capturedPushState=history.pushState,this.capturedReplaceState=history.replaceState,history.pushState=(...e)=>{this.capturedPushState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"pushState"))},history.replaceState=(...e)=>{this.capturedReplaceState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"replaceState"))},window.addEventListener("popstate",this.onPopState)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}diagnose(){return{isNative:this.wasNative,subscriberCount:this.listeners.size}}destroy(){this.destroyed||(this.destroyed=!0,history.pushState=this.capturedPushState,history.replaceState=this.capturedReplaceState,window.removeEventListener("popstate",this.onPopState),this.listeners.clear())}notify(e,a){if(!this.destroyed)for(let n of this.listeners)try{n(e,a)}catch{}}isNativeFunction(e){try{return Function.prototype.toString.call(e).includes("[native code]")}catch{return!1}}};var Gb="cooldown:";function vT(t){return{set(e,a){let n=Gb+e,r=Date.now()+a;t.set(n,r)},isActive(e){return this.remaining(e)>0},remaining(e){let a=Gb+e,n=t.get(a);if(n===void 0)return 0;let r=n-Date.now();return r<=0?(t.remove(a),0):r},clear(e){let a=Gb+e;t.remove(a)}}}var kc="dismissed:";function yT(t,e){return{mark(a,n=!1){let r=kc+a;(n?e:t).set(r,!0)},isDismissed(a){let n=kc+a;return t.has(n)||e.has(n)},clear(a){let n=kc+a;t.remove(n),e.remove(n)},clearAll(){for(let a of t.keys())a.startsWith(kc)&&t.remove(a);for(let a of e.keys())a.startsWith(kc)&&e.remove(a)}}}var Zb="freq:";function xT(t){function e(a){let n=Zb+a,r=t.get(n);if(r){if(r.resetAt&&Date.now()>=r.resetAt){t.remove(n);return}return r}}return{increment(a,n){let r=Zb+a,o=e(a),i=(o?.count??0)+1,s={count:i,resetAt:o?.resetAt??(n?Date.now()+n:void 0)};return t.set(r,s),i},count(a){return e(a)?.count??0},reset(a){let n=Zb+a;t.remove(n)},hasReachedLimit(a,n){return this.count(a)>=n}}}var q3="syntro";function Wb(t,e){let a=`${e}:`;return{get(n){if(t)try{let r=t.getItem(a+n);if(!r)return;let o=JSON.parse(r);if(o.expiresAt&&Date.now()>=o.expiresAt){t.removeItem(a+n);return}return o.value}catch{return}},set(n,r,o){if(t)try{let i={value:r,expiresAt:o?Date.now()+o:void 0};t.setItem(a+n,JSON.stringify(i))}catch(i){console.warn("[StateStore] Failed to save:",i)}},remove(n){t&&t.removeItem(a+n)},has(n){return t?this.get(n)!==void 0:!1},keys(){if(!t)return[];let n=[];for(let r=0;r<t.length;r++){let o=t.key(r);o?.startsWith(a)&&n.push(o.slice(a.length))}return n},clear(){if(!t)return;let n=this.keys();for(let r of n)t.removeItem(a+r)}}}function Ic(t){let e=new Map,a=`${t}:`;return{get(n){let r=e.get(a+n);if(r){if(r.expiresAt&&Date.now()>=r.expiresAt){e.delete(a+n);return}return r.value}},set(n,r,o){e.set(a+n,{value:r,expiresAt:o?Date.now()+o:void 0})},remove(n){e.delete(a+n)},has(n){return this.get(n)!==void 0},keys(){let n=[];for(let r of e.keys())r.startsWith(a)&&n.push(r.slice(a.length));return n},clear(){for(let n of e.keys())n.startsWith(a)&&e.delete(n)}}}var oh=class{constructor(e={}){B(this,"session");B(this,"user");B(this,"dismissals");B(this,"cooldowns");B(this,"frequency");B(this,"namespace");B(this,"namespacedStorages",new Map);this.namespace=e.namespace??q3;let a=n=>typeof n=="object"&&n!==null&&typeof n.setItem=="function";typeof window<"u"?(this.session=a(window.sessionStorage)?Wb(window.sessionStorage,this.namespace):Ic(this.namespace),this.user=a(window.localStorage)?Wb(window.localStorage,this.namespace):Ic(this.namespace)):(this.session=Ic(this.namespace),this.user=Ic(this.namespace)),this.dismissals=yT(this.session,this.user),this.cooldowns=vT(this.user),this.frequency=xT(this.session)}ns(e){let a=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(a)){let n=typeof window<"u"&&typeof sessionStorage<"u"?Wb(sessionStorage,a):Ic(a);this.namespacedStorages.set(a,n)}return this.namespacedStorages.get(a)}};function Xb(t={}){return new oh(t)}function Ac(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function ih(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var bT={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"}},Ec={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:[]},ST={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function Yb(t,e,a){let n=bT[e];Object.assign(t.style,n),a&&(a.maxWidth&&(t.style.maxWidth=a.maxWidth),a.maxHeight&&(t.style.maxHeight=a.maxHeight),a.minWidth&&(t.style.minWidth=a.minWidth),a.minHeight&&(t.style.minHeight=a.minHeight))}function Kb(t,e,a){let n=a.placement==="auto"?"bottom":a.placement,r=[Sf(a.offset?{mainAxis:a.offset.y,crossAxis:a.offset.x}:8)];return a.flip!==!1&&r.push(_f()),a.shift!==!1&&r.push(Cf({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",bf(e,t,async()=>{let{x:i,y:s,strategy:l}=await wf(e,t,{placement:n,middleware:r});Object.assign(t.style,{position:l,left:`${i}px`,top:`${s}px`})})}function Qb(t,e,a="append"){return t.style.position="relative",t.style.display="inline-block",a==="prepend"?e.insertBefore(t,e.firstChild):e.appendChild(t),()=>{t.remove()}}function Jb(t,e){return e==="none"||Ec[e].length===0?null:t.animate(Ec[e],ST)}function e0(t,e){if(e==="none"||Ec[e].length===0)return Promise.resolve();let a=[...Ec[e]].reverse(),n=t.animate(a,ST);return new Promise(r=>{n.onfinish=()=>r(),n.oncancel=()=>r()})}function t0(t,e){let a=document.createElement("div");return a.setAttribute("data-syntro-surface",t),a.setAttribute("data-syntro-mount-id",e),a.className="syntro-surface",Object.assign(a.style,{pointerEvents:"auto",boxSizing:"border-box",overflow:"auto"}),a}function a0(t){switch(Ac(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 CT(t){if(typeof window.Sanitizer=="function")try{let l=new window.Sanitizer({}).sanitizeToFragment(t),u=document.createElement("div");return u.append(l),u.innerHTML}catch{}let a=document.createElement("template");a.innerHTML=t;let n=a.content,r=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),o=new Set(["b","strong","i","em","u","span","div","p","br","ul","ol","li","code","pre","small","sup","sub","a","button"]),i=[];for(;r.nextNode();){let s=r.currentNode,l=s.tagName.toLowerCase();if(!o.has(l)){i.push(s);continue}for(let u of Array.from(s.attributes)){let c=u.name.toLowerCase(),d=u.value.trim().toLowerCase(),f=c.startsWith("on"),h=(c==="href"||c==="src")&&d.startsWith("javascript:");(f||h)&&s.removeAttribute(u.name)}}for(let s of i){for(;s.firstChild;)s.parentNode?.insertBefore(s.firstChild,s);s.remove()}return a.innerHTML=(n.firstChild,a.innerHTML)}var $3=0;function n0(t){let{overlayRoot:e,eventBus:a,anchorResolver:n,defaultAnimation:r="fade",widgetRegistry:o}=t,i=new Map,s=new Map,l=new Map;function u(){return`mount-${++$3}`}function c(y,_){a&&a.publish(y,_)}function d(y){let _=l.get(y);if(_){let L=b(y);for(let C of _)try{C(L)}catch(I){console.error("[Surfaces] State callback error:",I)}}}let f=new Map;function h(y,_,L){switch(_.type){case"html":y.innerHTML=CT(_.content);return;case"widget":{if(o?.has(_.widgetId)){let C=o.mount(_.widgetId,y,_.config);return L&&f.set(L,C),()=>{C.unmount(),L&&f.delete(L)}}console.warn(`[Surfaces] Widget not found: ${_.widgetId}`),y.innerHTML=`<div data-widget-id="${_.widgetId}" data-widget-missing="true">Widget: ${_.widgetId}</div>`;return}case"custom":return _.mount(y);case"react":y.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function S(y,_,L){let C=u(),I=Ac(y),w=L?.priority??0,k=L?.animation??r,T=L?.exclusive??!0,D=i.get(y);if(D&&T){if(D.options.priority>w)throw new Error(`Slot ${y} is occupied by higher priority content (${D.options.priority} > ${w})`);x(D)}let M=t0(y,C);M.style.zIndex=String(a0(y));let P;if(I==="static")Yb(M,y,L?.constraints),e.appendChild(M);else if(I==="inline"){let N=ih(y);if(!N)throw new Error(`Invalid inline slot: ${y}`);if(!n)throw new Error("Anchor resolver required for inline slots");let X=n({selector:N,route:"**"});if(!X)throw new Error(`Anchor not found for inline slot: ${N}`);P=Qb(M,X)}else if(I==="adjacent"){let N=ih(y);if(!N)throw new Error(`Invalid adjacent slot: ${y}`);if(!n)throw new Error("Anchor resolver required for adjacent slots");let X=n({selector:N,route:"**"});if(!X)throw new Error(`Anchor not found for adjacent slot: ${N}`);e.appendChild(M),P=Kb(M,X,L?.position??{placement:"bottom"})}let F=h(M,_,C);Jb(M,k);let U={id:C,slot:y,content:_,options:{priority:w,exclusive:T,animation:k,position:L?.position??{placement:"auto"},constraints:L?.constraints??{},adaptiveId:L?.adaptiveId,autoUnmountOnRouteChange:L?.autoUnmountOnRouteChange??!0},container:M,cleanup:()=>{P?.(),F?.()},mountedAt:Date.now()};return i.set(y,U),s.set(y,(s.get(y)??0)+1),c("surface.mounted",{slot:y,id:C,adaptiveId:L?.adaptiveId}),d(y),{id:C,update(N){let X=i.get(y);if(!X||X.id!==C)throw new Error("Mount no longer active");let ye=f.get(C);if(ye){if(N.type==="widget"){ye.update(N.config),X.content=N;return}ye.unmount(),f.delete(C)}X.container.innerHTML="";let qa=h(X.container,N,C);if(X.content=N,qa){let ht=X.cleanup;X.cleanup=()=>{ht?.(),qa()}}},setOptions(N){let X=i.get(y);if(!X||X.id!==C)throw new Error("Mount no longer active");N.priority!==void 0&&(X.options.priority=N.priority),N.animation!==void 0&&(X.options.animation=N.animation),N.constraints&&I==="static"&&(N.constraints.maxWidth&&(X.container.style.maxWidth=N.constraints.maxWidth),N.constraints.maxHeight&&(X.container.style.maxHeight=N.constraints.maxHeight),N.constraints.minWidth&&(X.container.style.minWidth=N.constraints.minWidth),N.constraints.minHeight&&(X.container.style.minHeight=N.constraints.minHeight)),d(y)},async unmount(){let N=i.get(y);!N||N.id!==C||await x(N)},isMounted(){return i.get(y)?.id===C},getContainer(){let N=i.get(y);return N?.id===C?N.container:null}}}async function x(y){y.container.isConnected&&await e0(y.container,y.options.animation);try{y.cleanup?.()}catch(_){console.warn("[Surfaces] Cleanup error during unmount, ignoring:",_)}try{y.container.remove()}catch{}i.delete(y.slot),c("surface.unmounted",{slot:y.slot,id:y.id}),d(y.slot)}function b(y){let _=i.get(y);return{slot:y,occupied:!!_,currentPriority:_?.options.priority,currentAdaptiveId:_?.options.adaptiveId,mountCount:s.get(y)??0,currentMountId:_?.id}}function m(y,_){let L=l.get(y);return L||(L=new Set,l.set(y,L)),L.add(_),()=>{L?.delete(_),L?.size===0&&l.delete(y)}}function g(y,_){let L=i.get(y);return L?_!==void 0?_>=L.options.priority:!1:!0}function v(){for(let y of i.values())try{y.cleanup?.(),y.container.remove()}catch(_){console.error("[Surfaces] Error during cleanup:",_)}i.clear(),l.clear()}return{mount:S,getState:b,onStateChange:m,canMount:g,destroy:v}}var sh=class{constructor(){B(this,"widgets",new Map);B(this,"mountedWidgets",new Map);B(this,"mountIdCounter",0);B(this,"runtimeRef");B(this,"listeners",new Set)}bindRuntime(e){this.runtimeRef=e}register(e,a,n="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:a,source:n,metadata:r}),this.notify({type:"registered",widgetId:e})}unregister(e){let a=this.widgets.get(e);return a?a.source==="built-in"?(console.warn(`[WidgetRegistry] Cannot unregister built-in widget: ${e}`),!1):(this.widgets.delete(e),this.notify({type:"unregistered",widgetId:e}),!0):!1}unregisterBySource(e){for(let[a,n]of this.widgets.entries())n.source===e&&this.widgets.delete(a)}get(e){return this.widgets.get(e)?.widget}getRegistration(e){return this.widgets.get(e)}has(e){return this.widgets.has(e)}mount(e,a,n){let r=this.widgets.get(e);if(!r)throw new Error(`Widget not found: ${e}`);let o=`widget-mount-${++this.mountIdCounter}`;a.setAttribute("data-widget-mount-id",o),a.setAttribute("data-widget-id",e);let i={...n,runtime:this.runtimeRef},s=r.widget.mount(a,i);return this.mountedWidgets.set(o,{cleanup:s??void 0,container:a}),{widgetId:e,container:a,unmount:()=>{let u=this.mountedWidgets.get(o);u&&(a.isConnected&&u.cleanup?.(),this.mountedWidgets.delete(o),a.removeAttribute("data-widget-mount-id"),a.removeAttribute("data-widget-id"),a.innerHTML="")},update:u=>{if(r.widget.update)r.widget.update(a,u);else{let c=this.mountedWidgets.get(o);if(c){c.cleanup?.(),a.innerHTML="";let d={...u,runtime:this.runtimeRef},f=r.widget.mount(a,d);c.cleanup=f??void 0}}}}}list(){return Array.from(this.widgets.keys())}listRegistrations(){return Array.from(this.widgets.values())}getBySource(e){return Array.from(this.widgets.values()).filter(a=>a.source===e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(let a of this.listeners)try{a(e)}catch(n){console.error("[WidgetRegistry] Listener error:",n)}}destroy(){for(let[e,a]of this.mountedWidgets.entries())a.cleanup?.(),a.container.innerHTML="";this.mountedWidgets.clear()}},r0=new sh;var wT="2.0.0";function V3(t,e){if(!e)return!0;let a;try{a=new URL(t).pathname}catch{a=t}let n=a.replace(/\/$/,"")||"/";if(e.exclude){for(let r of e.exclude)if(o0(n,r))return!1}if(e.include&&e.include.length>0){for(let r of e.include)if(o0(n,r))return!0;return!1}return!0}function o0(t,e){let a=e.replace(/\/$/,"")||"/";if(t===a)return!0;let n=a.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*").replace(/:[^/]+/g,"[^/]+");return new RegExp(`^${n}$`).test(t)}function _T(t){let a=(typeof window<"u"?window.location.pathname:"/").replace(/\/$/,"")||"/";return(Array.isArray(t.route)?t.route:[t.route]).some(r=>o0(a,r))}function i0(t={}){let{telemetry:e,sessionMetrics:a,routes:n,mode:r="production",namespace:o}=t,i=t.widgets??r0,s=t.executors??fr,l=t.apps??lu,u=new Lc,c=zb({telemetry:e,routes:n,navigation:u}),d=t.events??wc(),f=Xb({namespace:o}),h=$b({eventBus:d,stateStore:f}),S=qb({state:f,events:d,sessionMetrics:a,accumulator:h}),x=nk(),b=Hb(),m=C=>_T(C)?b.resolve(C.selector):null,g=async(C,I)=>{if(!_T(C))return null;try{return await b.waitFor(C.selector,I)}catch{return null}},v=n0({overlayRoot:x,eventBus:d,anchorResolver:m,widgetRegistry:i}),y=wb({overlayRoot:x,eventBus:d,surfaces:v,anchorResolver:m,waitForAnchor:g,executorRegistry:s,subscribeNavigation:C=>u.subscribe(C),runtime:{evaluateSync:C=>S.evaluateSync(C,c.get()),context:c,accumulator:h}}),_;if(a){a.increment("page_views");let C=typeof window<"u"?window.location.pathname:"/";_=u.subscribe((I,w)=>{if(w!=="replaceState")try{let k=new URL(I).pathname;k!==C&&(C=k,a.increment("page_views"))}catch{}})}let L={telemetry:e,context:c,events:d,state:f,sessionMetrics:a,actions:y,surfaces:v,widgets:i,executors:s,apps:l,accumulator:h,anchorResolver:b,navigation:u,version:wT,mode:r,async evaluate(C){return S.evaluate(C,c.get())},evaluateSync(C){return S.evaluateSync(C,c.get())},async filterTiles(C){let I=c.get().page.url,w=[];for(let k of C){let T=k.activation;if(!T){w.push(k);continue}if(V3(I,T.routes)){if(T.onlyIfPopulated){let D=k.props?.actions??[];if(D.length>0&&!D.some(P=>P.triggerWhen?S.evaluateSync(P.triggerWhen,c.get()).value:!0))continue}w.push(k)}}return w},setRoutes(C){c.setRoutes(C)},destroy(){l.unbind().catch(C=>{console.error("[Runtime] Error unbinding apps registry:",C)}),_?.(),b.destroy(),h.destroy(),u.destroy(),c.destroy(),y.destroy(),v.destroy()}};return l.bind(L),i.bindRuntime(L),L}var j3=p.object({value:p.unknown(),expiresAt:p.number().optional()}),G3=p.object({count:p.number(),resetAt:p.number().optional()});function E9(t){return j3.safeParse(t)}function T9(t){return G3.safeParse(t)}var LT={growthbook:t=>Ay({...t,autoInit:!0})};function kT(t,e){let a=LT[t];if(!a)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys(LT).join(", ")}`);return a(e)}var Z3=["cdn.syntrologie.com","localhost","127.0.0.1"];function W3(t){try{let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(console.warn("[SmartCanvas] CDN URL must use HTTPS:",t),!1):Z3.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 s0=class{constructor(e){B(this,"name","cdn");B(this,"url");B(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!W3(this.url))throw new Error(`[SmartCanvas] CDN URL not allowed: ${this.url}`)}async fetch(){let e=performance.now(),a=await fetch(this.url,{credentials:"omit",cache:"default"});if(!a.ok)throw new Error(`[SmartCanvas] Failed to fetch config from CDN (${a.status})`);let n=await a.text();if(this.integrity){let l=await X3(n),u=this.integrity.replace("sha384-","");if(l!==u)throw new Error(`[SmartCanvas] Config integrity check failed. Expected ${u}, got ${l}`)}let r=JSON.parse(n),o=performance.now()-e,i=a.headers.get("cache-control"),s=a.headers.get("age");return{config:r,meta:{source:"cdn",fetchTimeMs:o,cached:i?.includes("public")??!1,cacheAge:s?parseInt(s,10):void 0}}}};async function X3(t){let a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-384",a),r=new Uint8Array(n);return btoa(String.fromCharCode(...r))}function IT(t){return new s0(t)}var Y3="syntro_exp",K3="syntro_var",l0=class{constructor(e){B(this,"name","experiments");B(this,"client");B(this,"featureKey");B(this,"manifestKey");B(this,"variantFlagPrefix");this.client=e.client,this.featureKey=e.featureKey??"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),o=r.get(Y3),i=r.get(K3);if(o&&i!==null&&this.client.setForcedVariations){let s=parseInt(i,10);Number.isNaN(s)||(console.log(`[SmartCanvas] Preview mode: forcing "${o}" to variation ${s}`),this.client.setForcedVariations({[o]:s}))}}if(this.manifestKey||this.variantFlagPrefix||this.client.getAllFeatures){let r=this.fetchMultiFlag();if(r){let o=performance.now()-e;return{config:r,meta:{source:"experiments",fetchTimeMs:o,cached:!0}}}}let a=this.client.getFeatureValue?.(this.featureKey,null);if(!a||typeof a!="object")throw new Error(`[SmartCanvas] Feature "${this.featureKey}" not found or invalid. Ensure the feature is configured in your experiment platform.`);let n=performance.now()-e;return{config:a,meta:{source:"experiments",fetchTimeMs:n,cached:!0}}}fetchMultiFlag(){let e=this.getVariantFlagKeys();return!e||e.length===0?null:Pf(this.client,e)}getVariantFlagKeys(){if(this.manifestKey){let e=this.client.getFeatureValue?.(this.manifestKey,null);if(e&&typeof e=="object"){let a=e.variant_flags;if(a&&a.length>0)return a}}if(this.client.getAllFeatures){let e=this.client.getAllFeatures();return this.variantFlagPrefix?Object.keys(e).filter(a=>a.startsWith(this.variantFlagPrefix)):Object.keys(e)}return[]}};function AT(t){return new l0(t)}var Q3="https://cdn.syntrologie.com/configs",ET={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return IT({baseUrl:t.baseUrl??Q3,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return AT({featureKey:t.featureKey})}};function TT(t,e={}){let a=ET[t];if(!a)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys(ET).join(", ")}`);return a(e)}var RT={posthog:t=>yb(t),noop:()=>By()};function MT(t,e){let a=RT[t];if(!a)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(RT).join(", ")}`);return a(e)}var u0="syn_";function lh(t){if(!t.startsWith(u0))throw new Error("Invalid Syntro token: must start with 'syn_'");let a=t.slice(u0.length).replace(/-/g,"+").replace(/_/g,"/"),n=atob(a),r=JSON.parse(n);if(r.v!==1)throw new Error(`Unsupported token version: ${r.v}`);return r}function c0(t){let e=JSON.stringify(t),a=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return u0+a}function pr(t){if(typeof process<"u"&&process.env)return process.env[t];try{let e=(0,eval)("import.meta");if(e?.env)return e.env[t]}catch{}}var DT="syntro_segment_attributes";function J3(){if(typeof window>"u")return{};try{let t=localStorage.getItem(DT);if(t){let e=JSON.parse(t);return K("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){ya("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function eH(t){if(!(typeof window>"u"))try{localStorage.setItem(DT,JSON.stringify(t)),K("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){ya("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function tH(t){if(!t)return{};let e={};for(let[a,n]of Object.entries(t))a.startsWith("in_segment_")&&(e[a]=n===!0);return e}function aH(){if(typeof window>"u")return{};let t={};try{let e=new URLSearchParams(window.location.search);for(let a of["utm_source","utm_medium","utm_campaign","utm_content","utm_term"]){let n=e.get(a);n&&(t[a]=n)}}catch{}try{navigator.language&&(t.browser_language=navigator.language),navigator.languages?.length&&(t.browser_languages=[...navigator.languages])}catch{}try{let e=window.innerWidth;t.device_type=e<768?"mobile":e<1024?"tablet":"desktop"}catch{}try{if(document.referrer){t.referrer=document.referrer;try{t.referrer_hostname=new URL(document.referrer).hostname}catch{}}}catch{}try{t.page_url=window.location.href,t.page_path=window.location.pathname}catch{}return t}async function nH(t){Fv(),K("Syntro Bootstrap","====== INIT ======"),K("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=Hf();if(console.log(`[DIAG] Mode detection: sdkMode=${e}`),console.log("[DIAG] editorSource:",mu()),console.log("[DIAG] editorConf:",Nf()),K("Syntro Bootstrap","SDK mode:",e??"normal"),!e&&typeof window<"u"){let w=!!window.__SYNTRO_EDITOR_PARAMS__,k=!!window.__SYNTRO_AUDIT_LEGEND__,T=!!window.__SYNTRO_REVIEW_DATA__;if(w||k||T){let D=[w&&"__SYNTRO_EDITOR_PARAMS__",k&&"__SYNTRO_AUDIT_LEGEND__",T&&"__SYNTRO_REVIEW_DATA__"].filter(Boolean);console.warn(`[Syntro Bootstrap] \u26A0 Mode detection returned null but mode-specific globals found: ${D.join(", ")}. This suggests URL params were lost (redirect?) but the service worker injected mode data. Check if replaceState failed or if page JS changed the URL before init().`)}}console.log(`[DIAG] Token resolution: options.token=${t.token?t.token.slice(0,15)+"...":"null"}`);let a=t.token;if(!a&&e){let k=Nf()?.syntro_token;k?.startsWith("syn_")&&(a=k,K("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${e} mode)`))}let n;if(a)if(a.startsWith("syn_"))K("Syntro Bootstrap","Token starts with syn_, decoding..."),n=lh(a),Fv(n.d);else if(e)K("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${e} mode)`);else throw Ff("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),Ff("Syntro Bootstrap","Token received:",a),new Error("Invalid Syntro token: must start with 'syn_'");else if(e)K("Syntro Bootstrap",`\u2713 No token, but ${e} mode - proceeding`);else throw Ff("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 r=pr("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||pr("VITE_SYNTRO_EXPERIMENT_HOST")||n?.eh,o=pr("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||pr("VITE_SYNTRO_TELEMETRY_HOST")||n?.th,i=pr("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||pr("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,s=J3(),l=aH(),u={...l,...s};K("Syntro Bootstrap","Phase 1: Browser metadata:",l),K("Syntro Bootstrap","Phase 1: Cached segment attributes:",s);let c,d=wc();console.log("[Syntro Bootstrap] EventBus created");let f=jb(w=>{d.publishEvent(w)}),h=w=>{K("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let k=tH(w);if(K("Syntro Bootstrap","Segment flags from PostHog:",k),eH(k),c){let T=x?.getAll?.()??{},D={...l,...T,...k};K("Syntro Bootstrap","Updating GrowthBook with attributes:",D),c.setAttributes?.(D)}},S;if(n?.t){let w=n.t==="noop"?"noop":"posthog";S=MT(w,{apiKey:n.t,apiHost:o,enableFeatureFlags:!0,onFeatureFlagsLoaded:h,onCapture:f}),console.log(`[Syntro Bootstrap] Telemetry client created (${w}) with EventBus wiring`)}let x;n?.e&&(c=kT("growthbook",{clientKey:n.e,apiHost:r,attributes:u,onExperimentViewed:S?.trackExperiment?(w,k,T)=>{S.trackExperiment(w,k,T)}:void 0})),x=Ey({experiments:c,onMetricChange:(w,k)=>{K("Syntro Bootstrap",`Session metric changed: ${w} = ${k}`)}}),K("Syntro Bootstrap","SessionMetricTracker created");let b="production";e==="editor"?b="editor":e==="audit"?b="audit":pr("NODE_ENV")==="development"&&(b="development");let m=i0({telemetry:S,sessionMetrics:x,mode:b,events:d});K("Syntro Bootstrap","Runtime created:",{version:m.version,mode:m.mode,hasContext:!!m.context,hasEvents:!!m.events,hasState:!!m.state}),K("Syntro Bootstrap","Core app executors already registered");let g=t.cdnBase||pr("NEXT_PUBLIC_SYNTRO_CDN_BASE")||pr("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",v=vv({cdnBase:g,registry:m.apps,onLoadStart:w=>{K("Syntro Bootstrap",`Loading app from CDN: ${w}`)},onLoadEnd:(w,k,T)=>{k?K("Syntro Bootstrap",`App loaded successfully: ${w}`):ya("Syntro Bootstrap",`Failed to load app: ${w}`,T)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:m.apps,runtime:m,version:m.version},K("Syntro Bootstrap","Global SynOS object exposed"));let y=m.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${y.length} apps in registry:`,y.map(w=>`${w.manifest.id}(${w.state})`).join(", "));for(let w of y)if(w.state==="registered")try{await m.apps.activate(w.manifest.id),console.log(`[DIAG] Activated: ${w.manifest.id} \u2192 widgets: [${m.widgets.list().join(", ")}]`)}catch(k){console.error(`[DIAG] FAILED to activate: ${w.manifest.id}`,k),ya("Syntro Bootstrap",`Failed to auto-activate built-in app: ${w.manifest.id}`,k)}if(console.log(`[DIAG] Activation complete. Total widgets: [${m.widgets.list().join(", ")}]`),c?.refreshFeatures)try{await c.refreshFeatures(),K("Syntro Bootstrap","GrowthBook features loaded")}catch(w){ya("Syntro Bootstrap","Failed to load GrowthBook features:",w)}let _;if(t.fetcher)_=t.fetcher;else if(n?.f){let w=TT(n.f,n.o??{});_=async()=>{let k=await w.fetch();return{...k.config,tiles:k.config.tiles??[]}}}else c&&(_=ys({experiments:c}));let L=new Set,C=_?async()=>{let w=await _();console.log("[Syntro Bootstrap] Config fetched:",`tiles=${w.tiles?.length??0},`,`actions=${w.actions?.length??0},`,`theme=${w.theme?.name??"none"}`),w.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",w.actions.map((D,M)=>`[${M}] ${D.kind}${D.anchorId?` anchor="${D.anchorId.selector}"`:""}${D.label?` "${D.label}"`:""}`).join(", "));let k=w,T=v.getRequiredApps(k);return T.length>0?console.log("[Syntro Bootstrap] Required external apps:",T.join(", ")):K("Syntro Bootstrap","No external apps required (all executors are built-in)"),T.length>0&&await v.loadAppsForConfig(k).then(async M=>{let P=M.filter(j=>j.success),F=M.filter(j=>!j.success);P.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${P.map(j=>j.appId).join(", ")}`);let U=F.filter(j=>!L.has(j.appId));U.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",U.map(j=>`${j.appId} (${j.error})`).join(", ")),U.forEach(j=>L.add(j.appId)));for(let j of T)if(m.apps.has(j))try{await m.apps.activate(j),console.log(`[Syntro Bootstrap] App activated: ${j}`)}catch(N){console.error(`[Syntro Bootstrap] Failed to activate app: ${j}`,N)}else console.error(`[Syntro Bootstrap] App "${j}" required by config but NOT registered.`,`Available apps: [${Array.from(m.apps.list?.()??[]).join(", ")}]`)}),w}:void 0;return{canvas:await uy({...t.canvas,fetcher:C,integrations:{experiments:c,telemetry:S},editorUrl:i,runtime:m}),runtime:m,experiments:c,telemetry:S,sessionMetrics:x,appLoader:v}}var OT={init:nH,encodeToken:c0,decodeToken:lh};typeof window<"u"&&(window.Syntro=OT);var BT="2026-03-12T07:44:11.886Z (4695ed48bd)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${BT}`);let t=window.SynOS,e=t?.appRegistry||lu;window.SynOS={...t,appRegistry:e,_runtimeBuild:BT,React:PT.default,ReactDOM:{...rH,createPortal:uh.createPortal,flushSync:uh.flushSync}},j1(e)}export{Ec as ANIMATION_KEYFRAMES,eh as ActivationConfigZ,VE as AddClassZ,za as AnchorIdZ,O3 as AnchorStateZ,Ib as AnchorVisibleConditionZ,kf as AppRegistry,B3 as AugmentationZ,DE as BadgePositionZ,YE as BadgeZ,D3 as BoundingBoxZ,gu as CanvasEvents,Dy as CanvasRecipeZ,So as ConditionZ,th as ContextManager,Db as CooldownActiveConditionZ,vc as CounterDefZ,Nb as CtaButtonZ,Gv as DEFAULT_COOLDOWN,jv as DEFAULT_TTL,_c as DecisionStrategyZ,Mb as DismissedConditionZ,Cs as EVENT_SCHEMA_VERSION,rh as EventBus,Bb as EventCountConditionZ,z3 as EventFilterZ,Ab as EventOccurredConditionZ,gT as EventSourceZ,Qp as ExecutorRegistry,Cc as ExternalStrategyZ,G3 as FrequencyEntryZ,Ob as FrequencyLimitConditionZ,xN as HighlightStepZ,ME as HighlightStyleZ,WE as HighlightZ,ZE as InsertHtmlZ,FE as InsertPositionZ,Vv as MAX_VISIBLE_TOASTS,gc as MatchOpZ,PE as ModalContentZ,QE as ModalZ,Sc as ModelStrategyZ,tT as MountWidgetZ,eT as NavigateZ,Lc as NavigationMonitor,U3 as NormalizedEventZ,$v as NotificationToastStack,E3 as PageContextZ,T3 as PageHistoryEntryZ,Lb as PageUrlConditionZ,rT as ParallelZ,OE as PlacementZ,XE as PulseZ,BT as RUNTIME_SDK_BUILD,wT as RUNTIME_VERSION,jE as RemoveClassZ,kb as RouteConditionZ,RE as RouteFilterZ,xc as RuleStrategyZ,yc as RuleZ,P3 as RuntimeContextZ,Kv as RuntimeProvider,Zr as SDK_SCHEMA_VERSION,Nv as SDK_VERSION,bT as STATIC_SLOT_STYLES,bc as ScoreStrategyZ,zE as ScrollBehaviorZ,Fb as ScrollLogicalPositionZ,JE as ScrollToZ,LI as SelectorZ,nT as SequenceZ,R3 as SessionContextZ,Rb as SessionMetricConditionZ,dp as SessionMetricTracker,$E as SetAttrZ,GE as SetStyleZ,qE as SetTextZ,bk as ShadowCanvasOverlay,ik as ShadowRootProvider,wk as SmartCanvasApp,Uv as SmartCanvasController,sy as SmartCanvasElement,Z$ as SmartCanvasPortal,we as StandardEvents,Eb as StateEqualsConditionZ,oh as StateStore,j3 as StoredValueZ,OT as Syntro,Ru as TileCard,P6 as TileWheel,BE as TooltipContentZ,yN as TooltipStepZ,NE as TooltipTriggerZ,KE as TooltipZ,UE as TourStepForSchemaZ,oT as TourZ,Jp as TriggerWhenZ,Tb as ViewportConditionZ,M3 as ViewportContextZ,aT as WaitZ,HE as WidgetConfigZ,sh as WidgetRegistry,lu as appRegistry,Yb as applyStaticSlotStyles,mv as cleanupAppContext,tv as contentRuntime,I3 as coreActionStepSchemas,wb as createActionEngine,Hb as createAnchorResolver,hv as createAppContext,vv as createAppLoader,ys as createCanvasConfigFetcher,zb as createContextManager,qb as createDecisionEngine,$b as createEventAccumulator,wc as createEventBus,Ay as createGrowthBookClient,By as createNoopClient,j$ as createOverlayRecipeFetcher,yb as createPostHogClient,jb as createPostHogNormalizer,Ey as createSessionMetricTracker,uy as createSmartCanvas,rk as createSmartCanvasController,i0 as createSmartCanvasRuntime,Xb as createStateStore,t0 as createSurfaceContainer,n0 as createSurfaces,DV as decisionSchemas,lh as decodeToken,c0 as encodeToken,cT as evaluate,sT as evaluateCondition,lT as evaluateRule,ah as evaluateRuleStrategy,nh as evaluateScoreStrategy,dT as evaluateSync,fr as executorRegistry,XO as getAntiFlickerSnippet,f1 as getAppIdFromActionKind,gv as getAppIdFromWidgetId,K4 as getExecutor,ih as getSlotAnchorId,Ac as getSlotType,a0 as getSlotZIndex,Cb as hasExecutor,jf as interpolateTemplate,d1 as isCoreActionKind,Zv as matchEvent,U6 as needsMigration,hT as normalizePostHogEvent,pv as overlaysRuntime,Mu as parseVersion,Jb as playEnterAnimation,e0 as playExitAnimation,Uf as registerConfigPredicates,Ak as registerSmartCanvasElement,Hv as resolveConfigUri,Kb as setupAdjacentPositioning,Qb as setupInlinePositioning,mT as shouldNormalizeEvent,QB as useDecision,Wv as useNotifications,Xv as useNotifyWatcher,Qv as usePageContext,Yn as useRuntime,Zf as useRuntimeContext,YB as useRuntimeEvents,KB as useRuntimeState,WB as useSessionContext,Ck as useShadowCanvasConfig,Ss as useShadowRoot,XB as useViewportContext,bo as validateAction,_b as validateActions,MV as validateActivationConfig,TV as validateCondition,H6 as validateConfig,k8 as validateEventFilter,T9 as validateFrequencyEntry,L8 as validateNormalizedEvent,z$ as validateRecipe,t8 as validateRuntimeContext,E9 as validateStoredValue,RV as validateStrategy,r0 as widgetRegistry};
|
|
519
|
+
`)),new Error(`Batch validation failed: ${M}`)}let w=f(),k=[],T=[];try{for(let M of C){let P=await g(M);k.push(P),T.push(P)}}catch(M){console.error(`[ActionEngine] Batch apply FAILED at action ${T.length+1}/${C.length}.`,`Successfully applied: ${T.length}. Rolling back...`,M);for(let P of T)try{await P.revert()}catch{}throw M}return{id:w,handles:k,async revertAll(){for(let M=k.length-1;M>=0;M--)try{await k[M].revert()}catch(P){console.error(`[ActionEngine] Error reverting action ${k[M].id}:`,P)}},isApplied(){return k.every(M=>M.isApplied())}}}function y(C){return bo(C)}function _(){return Array.from(c.values()).map(C=>({id:C.id,action:C.action,adaptiveId:C.adaptiveId,appliedTs:C.appliedTs,state:C.state}))}function L(){for(let C of d.values())for(let I of C)try{I()}catch{}d.clear();for(let C of c.values())if(C.state==="applied")try{C.cleanup()}catch(I){console.error("[ActionEngine] Error during cleanup:",I)}c.clear()}return{apply:g,applyBatch:v,validate:y,getActive:_,destroy:L}}var h3=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),Lb=p.object({type:p.literal("page_url"),url:p.string()}),kb=p.object({type:p.literal("route"),routeId:p.string()}),Ib=p.object({type:p.literal("anchor_visible"),anchorId:p.string(),state:p.enum(["visible","present","absent"])}),Ab=p.object({type:p.literal("event_occurred"),eventName:p.string(),withinMs:p.number().optional()}),Eb=p.object({type:p.literal("state_equals"),key:p.string(),value:p.unknown()}),Tb=p.object({type:p.literal("viewport"),minWidth:p.number().optional(),maxWidth:p.number().optional(),minHeight:p.number().optional(),maxHeight:p.number().optional()}),Rb=p.object({type:p.literal("session_metric"),key:p.string(),operator:p.enum(["gte","lte","eq","gt","lt"]),threshold:p.number()}),Mb=p.object({type:p.literal("dismissed"),key:p.string(),inverted:p.boolean().optional()}),Db=p.object({type:p.literal("cooldown_active"),key:p.string(),inverted:p.boolean().optional()}),Ob=p.object({type:p.literal("frequency_limit"),key:p.string(),limit:p.number(),inverted:p.boolean().optional()}),gc=p.object({equals:p.union([p.string(),p.number(),p.boolean()]).optional(),contains:p.string().optional()}),vc=p.object({events:p.array(p.string()).min(1),match:p.record(p.string(),gc).optional()}),Bb=p.object({type:p.literal("event_count"),key:p.string(),operator:p.enum(["gte","lte","eq","gt","lt"]),count:p.number().int().min(0),withinMs:p.number().positive().optional(),counter:vc.optional()}),So=p.discriminatedUnion("type",[Lb,kb,Ib,Ab,Eb,Tb,Rb,Mb,Db,Ob,Bb]),yc=p.object({conditions:p.array(So),value:p.unknown()}),xc=p.object({type:p.literal("rules"),rules:p.array(yc),default:p.unknown()}),bc=p.object({type:p.literal("score"),field:p.string(),threshold:p.number(),above:p.unknown(),below:p.unknown()}),Sc=p.object({type:p.literal("model"),modelId:p.string(),inputs:p.array(p.string()),outputMapping:p.record(p.string(),p.unknown()),default:p.unknown()}),Cc=p.object({type:p.literal("external"),endpoint:p.string(),method:p.enum(["GET","POST"]).optional(),default:p.unknown(),timeoutMs:p.number().optional()}),_c=p.discriminatedUnion("type",[xc,bc,Sc,Cc]),Jp=_c.nullable().optional(),m3=p.object({events:p.array(p.string()),urlContains:p.string().optional(),props:p.record(p.union([p.string(),p.number(),p.boolean()])).optional()}),g3=p.object({title:p.string().optional(),body:p.string().optional(),icon:p.string().optional()}).nullable().optional();var RE=p.object({include:p.array(p.string()).optional().describe("URL patterns where this tile appears. Supports *, **, :param wildcards. Use sparingly \u2014 mostly to isolate to specific webapp functionality. Omit to appear on all routes."),exclude:p.array(p.string()).optional().describe("URL patterns where this tile should NOT appear. Evaluated before include.")}),eh=p.object({routes:RE,onlyIfPopulated:p.boolean().optional().describe("When true, tile is hidden if none of its props.actions[] have an active triggerWhen. Useful for tiles with all-deferred FAQ questions or nav tips. Default: false.")});function TV(t){return So.safeParse(t)}function RV(t){return _c.safeParse(t)}function MV(t){return eh.safeParse(t)}var DV=[{defName:"matchOp",schema:gc},{defName:"counterDef",schema:vc},{defName:"activationConfig",schema:eh},{defName:"routeFilter",schema:RE},{defName:"ruleStrategy",schema:xc},{defName:"scoreStrategy",schema:bc},{defName:"modelStrategy",schema:Sc},{defName:"externalStrategy",schema:Cc},{defName:"rule",schema:yc},{defName:"condition",schema:So}];var Pb=p.object({tileId:p.string(),itemId:p.string().optional()}).strict(),v3=p.object({on:p.string(),title:p.string(),body:p.string().optional(),icon:p.string().optional(),ttl:p.number().optional(),cooldown:p.number().optional(),deepLink:Pb.optional()}).strict(),y3=p.object({id:p.string(),title:p.string().optional(),subtitle:p.string().optional(),icon:p.string().optional(),priority:p.number().optional(),widget:p.string(),props:p.record(p.unknown()).optional(),activation:eh.optional(),notifications:p.array(v3).optional()}).strict(),x3=p.object({position:p.enum(["left","right"]).optional(),layout:p.enum(["overlay","push"]).optional(),background:p.string().optional(),blur:p.string().optional(),border:p.string().optional(),width:p.string().optional(),transitionDuration:p.string().optional(),transitionEasing:p.string().optional(),transitionFade:p.string().optional()}),b3=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),color:p.string().optional(),size:p.string().optional(),shadow:p.string().optional(),borderRadius:p.string().optional()}),S3=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),shadow:p.string().optional(),titleColor:p.string().optional(),textColor:p.string().optional(),iconBackground:p.string().optional(),iconShadow:p.string().optional(),headerPadding:p.string().optional(),bodyPadding:p.string().optional(),gap:p.string().optional()}),C3=p.object({background:p.string().optional(),textColor:p.string().optional(),titleColor:p.string().optional(),arrowColor:p.string().optional(),arrowSize:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),scrimOpacity:p.string().optional(),highlightRing:p.string().optional()}),_3=p.object({background:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),successColor:p.string().optional(),warningColor:p.string().optional(),errorColor:p.string().optional(),iconBackground:p.string().optional(),progressGradient:p.string().optional()}),w3=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),itemDivider:p.string().optional(),itemGap:p.string().optional(),itemPadding:p.string().optional(),itemFontSize:p.string().optional(),bodyPadding:p.string().optional(),bodyFontSize:p.string().optional(),categoryPadding:p.string().optional(),categoryGap:p.string().optional(),categoryFontSize:p.string().optional(),searchBackground:p.string().optional(),searchColor:p.string().optional(),chevronColor:p.string().optional()}),L3=p.object({mode:p.enum(["dark","light"]).optional(),fontFamily:p.string().optional(),colorPrimary:p.string().optional(),colorPrimaryHover:p.string().optional(),borderRadius:p.string().optional(),canvas:x3.optional(),launcher:b3.optional(),tile:S3.optional(),overlay:C3.optional(),notification:_3.optional(),content:w3.optional()}).strict(),k3=p.object({enabled:p.boolean().optional(),label:p.string().optional(),icon:p.string().optional(),position:p.string().optional(),animate:p.boolean().optional(),animationStyle:p.enum(["pulse","bounce","glow"]).optional(),notificationCount:p.number().optional()}).strict(),NV=p.object({schemaVersion:p.string().optional(),fetchedAt:p.string().datetime(),configVersion:p.string().optional(),canvasTitle:p.string().optional(),tiles:p.array(y3),actions:p.array(p.any()),theme:L3.optional(),launcher:k3.optional(),meta:p.object({verificationSteps:p.array(p.union([p.string(),p.object({text:p.string(),check:So.optional()})])).optional()}).passthrough().optional()}).strict();var xt={triggerWhen:Jp},za=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),ME=p.object({color:p.string().optional(),scrimOpacity:p.number().min(0).max(1).optional(),paddingPx:p.number().optional(),radiusPx:p.number().optional()}).strict(),DE=p.enum(["top-left","top-right","bottom-left","bottom-right"]),OE=p.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),Nb=p.object({label:p.string(),actionId:p.string(),primary:p.boolean().optional()}).strict(),BE=p.object({title:p.string().optional(),body:p.string(),ctaButtons:p.array(Nb).optional()}).strict(),PE=p.object({title:p.string().optional(),body:p.string()}).strict(),FE=p.enum(["before","after","prepend","append","replace"]),NE=p.enum(["immediate","hover","click"]),HE=p.object({widgetId:p.string(),props:p.record(p.unknown()).optional(),priority:p.number().optional()}).strict(),UE=p.object({id:p.string(),action:p.any(),route:p.string().optional(),onAction:p.record(p.string()).optional()}).passthrough(),zE=p.enum(["auto","smooth","instant"]),Fb=p.enum(["start","center","end","nearest"]),qE=p.object({kind:p.literal("content:setText"),anchorId:za,text:p.string(),label:p.string().optional()}).extend(xt).strict(),$E=p.object({kind:p.literal("content:setAttr"),anchorId:za,attr:p.string(),value:p.string(),label:p.string().optional()}).extend(xt).strict(),VE=p.object({kind:p.literal("content:addClass"),anchorId:za,className:p.string(),label:p.string().optional()}).extend(xt).strict(),jE=p.object({kind:p.literal("content:removeClass"),anchorId:za,className:p.string(),label:p.string().optional()}).extend(xt).strict(),GE=p.object({kind:p.literal("content:setStyle"),anchorId:za,styles:p.record(p.string()),label:p.string().optional()}).extend(xt).strict(),ZE=p.object({kind:p.literal("content:insertHtml"),anchorId:za,html:p.string(),position:FE,deepLink:Pb.optional(),label:p.string().optional()}).extend(xt).strict(),WE=p.object({kind:p.literal("overlays:highlight"),anchorId:za,style:ME.optional(),duration:p.number().optional(),label:p.string().optional()}).extend(xt).strict(),XE=p.object({kind:p.literal("overlays:pulse"),anchorId:za,duration:p.number().optional(),label:p.string().optional()}).extend(xt).strict(),YE=p.object({kind:p.literal("overlays:badge"),anchorId:za,content:p.string(),position:DE.optional(),label:p.string().optional()}).extend(xt).strict(),KE=p.object({kind:p.literal("overlays:tooltip"),anchorId:za,content:BE,trigger:NE.optional(),placement:OE.optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(xt).strict(),QE=p.object({kind:p.literal("overlays:modal"),content:PE,size:p.enum(["sm","md","lg"]).optional(),blocking:p.boolean().optional(),scrim:p.object({opacity:p.number().min(0).max(1).optional()}).strict().optional(),dismiss:p.object({onEsc:p.boolean().optional(),closeButton:p.boolean().optional(),timeoutMs:p.number().min(0).optional()}).strict().optional(),ctaButtons:p.array(Nb).optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(xt).strict(),JE=p.object({kind:p.literal("navigation:scrollTo"),anchorId:za,behavior:zE.optional(),block:Fb.optional(),inline:Fb.optional(),label:p.string().optional()}).extend(xt).strict(),eT=p.object({kind:p.literal("navigation:navigate"),url:p.string(),target:p.enum(["_self","_blank"]).optional(),label:p.string().optional()}).extend(xt).strict(),tT=p.object({kind:p.literal("core:mountWidget"),slot:p.string(),widget:HE,label:p.string().optional()}).extend(xt).strict(),aT=p.object({kind:p.literal("core:wait"),durationMs:p.number().min(0).optional(),event:p.string().optional(),label:p.string().optional()}).extend(xt).strict(),nT=p.object({kind:p.literal("core:sequence"),actions:p.array(p.any()),label:p.string().optional()}).extend(xt).strict(),rT=p.object({kind:p.literal("core:parallel"),actions:p.array(p.any()),waitFor:p.enum(["all","any"]).optional(),label:p.string().optional()}).extend(xt).strict(),oT=p.object({kind:p.literal("core:tour"),tourId:p.string(),steps:p.array(UE).min(1),startStep:p.string().optional(),autoStart:p.boolean().optional(),label:p.string().optional()}).extend(xt).passthrough(),I3=[{defName:"setText",schema:qE},{defName:"setAttr",schema:$E},{defName:"addClass",schema:VE},{defName:"removeClass",schema:jE},{defName:"setStyle",schema:GE},{defName:"insertHtml",schema:ZE},{defName:"highlight",schema:WE},{defName:"pulse",schema:XE},{defName:"badge",schema:YE},{defName:"tooltip",schema:KE},{defName:"modal",schema:QE},{defName:"scrollTo",schema:JE},{defName:"navigate",schema:eT},{defName:"mountWidget",schema:tT},{defName:"wait",schema:aT},{defName:"sequence",schema:nT},{defName:"parallel",schema:rT},{defName:"tour",schema:oT}];function Hb(t){let e=t?.root??(typeof document<"u"?document.body:null),a=t?.defaultTimeoutMs??5e3,n=new Map,r=new Map,o=null,i=!1;function s(b){if(!e)return null;try{return e.matches(b)?e:e.querySelector(b)}catch{return null}}function l(){for(let[b,m]of n){let g=s(b);if(g){for(let v of m)clearTimeout(v.timer),v.resolve(g);n.delete(b)}}for(let[b,m]of r){let g=s(b);if(g){for(let v of m)v.cancelled||v.cb(g);r.delete(b)}}n.size===0&&r.size===0&&c()}function u(){o||i||typeof MutationObserver>"u"||!e||(o=new MutationObserver(()=>{l()}),o.observe(e,{childList:!0,subtree:!0}))}function c(){o&&(o.disconnect(),o=null)}function d(b,m){let g=n.get(b);g&&(g.delete(m),g.size===0&&n.delete(b)),n.size===0&&r.size===0&&c()}function f(b,m){if(i)return Promise.reject(new Error("AnchorResolver destroyed"));let g=s(b);if(g)return Promise.resolve(g);let v=m??a;return new Promise((y,_)=>{let L={resolve:y,reject:_,timer:setTimeout(()=>{d(b,L),_(new Error(`waitFor("${b}") timed out after ${v}ms`))},v)},C=n.get(b);C||(C=new Set,n.set(b,C)),C.add(L),u()})}function h(b,m){if(i)return()=>{};let g=s(b);if(g)return m(g),()=>{};let v={cb:m,cancelled:!1},y=r.get(b);return y||(y=new Set,r.set(b,y)),y.add(v),u(),()=>{v.cancelled=!0;let _=r.get(b);_&&(_.delete(v),_.size===0&&r.delete(b)),n.size===0&&r.size===0&&c()}}function S(){let b=0;for(let m of n.values())b+=m.size;return b}function x(){i=!0,c();let b=new Error("AnchorResolver destroyed");for(let m of n.values())for(let g of m)clearTimeout(g.timer),g.reject(b);n.clear(),r.clear()}return{resolve:s,waitFor:f,onAppear:h,pendingCount:S,destroy:x}}function A3(){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 Ub(t,e){if(!e)return;let a;try{a=new URL(t).pathname}catch{a=t}if(e.exclude){for(let n of e.exclude)if(iT(a,n))return}if(e.include){for(let n of e.include)if(iT(a,n))return n;return}return a}function iT(t,e){let a=t.replace(/\/$/,"")||"/",n=e.replace(/\/$/,"")||"/";if(a===n)return!0;let r=n.replace(/:[^/]+/g,"[^/]+").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(a)}var th=class{constructor(e){B(this,"context");B(this,"previousContext");B(this,"listeners",new Set);B(this,"telemetry");B(this,"routes");B(this,"navigation");B(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=A3(),this.previousContext={...this.context},e.telemetry?.getSessionId){let a=e.telemetry.getSessionId();a&&(this.context.session.sessionId=a)}e.initialPageHistory&&(this.context.session.pageHistory=e.initialPageHistory),this.context.page.routeId=Ub(this.context.page.url,this.routes),this.addPageToHistory(this.context.page.url),typeof window<"u"&&this.setupBrowserListeners()}get(){return{...this.context}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setRoutes(e){this.routes=e;let a=Ub(this.context.page.url,this.routes);a!==this.context.page.routeId&&this.updateContext({page:{...this.context.page,routeId:a}})}setAnchors(e){this.updateContext({anchors:e})}setSessionId(e){e!==this.context.session.sessionId&&this.updateContext({session:{...this.context.session,sessionId:e}})}destroy(){for(let e of this.cleanupFns)e();this.cleanupFns=[],this.listeners.clear()}setupBrowserListeners(){let e,a=()=>{clearTimeout(e),e=setTimeout(()=>{this.updateViewport()},100)};window.addEventListener("resize",a),this.cleanupFns.push(()=>window.removeEventListener("resize",a));let n=this.navigation.subscribe(()=>this.updatePage());this.cleanupFns.push(n)}updateViewport(){let e={width:window.innerWidth,height:window.innerHeight};(e.width!==this.context.viewport.width||e.height!==this.context.viewport.height)&&this.updateContext({viewport:e})}updatePage(){let e=window.location.href,{title:a}=document,n=Ub(e,this.routes),r={url:e,title:a,routeId:n};(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 a={url:e,ts:Date.now()},n=[...this.context.session.pageHistory||[],a];n.length>50&&n.shift(),this.context.session.pageHistory=n}updateContext(e){this.previousContext={...this.context},this.context={...this.context,...e},this.notifyListeners()}notifyListeners(){for(let e of this.listeners)try{e(this.context,this.previousContext)}catch(a){console.error("[ContextManager] Listener error:",a)}}};function zb(t){return new th(t)}var E3=p.object({url:p.string(),routeId:p.string().optional(),title:p.string().optional(),locale:p.string().optional()}),T3=p.object({url:p.string(),ts:p.number()}),R3=p.object({sessionId:p.string(),startTs:p.number(),pageHistory:p.array(T3).optional()}),M3=p.object({width:p.number(),height:p.number()}),D3=p.object({x:p.number(),y:p.number(),w:p.number(),h:p.number()}),O3=p.object({anchorId:p.string(),present:p.boolean(),visible:p.boolean().optional(),boundingBox:D3.optional()}),B3=p.record(p.string(),p.union([p.number(),p.string(),p.boolean(),p.undefined()])),P3=p.object({page:E3,session:R3,viewport:M3,anchors:p.array(O3).optional(),augmented:B3.optional()});function t8(t){return P3.safeParse(t)}function sT(t,e){let{context:a,state:n,events:r}=e;switch(t.type){case"page_url":{let{url:o}=t,i=a.page.url.split("?")[0].split("#")[0],s=o.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*");return new RegExp(`^${s}$`).test(i)}case"route":return a.page.routeId===t.routeId;case"anchor_visible":{let o=a.anchors?.find(i=>i.anchorId===t.anchorId);switch(t.state){case"visible":return o?.visible===!0;case"present":return o?.present===!0;case"absent":return!o?.present;default:return!1}}case"event_occurred":{if(!r)return!1;let o=t.withinMs??6e4;return r.hasRecentEvent(t.eventName,o)}case"state_equals":return n?.getValue?n.getValue(t.key)===t.value:!1;case"viewport":{let{width:o,height:i}=a.viewport;return!(t.minWidth!==void 0&&o<t.minWidth||t.maxWidth!==void 0&&o>t.maxWidth||t.minHeight!==void 0&&i<t.minHeight||t.maxHeight!==void 0&&i>t.maxHeight)}case"session_metric":{if(!n)return!1;let o=n.getSessionMetric(t.key),{operator:i,threshold:s}=t;switch(i){case"gte":return o>=s;case"lte":return o<=s;case"eq":return o===s;case"gt":return o>s;case"lt":return o<s;default:return!1}}case"dismissed":{if(!n)return t.inverted??!1;let o=n.isDismissed(t.key);return t.inverted?!o:o}case"cooldown_active":{if(!n)return t.inverted??!1;let o=n.isCooldownActive(t.key);return t.inverted?!o:o}case"frequency_limit":{if(!n)return t.inverted??!1;let i=n.getFrequencyCount(t.key)>=t.limit;return t.inverted?!i:i}case"event_count":{if(!e.accumulator)return!1;let o=t,i=e.accumulator.getCount(o.key,o.withinMs);switch(o.operator){case"gte":return i>=o.count;case"lte":return i<=o.count;case"eq":return i===o.count;case"gt":return i>o.count;case"lt":return i<o.count;default:return!1}}default:return console.warn("[RuleStrategy] Unknown condition type:",t.type),!1}}function lT(t,e){let a=[];for(let n of t.conditions){let r=sT(n,e);if(a.push({condition:n,result:r}),!r)return{matched:!1,conditionResults:a}}return{matched:!0,conditionResults:a}}function ah(t,e){for(let a=0;a<t.rules.length;a++){let n=t.rules[a],{matched:r,conditionResults:o}=lT(n,e);if(r)return{value:n.value,isFallback:!1,matchInfo:{strategyType:"rules",matchedRuleIndex:a,evaluatedConditions:o}}}return{value:t.default,isFallback:!0,matchInfo:{strategyType:"rules"}}}function nh(t,e){let{context:a}=e,n=a.augmented?.[t.field];return n===void 0||typeof n!="number"?{value:t.below,isFallback:!0,matchInfo:{strategyType:"score"}}:{value:n>=t.threshold?t.above:t.below,isFallback:!1,matchInfo:{strategyType:"score"}}}function uT(t,e){let{state:a,events:n,sessionMetrics:r,accumulator:o}=e;return{context:t,state:a?{isDismissed:i=>a.dismissals.isDismissed(i),isCooldownActive:i=>a.cooldowns.isActive(i),getFrequencyCount:i=>a.frequency.count(i),getSessionMetric:i=>r?.get(i)??0,getValue:i=>a.session.get(i)??a.user.get(i)}:void 0,events:n?{hasRecentEvent:(i,s)=>n.hasRecentEvent(i,s)}:void 0,accumulator:o?{getCount:(i,s)=>o.getCount(i,s)}:void 0}}async function cT(t,e,a={}){let n=uT(e,a);switch(t.type){case"rules":return ah(t,n);case"score":return nh(t,n);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 dT(t,e,a={}){let n=uT(e,a);switch(t.type){case"rules":return ah(t,n);case"score":return nh(t,n);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 qb(t){return{evaluate:(e,a)=>cT(e,a,t),evaluateSync:(e,a)=>dT(e,a,t)}}function $b(t){let{eventBus:e,stateStore:a}=t,n=new Map,r=new Set,o=null,i=a.ns("accumulator");function s(u){let c=!1;for(let d of n.values()){if(!d.predicate(u))continue;let f=i.get(d.stateKey)||{count:0};f.count++,d.needsTimestamps&&(f.timestamps||(f.timestamps=[]),f.timestamps.push(u.ts),f.timestamps.length>200&&(f.timestamps=f.timestamps.slice(-200))),i.set(d.stateKey,f),c=!0}if(c)for(let d of r)try{d()}catch(f){console.error("[EventAccumulator] Subscriber error:",f)}}function l(){o||n.size===0||(o=e.subscribe(s))}return{register(u,c,d=!1){let f=`ev:${u}`,h=n.get(f);if(h){d&&!h.needsTimestamps&&(h.needsTimestamps=!0);return}n.set(f,{stateKey:f,needsTimestamps:d,predicate:c}),l()},getCount(u,c){let d=`ev:${u}`,f=i.get(d);if(!f)return 0;if(c===void 0||!f.timestamps)return f.count;let h=Date.now()-c;return f.timestamps.filter(S=>S>=h).length},subscribe(u){return r.add(u),()=>{r.delete(u)}},destroy(){o&&(o(),o=null),n.clear(),r.clear()}}}function Vb(t,e){return e?!(e.names&&e.names.length>0&&!e.names.includes(t.name)||e.patterns&&e.patterns.length>0&&!e.patterns.some(n=>{try{return new RegExp(n).test(t.name)}catch{return!1}})||e.sources&&e.sources.length>0&&!e.sources.includes(t.source)):!0}var rh=class{constructor(e={}){B(this,"subscriptions",new Set);B(this,"history",[]);B(this,"maxHistorySize");this.maxHistorySize=e.maxHistorySize??100}subscribe(e,a){let n,r;typeof e=="function"?(n=void 0,r=e):(n=e,r=a);let o={filter:n,callback:r};return this.subscriptions.add(o),()=>{this.subscriptions.delete(o)}}publish(e,a,n="canvas"){let r={ts:Date.now(),name:e,source:n,props:a,schemaVersion:Cs};this.publishEvent(r)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let a of this.subscriptions)if(Vb(e,a.filter))try{a.callback(e)}catch(n){console.error("[EventBus] Subscriber error:",n)}}getRecent(e,a){let n=this.history;return e&&(n=n.filter(r=>Vb(r,e))),a&&a>0&&(n=n.slice(-a)),n}hasRecentEvent(e,a,n){let r=Date.now()-a;return this.history.some(o=>o.name===e&&o.ts>=r&&(n===void 0||o.source===n))}countRecentEvents(e,a){let n=this.history.filter(r=>Vb(r,e));if(a!==void 0){let r=Date.now()-a;n=n.filter(o=>o.ts>=r)}return n.length}clearHistory(){this.history=[]}getSubscriberCount(){return this.subscriptions.size}};function wc(t={}){return new rh(t)}var fT={$click:we.UI_CLICK,$scroll:we.UI_SCROLL,$input:we.UI_INPUT,$change:we.UI_CHANGE,$submit:we.UI_SUBMIT,$pageview:we.NAV_PAGE_VIEW,$pageleave:we.NAV_PAGE_LEAVE,$session_start:"session.start",$identify:"user.identify"};function F3(t){let e=t.event;if(typeof e!="string")return"posthog.unknown";if(fT[e])return fT[e];if(e==="$autocapture"){let a=t.properties?.$tag_name,n=t.properties?.$event_type;return n==="submit"?we.UI_SUBMIT:n==="change"?we.UI_CHANGE:a==="input"||a==="textarea"?we.UI_INPUT:we.UI_CLICK}return e.startsWith("$")?e.replace("$","posthog."):`posthog.${e}`}var pT=new Set(["a","button","input","select","textarea"]);function N3(t,e){if(e&&pT.has(e)||!t)return e;for(let a of t){let n=a.tag_name;if(n&&pT.has(n))return n}return e}function H3(t){let e={},a=t.properties||{},n=a.$elements,r=a.$tag_name??n?.[0]?.tag_name,o=t.event==="$autocapture"||t.event==="$click";return e.tagName=o?N3(n,r):r,a.$el_text&&(e.elementText=a.$el_text),n&&(e.elements=n),a.$current_url&&(e.url=a.$current_url),a.$pathname&&(e.pathname=a.$pathname),a.$host&&(e.host=a.$host),a.$viewport_width&&(e.viewportWidth=a.$viewport_width),a.$viewport_height&&(e.viewportHeight=a.$viewport_height),a.$session_id&&(e.sessionId=a.$session_id),a.$scroll_depth&&(e.scrollDepth=a.$scroll_depth),a.$scroll_percentage&&(e.scrollPercentage=a.$scroll_percentage),e.originalEvent=t.event,e}function hT(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:F3(t),source:"posthog",props:H3(t),schemaVersion:Cs}}function mT(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 jb(t){return(e,a)=>{if(typeof e!="string")return;let n={event:e,properties:a,timestamp:Date.now()};if(mT(n)){let r=hT(n);t(r)}}}var gT=p.enum(["posthog","canvas","derived"]),U3=p.object({ts:p.number(),name:p.string(),source:gT,props:p.record(p.string(),p.unknown()).optional(),schemaVersion:p.string()}),z3=p.object({names:p.array(p.string()).optional(),patterns:p.array(p.string()).optional(),sources:p.array(gT).optional()});function L8(t){return U3.safeParse(t)}function k8(t){return z3.safeParse(t)}var Lc=class{constructor(){B(this,"listeners",new Set);B(this,"capturedPushState");B(this,"capturedReplaceState");B(this,"wasNative");B(this,"destroyed",!1);B(this,"onPopState",()=>{this.notify(window.location.href,"popstate")});this.wasNative=this.isNativeFunction(history.pushState),this.capturedPushState=history.pushState,this.capturedReplaceState=history.replaceState,history.pushState=(...e)=>{this.capturedPushState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"pushState"))},history.replaceState=(...e)=>{this.capturedReplaceState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"replaceState"))},window.addEventListener("popstate",this.onPopState)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}diagnose(){return{isNative:this.wasNative,subscriberCount:this.listeners.size}}destroy(){this.destroyed||(this.destroyed=!0,history.pushState=this.capturedPushState,history.replaceState=this.capturedReplaceState,window.removeEventListener("popstate",this.onPopState),this.listeners.clear())}notify(e,a){if(!this.destroyed)for(let n of this.listeners)try{n(e,a)}catch{}}isNativeFunction(e){try{return Function.prototype.toString.call(e).includes("[native code]")}catch{return!1}}};var Gb="cooldown:";function vT(t){return{set(e,a){let n=Gb+e,r=Date.now()+a;t.set(n,r)},isActive(e){return this.remaining(e)>0},remaining(e){let a=Gb+e,n=t.get(a);if(n===void 0)return 0;let r=n-Date.now();return r<=0?(t.remove(a),0):r},clear(e){let a=Gb+e;t.remove(a)}}}var kc="dismissed:";function yT(t,e){return{mark(a,n=!1){let r=kc+a;(n?e:t).set(r,!0)},isDismissed(a){let n=kc+a;return t.has(n)||e.has(n)},clear(a){let n=kc+a;t.remove(n),e.remove(n)},clearAll(){for(let a of t.keys())a.startsWith(kc)&&t.remove(a);for(let a of e.keys())a.startsWith(kc)&&e.remove(a)}}}var Zb="freq:";function xT(t){function e(a){let n=Zb+a,r=t.get(n);if(r){if(r.resetAt&&Date.now()>=r.resetAt){t.remove(n);return}return r}}return{increment(a,n){let r=Zb+a,o=e(a),i=(o?.count??0)+1,s={count:i,resetAt:o?.resetAt??(n?Date.now()+n:void 0)};return t.set(r,s),i},count(a){return e(a)?.count??0},reset(a){let n=Zb+a;t.remove(n)},hasReachedLimit(a,n){return this.count(a)>=n}}}var q3="syntro";function Wb(t,e){let a=`${e}:`;return{get(n){if(t)try{let r=t.getItem(a+n);if(!r)return;let o=JSON.parse(r);if(o.expiresAt&&Date.now()>=o.expiresAt){t.removeItem(a+n);return}return o.value}catch{return}},set(n,r,o){if(t)try{let i={value:r,expiresAt:o?Date.now()+o:void 0};t.setItem(a+n,JSON.stringify(i))}catch(i){console.warn("[StateStore] Failed to save:",i)}},remove(n){t&&t.removeItem(a+n)},has(n){return t?this.get(n)!==void 0:!1},keys(){if(!t)return[];let n=[];for(let r=0;r<t.length;r++){let o=t.key(r);o?.startsWith(a)&&n.push(o.slice(a.length))}return n},clear(){if(!t)return;let n=this.keys();for(let r of n)t.removeItem(a+r)}}}function Ic(t){let e=new Map,a=`${t}:`;return{get(n){let r=e.get(a+n);if(r){if(r.expiresAt&&Date.now()>=r.expiresAt){e.delete(a+n);return}return r.value}},set(n,r,o){e.set(a+n,{value:r,expiresAt:o?Date.now()+o:void 0})},remove(n){e.delete(a+n)},has(n){return this.get(n)!==void 0},keys(){let n=[];for(let r of e.keys())r.startsWith(a)&&n.push(r.slice(a.length));return n},clear(){for(let n of e.keys())n.startsWith(a)&&e.delete(n)}}}var oh=class{constructor(e={}){B(this,"session");B(this,"user");B(this,"dismissals");B(this,"cooldowns");B(this,"frequency");B(this,"namespace");B(this,"namespacedStorages",new Map);this.namespace=e.namespace??q3;let a=n=>typeof n=="object"&&n!==null&&typeof n.setItem=="function";typeof window<"u"?(this.session=a(window.sessionStorage)?Wb(window.sessionStorage,this.namespace):Ic(this.namespace),this.user=a(window.localStorage)?Wb(window.localStorage,this.namespace):Ic(this.namespace)):(this.session=Ic(this.namespace),this.user=Ic(this.namespace)),this.dismissals=yT(this.session,this.user),this.cooldowns=vT(this.user),this.frequency=xT(this.session)}ns(e){let a=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(a)){let n=typeof window<"u"&&typeof sessionStorage<"u"?Wb(sessionStorage,a):Ic(a);this.namespacedStorages.set(a,n)}return this.namespacedStorages.get(a)}};function Xb(t={}){return new oh(t)}function Ac(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function ih(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var bT={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"}},Ec={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:[]},ST={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function Yb(t,e,a){let n=bT[e];Object.assign(t.style,n),a&&(a.maxWidth&&(t.style.maxWidth=a.maxWidth),a.maxHeight&&(t.style.maxHeight=a.maxHeight),a.minWidth&&(t.style.minWidth=a.minWidth),a.minHeight&&(t.style.minHeight=a.minHeight))}function Kb(t,e,a){let n=a.placement==="auto"?"bottom":a.placement,r=[Sf(a.offset?{mainAxis:a.offset.y,crossAxis:a.offset.x}:8)];return a.flip!==!1&&r.push(_f()),a.shift!==!1&&r.push(Cf({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",bf(e,t,async()=>{let{x:i,y:s,strategy:l}=await wf(e,t,{placement:n,middleware:r});Object.assign(t.style,{position:l,left:`${i}px`,top:`${s}px`})})}function Qb(t,e,a="append"){return t.style.position="relative",t.style.display="inline-block",a==="prepend"?e.insertBefore(t,e.firstChild):e.appendChild(t),()=>{t.remove()}}function Jb(t,e){return e==="none"||Ec[e].length===0?null:t.animate(Ec[e],ST)}function e0(t,e){if(e==="none"||Ec[e].length===0)return Promise.resolve();let a=[...Ec[e]].reverse(),n=t.animate(a,ST);return new Promise(r=>{n.onfinish=()=>r(),n.oncancel=()=>r()})}function t0(t,e){let a=document.createElement("div");return a.setAttribute("data-syntro-surface",t),a.setAttribute("data-syntro-mount-id",e),a.className="syntro-surface",Object.assign(a.style,{pointerEvents:"auto",boxSizing:"border-box",overflow:"auto"}),a}function a0(t){switch(Ac(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 CT(t){if(typeof window.Sanitizer=="function")try{let l=new window.Sanitizer({}).sanitizeToFragment(t),u=document.createElement("div");return u.append(l),u.innerHTML}catch{}let a=document.createElement("template");a.innerHTML=t;let n=a.content,r=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),o=new Set(["b","strong","i","em","u","span","div","p","br","ul","ol","li","code","pre","small","sup","sub","a","button"]),i=[];for(;r.nextNode();){let s=r.currentNode,l=s.tagName.toLowerCase();if(!o.has(l)){i.push(s);continue}for(let u of Array.from(s.attributes)){let c=u.name.toLowerCase(),d=u.value.trim().toLowerCase(),f=c.startsWith("on"),h=(c==="href"||c==="src")&&d.startsWith("javascript:");(f||h)&&s.removeAttribute(u.name)}}for(let s of i){for(;s.firstChild;)s.parentNode?.insertBefore(s.firstChild,s);s.remove()}return a.innerHTML=(n.firstChild,a.innerHTML)}var $3=0;function n0(t){let{overlayRoot:e,eventBus:a,anchorResolver:n,defaultAnimation:r="fade",widgetRegistry:o}=t,i=new Map,s=new Map,l=new Map;function u(){return`mount-${++$3}`}function c(y,_){a&&a.publish(y,_)}function d(y){let _=l.get(y);if(_){let L=b(y);for(let C of _)try{C(L)}catch(I){console.error("[Surfaces] State callback error:",I)}}}let f=new Map;function h(y,_,L){switch(_.type){case"html":y.innerHTML=CT(_.content);return;case"widget":{if(o?.has(_.widgetId)){let C=o.mount(_.widgetId,y,_.config);return L&&f.set(L,C),()=>{C.unmount(),L&&f.delete(L)}}console.warn(`[Surfaces] Widget not found: ${_.widgetId}`),y.innerHTML=`<div data-widget-id="${_.widgetId}" data-widget-missing="true">Widget: ${_.widgetId}</div>`;return}case"custom":return _.mount(y);case"react":y.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function S(y,_,L){let C=u(),I=Ac(y),w=L?.priority??0,k=L?.animation??r,T=L?.exclusive??!0,D=i.get(y);if(D&&T){if(D.options.priority>w)throw new Error(`Slot ${y} is occupied by higher priority content (${D.options.priority} > ${w})`);x(D)}let M=t0(y,C);M.style.zIndex=String(a0(y));let P;if(I==="static")Yb(M,y,L?.constraints),e.appendChild(M);else if(I==="inline"){let N=ih(y);if(!N)throw new Error(`Invalid inline slot: ${y}`);if(!n)throw new Error("Anchor resolver required for inline slots");let X=n({selector:N,route:"**"});if(!X)throw new Error(`Anchor not found for inline slot: ${N}`);P=Qb(M,X)}else if(I==="adjacent"){let N=ih(y);if(!N)throw new Error(`Invalid adjacent slot: ${y}`);if(!n)throw new Error("Anchor resolver required for adjacent slots");let X=n({selector:N,route:"**"});if(!X)throw new Error(`Anchor not found for adjacent slot: ${N}`);e.appendChild(M),P=Kb(M,X,L?.position??{placement:"bottom"})}let F=h(M,_,C);Jb(M,k);let U={id:C,slot:y,content:_,options:{priority:w,exclusive:T,animation:k,position:L?.position??{placement:"auto"},constraints:L?.constraints??{},adaptiveId:L?.adaptiveId,autoUnmountOnRouteChange:L?.autoUnmountOnRouteChange??!0},container:M,cleanup:()=>{P?.(),F?.()},mountedAt:Date.now()};return i.set(y,U),s.set(y,(s.get(y)??0)+1),c("surface.mounted",{slot:y,id:C,adaptiveId:L?.adaptiveId}),d(y),{id:C,update(N){let X=i.get(y);if(!X||X.id!==C)throw new Error("Mount no longer active");let ye=f.get(C);if(ye){if(N.type==="widget"){ye.update(N.config),X.content=N;return}ye.unmount(),f.delete(C)}X.container.innerHTML="";let qa=h(X.container,N,C);if(X.content=N,qa){let ht=X.cleanup;X.cleanup=()=>{ht?.(),qa()}}},setOptions(N){let X=i.get(y);if(!X||X.id!==C)throw new Error("Mount no longer active");N.priority!==void 0&&(X.options.priority=N.priority),N.animation!==void 0&&(X.options.animation=N.animation),N.constraints&&I==="static"&&(N.constraints.maxWidth&&(X.container.style.maxWidth=N.constraints.maxWidth),N.constraints.maxHeight&&(X.container.style.maxHeight=N.constraints.maxHeight),N.constraints.minWidth&&(X.container.style.minWidth=N.constraints.minWidth),N.constraints.minHeight&&(X.container.style.minHeight=N.constraints.minHeight)),d(y)},async unmount(){let N=i.get(y);!N||N.id!==C||await x(N)},isMounted(){return i.get(y)?.id===C},getContainer(){let N=i.get(y);return N?.id===C?N.container:null}}}async function x(y){y.container.isConnected&&await e0(y.container,y.options.animation);try{y.cleanup?.()}catch(_){console.warn("[Surfaces] Cleanup error during unmount, ignoring:",_)}try{y.container.remove()}catch{}i.delete(y.slot),c("surface.unmounted",{slot:y.slot,id:y.id}),d(y.slot)}function b(y){let _=i.get(y);return{slot:y,occupied:!!_,currentPriority:_?.options.priority,currentAdaptiveId:_?.options.adaptiveId,mountCount:s.get(y)??0,currentMountId:_?.id}}function m(y,_){let L=l.get(y);return L||(L=new Set,l.set(y,L)),L.add(_),()=>{L?.delete(_),L?.size===0&&l.delete(y)}}function g(y,_){let L=i.get(y);return L?_!==void 0?_>=L.options.priority:!1:!0}function v(){for(let y of i.values())try{y.cleanup?.(),y.container.remove()}catch(_){console.error("[Surfaces] Error during cleanup:",_)}i.clear(),l.clear()}return{mount:S,getState:b,onStateChange:m,canMount:g,destroy:v}}var sh=class{constructor(){B(this,"widgets",new Map);B(this,"mountedWidgets",new Map);B(this,"mountIdCounter",0);B(this,"runtimeRef");B(this,"listeners",new Set)}bindRuntime(e){this.runtimeRef=e}register(e,a,n="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:a,source:n,metadata:r}),this.notify({type:"registered",widgetId:e})}unregister(e){let a=this.widgets.get(e);return a?a.source==="built-in"?(console.warn(`[WidgetRegistry] Cannot unregister built-in widget: ${e}`),!1):(this.widgets.delete(e),this.notify({type:"unregistered",widgetId:e}),!0):!1}unregisterBySource(e){for(let[a,n]of this.widgets.entries())n.source===e&&this.widgets.delete(a)}get(e){return this.widgets.get(e)?.widget}getRegistration(e){return this.widgets.get(e)}has(e){return this.widgets.has(e)}mount(e,a,n){let r=this.widgets.get(e);if(!r)throw new Error(`Widget not found: ${e}`);let o=`widget-mount-${++this.mountIdCounter}`;a.setAttribute("data-widget-mount-id",o),a.setAttribute("data-widget-id",e);let i={...n,runtime:this.runtimeRef},s=r.widget.mount(a,i);return this.mountedWidgets.set(o,{cleanup:s??void 0,container:a}),{widgetId:e,container:a,unmount:()=>{let u=this.mountedWidgets.get(o);u&&(a.isConnected&&u.cleanup?.(),this.mountedWidgets.delete(o),a.removeAttribute("data-widget-mount-id"),a.removeAttribute("data-widget-id"),a.innerHTML="")},update:u=>{if(r.widget.update)r.widget.update(a,u);else{let c=this.mountedWidgets.get(o);if(c){c.cleanup?.(),a.innerHTML="";let d={...u,runtime:this.runtimeRef},f=r.widget.mount(a,d);c.cleanup=f??void 0}}}}}list(){return Array.from(this.widgets.keys())}listRegistrations(){return Array.from(this.widgets.values())}getBySource(e){return Array.from(this.widgets.values()).filter(a=>a.source===e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(let a of this.listeners)try{a(e)}catch(n){console.error("[WidgetRegistry] Listener error:",n)}}destroy(){for(let[e,a]of this.mountedWidgets.entries())a.cleanup?.(),a.container.innerHTML="";this.mountedWidgets.clear()}},r0=new sh;var wT="2.0.0";function V3(t,e){if(!e)return!0;let a;try{a=new URL(t).pathname}catch{a=t}let n=a.replace(/\/$/,"")||"/";if(e.exclude){for(let r of e.exclude)if(o0(n,r))return!1}if(e.include&&e.include.length>0){for(let r of e.include)if(o0(n,r))return!0;return!1}return!0}function o0(t,e){let a=e.replace(/\/$/,"")||"/";if(t===a)return!0;let n=a.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*").replace(/:[^/]+/g,"[^/]+");return new RegExp(`^${n}$`).test(t)}function _T(t){let a=(typeof window<"u"?window.location.pathname:"/").replace(/\/$/,"")||"/";return(Array.isArray(t.route)?t.route:[t.route]).some(r=>o0(a,r))}function i0(t={}){let{telemetry:e,sessionMetrics:a,routes:n,mode:r="production",namespace:o}=t,i=t.widgets??r0,s=t.executors??fr,l=t.apps??lu,u=new Lc,c=zb({telemetry:e,routes:n,navigation:u}),d=t.events??wc(),f=Xb({namespace:o}),h=$b({eventBus:d,stateStore:f}),S=qb({state:f,events:d,sessionMetrics:a,accumulator:h}),x=nk(),b=Hb(),m=C=>_T(C)?b.resolve(C.selector):null,g=async(C,I)=>{if(!_T(C))return null;try{return await b.waitFor(C.selector,I)}catch{return null}},v=n0({overlayRoot:x,eventBus:d,anchorResolver:m,widgetRegistry:i}),y=wb({overlayRoot:x,eventBus:d,surfaces:v,anchorResolver:m,waitForAnchor:g,executorRegistry:s,subscribeNavigation:C=>u.subscribe(C),runtime:{evaluateSync:C=>S.evaluateSync(C,c.get()),context:c,accumulator:h}}),_;if(a){a.increment("page_views");let C=typeof window<"u"?window.location.pathname:"/";_=u.subscribe((I,w)=>{if(w!=="replaceState")try{let k=new URL(I).pathname;k!==C&&(C=k,a.increment("page_views"))}catch{}})}let L={telemetry:e,context:c,events:d,state:f,sessionMetrics:a,actions:y,surfaces:v,widgets:i,executors:s,apps:l,accumulator:h,anchorResolver:b,navigation:u,version:wT,mode:r,async evaluate(C){return S.evaluate(C,c.get())},evaluateSync(C){return S.evaluateSync(C,c.get())},async filterTiles(C){let I=c.get().page.url,w=[];for(let k of C){let T=k.activation;if(!T){w.push(k);continue}if(V3(I,T.routes)){if(T.onlyIfPopulated){let D=k.props?.actions??[];if(D.length>0&&!D.some(P=>P.triggerWhen?S.evaluateSync(P.triggerWhen,c.get()).value:!0))continue}w.push(k)}}return w},setRoutes(C){c.setRoutes(C)},destroy(){l.unbind().catch(C=>{console.error("[Runtime] Error unbinding apps registry:",C)}),_?.(),b.destroy(),h.destroy(),u.destroy(),c.destroy(),y.destroy(),v.destroy()}};return l.bind(L),i.bindRuntime(L),L}var j3=p.object({value:p.unknown(),expiresAt:p.number().optional()}),G3=p.object({count:p.number(),resetAt:p.number().optional()});function E9(t){return j3.safeParse(t)}function T9(t){return G3.safeParse(t)}var LT={growthbook:t=>Ay({...t,autoInit:!0})};function kT(t,e){let a=LT[t];if(!a)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys(LT).join(", ")}`);return a(e)}var Z3=["cdn.syntrologie.com","localhost","127.0.0.1"];function W3(t){try{let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(console.warn("[SmartCanvas] CDN URL must use HTTPS:",t),!1):Z3.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 s0=class{constructor(e){B(this,"name","cdn");B(this,"url");B(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!W3(this.url))throw new Error(`[SmartCanvas] CDN URL not allowed: ${this.url}`)}async fetch(){let e=performance.now(),a=await fetch(this.url,{credentials:"omit",cache:"default"});if(!a.ok)throw new Error(`[SmartCanvas] Failed to fetch config from CDN (${a.status})`);let n=await a.text();if(this.integrity){let l=await X3(n),u=this.integrity.replace("sha384-","");if(l!==u)throw new Error(`[SmartCanvas] Config integrity check failed. Expected ${u}, got ${l}`)}let r=JSON.parse(n),o=performance.now()-e,i=a.headers.get("cache-control"),s=a.headers.get("age");return{config:r,meta:{source:"cdn",fetchTimeMs:o,cached:i?.includes("public")??!1,cacheAge:s?parseInt(s,10):void 0}}}};async function X3(t){let a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-384",a),r=new Uint8Array(n);return btoa(String.fromCharCode(...r))}function IT(t){return new s0(t)}var Y3="syntro_exp",K3="syntro_var",l0=class{constructor(e){B(this,"name","experiments");B(this,"client");B(this,"featureKey");B(this,"manifestKey");B(this,"variantFlagPrefix");this.client=e.client,this.featureKey=e.featureKey??"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),o=r.get(Y3),i=r.get(K3);if(o&&i!==null&&this.client.setForcedVariations){let s=parseInt(i,10);Number.isNaN(s)||(console.log(`[SmartCanvas] Preview mode: forcing "${o}" to variation ${s}`),this.client.setForcedVariations({[o]:s}))}}if(this.manifestKey||this.variantFlagPrefix||this.client.getAllFeatures){let r=this.fetchMultiFlag();if(r){let o=performance.now()-e;return{config:r,meta:{source:"experiments",fetchTimeMs:o,cached:!0}}}}let a=this.client.getFeatureValue?.(this.featureKey,null);if(!a||typeof a!="object")throw new Error(`[SmartCanvas] Feature "${this.featureKey}" not found or invalid. Ensure the feature is configured in your experiment platform.`);let n=performance.now()-e;return{config:a,meta:{source:"experiments",fetchTimeMs:n,cached:!0}}}fetchMultiFlag(){let e=this.getVariantFlagKeys();return!e||e.length===0?null:Pf(this.client,e)}getVariantFlagKeys(){if(this.manifestKey){let e=this.client.getFeatureValue?.(this.manifestKey,null);if(e&&typeof e=="object"){let a=e.variant_flags;if(a&&a.length>0)return a}}if(this.client.getAllFeatures){let e=this.client.getAllFeatures();return this.variantFlagPrefix?Object.keys(e).filter(a=>a.startsWith(this.variantFlagPrefix)):Object.keys(e)}return[]}};function AT(t){return new l0(t)}var Q3="https://cdn.syntrologie.com/configs",ET={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return IT({baseUrl:t.baseUrl??Q3,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return AT({featureKey:t.featureKey})}};function TT(t,e={}){let a=ET[t];if(!a)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys(ET).join(", ")}`);return a(e)}var RT={posthog:t=>yb(t),noop:()=>By()};function MT(t,e){let a=RT[t];if(!a)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(RT).join(", ")}`);return a(e)}var u0="syn_";function lh(t){if(!t.startsWith(u0))throw new Error("Invalid Syntro token: must start with 'syn_'");let a=t.slice(u0.length).replace(/-/g,"+").replace(/_/g,"/"),n=atob(a),r=JSON.parse(n);if(r.v!==1)throw new Error(`Unsupported token version: ${r.v}`);return r}function c0(t){let e=JSON.stringify(t),a=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return u0+a}function pr(t){if(typeof process<"u"&&process.env)return process.env[t];try{let e=(0,eval)("import.meta");if(e?.env)return e.env[t]}catch{}}var DT="syntro_segment_attributes";function J3(){if(typeof window>"u")return{};try{let t=localStorage.getItem(DT);if(t){let e=JSON.parse(t);return K("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){ya("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function eH(t){if(!(typeof window>"u"))try{localStorage.setItem(DT,JSON.stringify(t)),K("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){ya("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function tH(t){if(!t)return{};let e={};for(let[a,n]of Object.entries(t))a.startsWith("in_segment_")&&(e[a]=n===!0);return e}function aH(){if(typeof window>"u")return{};let t={};try{let e=new URLSearchParams(window.location.search);for(let a of["utm_source","utm_medium","utm_campaign","utm_content","utm_term"]){let n=e.get(a);n&&(t[a]=n)}}catch{}try{navigator.language&&(t.browser_language=navigator.language),navigator.languages?.length&&(t.browser_languages=[...navigator.languages])}catch{}try{let e=window.innerWidth;t.device_type=e<768?"mobile":e<1024?"tablet":"desktop"}catch{}try{if(document.referrer){t.referrer=document.referrer;try{t.referrer_hostname=new URL(document.referrer).hostname}catch{}}}catch{}try{t.page_url=window.location.href,t.page_path=window.location.pathname}catch{}return t}async function nH(t){Fv(),K("Syntro Bootstrap","====== INIT ======"),K("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=Hf();if(console.log(`[DIAG] Mode detection: sdkMode=${e}`),console.log("[DIAG] editorSource:",mu()),console.log("[DIAG] editorConf:",Nf()),K("Syntro Bootstrap","SDK mode:",e??"normal"),!e&&typeof window<"u"){let w=!!window.__SYNTRO_EDITOR_PARAMS__,k=!!window.__SYNTRO_AUDIT_LEGEND__,T=!!window.__SYNTRO_REVIEW_DATA__;if(w||k||T){let D=[w&&"__SYNTRO_EDITOR_PARAMS__",k&&"__SYNTRO_AUDIT_LEGEND__",T&&"__SYNTRO_REVIEW_DATA__"].filter(Boolean);console.warn(`[Syntro Bootstrap] \u26A0 Mode detection returned null but mode-specific globals found: ${D.join(", ")}. This suggests URL params were lost (redirect?) but the service worker injected mode data. Check if replaceState failed or if page JS changed the URL before init().`)}}console.log(`[DIAG] Token resolution: options.token=${t.token?t.token.slice(0,15)+"...":"null"}`);let a=t.token;if(!a&&e){let k=Nf()?.syntro_token;k?.startsWith("syn_")&&(a=k,K("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${e} mode)`))}let n;if(a)if(a.startsWith("syn_"))K("Syntro Bootstrap","Token starts with syn_, decoding..."),n=lh(a),Fv(n.d);else if(e)K("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${e} mode)`);else throw Ff("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),Ff("Syntro Bootstrap","Token received:",a),new Error("Invalid Syntro token: must start with 'syn_'");else if(e)K("Syntro Bootstrap",`\u2713 No token, but ${e} mode - proceeding`);else throw Ff("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 r=pr("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||pr("VITE_SYNTRO_EXPERIMENT_HOST")||n?.eh,o=pr("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||pr("VITE_SYNTRO_TELEMETRY_HOST")||n?.th,i=pr("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||pr("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,s=J3(),l=aH(),u={...l,...s};K("Syntro Bootstrap","Phase 1: Browser metadata:",l),K("Syntro Bootstrap","Phase 1: Cached segment attributes:",s);let c,d=wc();console.log("[Syntro Bootstrap] EventBus created");let f=jb(w=>{d.publishEvent(w)}),h=w=>{K("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let k=tH(w);if(K("Syntro Bootstrap","Segment flags from PostHog:",k),eH(k),c){let T=x?.getAll?.()??{},D={...l,...T,...k};K("Syntro Bootstrap","Updating GrowthBook with attributes:",D),c.setAttributes?.(D)}},S;if(n?.t){let w=n.t==="noop"?"noop":"posthog";S=MT(w,{apiKey:n.t,apiHost:o,enableFeatureFlags:!0,onFeatureFlagsLoaded:h,onCapture:f}),console.log(`[Syntro Bootstrap] Telemetry client created (${w}) with EventBus wiring`)}let x;n?.e&&(c=kT("growthbook",{clientKey:n.e,apiHost:r,attributes:u,onExperimentViewed:S?.trackExperiment?(w,k,T)=>{S.trackExperiment(w,k,T)}:void 0})),x=Ey({experiments:c,onMetricChange:(w,k)=>{K("Syntro Bootstrap",`Session metric changed: ${w} = ${k}`)}}),K("Syntro Bootstrap","SessionMetricTracker created");let b="production";e==="editor"?b="editor":e==="audit"?b="audit":pr("NODE_ENV")==="development"&&(b="development");let m=i0({telemetry:S,sessionMetrics:x,mode:b,events:d});K("Syntro Bootstrap","Runtime created:",{version:m.version,mode:m.mode,hasContext:!!m.context,hasEvents:!!m.events,hasState:!!m.state}),K("Syntro Bootstrap","Core app executors already registered");let g=t.cdnBase||pr("NEXT_PUBLIC_SYNTRO_CDN_BASE")||pr("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",v=vv({cdnBase:g,registry:m.apps,onLoadStart:w=>{K("Syntro Bootstrap",`Loading app from CDN: ${w}`)},onLoadEnd:(w,k,T)=>{k?K("Syntro Bootstrap",`App loaded successfully: ${w}`):ya("Syntro Bootstrap",`Failed to load app: ${w}`,T)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:m.apps,runtime:m,version:m.version},K("Syntro Bootstrap","Global SynOS object exposed"));let y=m.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${y.length} apps in registry:`,y.map(w=>`${w.manifest.id}(${w.state})`).join(", "));for(let w of y)if(w.state==="registered")try{await m.apps.activate(w.manifest.id),console.log(`[DIAG] Activated: ${w.manifest.id} \u2192 widgets: [${m.widgets.list().join(", ")}]`)}catch(k){console.error(`[DIAG] FAILED to activate: ${w.manifest.id}`,k),ya("Syntro Bootstrap",`Failed to auto-activate built-in app: ${w.manifest.id}`,k)}if(console.log(`[DIAG] Activation complete. Total widgets: [${m.widgets.list().join(", ")}]`),c?.refreshFeatures)try{await c.refreshFeatures(),K("Syntro Bootstrap","GrowthBook features loaded")}catch(w){ya("Syntro Bootstrap","Failed to load GrowthBook features:",w)}let _;if(t.fetcher)_=t.fetcher;else if(n?.f){let w=TT(n.f,n.o??{});_=async()=>{let k=await w.fetch();return{...k.config,tiles:k.config.tiles??[]}}}else c&&(_=ys({experiments:c}));let L=new Set,C=_?async()=>{let w=await _();console.log("[Syntro Bootstrap] Config fetched:",`tiles=${w.tiles?.length??0},`,`actions=${w.actions?.length??0},`,`theme=${w.theme?.name??"none"}`),w.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",w.actions.map((D,M)=>`[${M}] ${D.kind}${D.anchorId?` anchor="${D.anchorId.selector}"`:""}${D.label?` "${D.label}"`:""}`).join(", "));let k=w,T=v.getRequiredApps(k);return T.length>0?console.log("[Syntro Bootstrap] Required external apps:",T.join(", ")):K("Syntro Bootstrap","No external apps required (all executors are built-in)"),T.length>0&&await v.loadAppsForConfig(k).then(async M=>{let P=M.filter(j=>j.success),F=M.filter(j=>!j.success);P.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${P.map(j=>j.appId).join(", ")}`);let U=F.filter(j=>!L.has(j.appId));U.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",U.map(j=>`${j.appId} (${j.error})`).join(", ")),U.forEach(j=>L.add(j.appId)));for(let j of T)if(m.apps.has(j))try{await m.apps.activate(j),console.log(`[Syntro Bootstrap] App activated: ${j}`)}catch(N){console.error(`[Syntro Bootstrap] Failed to activate app: ${j}`,N)}else console.error(`[Syntro Bootstrap] App "${j}" required by config but NOT registered.`,`Available apps: [${Array.from(m.apps.list?.()??[]).join(", ")}]`)}),w}:void 0;return{canvas:await uy({...t.canvas,fetcher:C,integrations:{experiments:c,telemetry:S},editorUrl:i,runtime:m}),runtime:m,experiments:c,telemetry:S,sessionMetrics:x,appLoader:v}}var OT={init:nH,encodeToken:c0,decodeToken:lh};typeof window<"u"&&(window.Syntro=OT);var BT="2026-03-14T02:31:26.217Z (7fefac724c)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${BT}`);let t=window.SynOS,e=t?.appRegistry||lu;window.SynOS={...t,appRegistry:e,_runtimeBuild:BT,React:PT.default,ReactDOM:{...rH,createPortal:uh.createPortal,flushSync:uh.flushSync}},j1(e)}export{Ec as ANIMATION_KEYFRAMES,eh as ActivationConfigZ,VE as AddClassZ,za as AnchorIdZ,O3 as AnchorStateZ,Ib as AnchorVisibleConditionZ,kf as AppRegistry,B3 as AugmentationZ,DE as BadgePositionZ,YE as BadgeZ,D3 as BoundingBoxZ,gu as CanvasEvents,Dy as CanvasRecipeZ,So as ConditionZ,th as ContextManager,Db as CooldownActiveConditionZ,vc as CounterDefZ,Nb as CtaButtonZ,Gv as DEFAULT_COOLDOWN,jv as DEFAULT_TTL,_c as DecisionStrategyZ,Mb as DismissedConditionZ,Cs as EVENT_SCHEMA_VERSION,rh as EventBus,Bb as EventCountConditionZ,z3 as EventFilterZ,Ab as EventOccurredConditionZ,gT as EventSourceZ,Qp as ExecutorRegistry,Cc as ExternalStrategyZ,G3 as FrequencyEntryZ,Ob as FrequencyLimitConditionZ,xN as HighlightStepZ,ME as HighlightStyleZ,WE as HighlightZ,ZE as InsertHtmlZ,FE as InsertPositionZ,Vv as MAX_VISIBLE_TOASTS,gc as MatchOpZ,PE as ModalContentZ,QE as ModalZ,Sc as ModelStrategyZ,tT as MountWidgetZ,eT as NavigateZ,Lc as NavigationMonitor,U3 as NormalizedEventZ,$v as NotificationToastStack,E3 as PageContextZ,T3 as PageHistoryEntryZ,Lb as PageUrlConditionZ,rT as ParallelZ,OE as PlacementZ,XE as PulseZ,BT as RUNTIME_SDK_BUILD,wT as RUNTIME_VERSION,jE as RemoveClassZ,kb as RouteConditionZ,RE as RouteFilterZ,xc as RuleStrategyZ,yc as RuleZ,P3 as RuntimeContextZ,Kv as RuntimeProvider,Zr as SDK_SCHEMA_VERSION,Nv as SDK_VERSION,bT as STATIC_SLOT_STYLES,bc as ScoreStrategyZ,zE as ScrollBehaviorZ,Fb as ScrollLogicalPositionZ,JE as ScrollToZ,LI as SelectorZ,nT as SequenceZ,R3 as SessionContextZ,Rb as SessionMetricConditionZ,dp as SessionMetricTracker,$E as SetAttrZ,GE as SetStyleZ,qE as SetTextZ,bk as ShadowCanvasOverlay,ik as ShadowRootProvider,wk as SmartCanvasApp,Uv as SmartCanvasController,sy as SmartCanvasElement,Z$ as SmartCanvasPortal,we as StandardEvents,Eb as StateEqualsConditionZ,oh as StateStore,j3 as StoredValueZ,OT as Syntro,Ru as TileCard,P6 as TileWheel,BE as TooltipContentZ,yN as TooltipStepZ,NE as TooltipTriggerZ,KE as TooltipZ,UE as TourStepForSchemaZ,oT as TourZ,Jp as TriggerWhenZ,Tb as ViewportConditionZ,M3 as ViewportContextZ,aT as WaitZ,HE as WidgetConfigZ,sh as WidgetRegistry,lu as appRegistry,Yb as applyStaticSlotStyles,mv as cleanupAppContext,tv as contentRuntime,I3 as coreActionStepSchemas,wb as createActionEngine,Hb as createAnchorResolver,hv as createAppContext,vv as createAppLoader,ys as createCanvasConfigFetcher,zb as createContextManager,qb as createDecisionEngine,$b as createEventAccumulator,wc as createEventBus,Ay as createGrowthBookClient,By as createNoopClient,j$ as createOverlayRecipeFetcher,yb as createPostHogClient,jb as createPostHogNormalizer,Ey as createSessionMetricTracker,uy as createSmartCanvas,rk as createSmartCanvasController,i0 as createSmartCanvasRuntime,Xb as createStateStore,t0 as createSurfaceContainer,n0 as createSurfaces,DV as decisionSchemas,lh as decodeToken,c0 as encodeToken,cT as evaluate,sT as evaluateCondition,lT as evaluateRule,ah as evaluateRuleStrategy,nh as evaluateScoreStrategy,dT as evaluateSync,fr as executorRegistry,XO as getAntiFlickerSnippet,f1 as getAppIdFromActionKind,gv as getAppIdFromWidgetId,K4 as getExecutor,ih as getSlotAnchorId,Ac as getSlotType,a0 as getSlotZIndex,Cb as hasExecutor,jf as interpolateTemplate,d1 as isCoreActionKind,Zv as matchEvent,U6 as needsMigration,hT as normalizePostHogEvent,pv as overlaysRuntime,Mu as parseVersion,Jb as playEnterAnimation,e0 as playExitAnimation,Uf as registerConfigPredicates,Ak as registerSmartCanvasElement,Hv as resolveConfigUri,Kb as setupAdjacentPositioning,Qb as setupInlinePositioning,mT as shouldNormalizeEvent,QB as useDecision,Wv as useNotifications,Xv as useNotifyWatcher,Qv as usePageContext,Yn as useRuntime,Zf as useRuntimeContext,YB as useRuntimeEvents,KB as useRuntimeState,WB as useSessionContext,Ck as useShadowCanvasConfig,Ss as useShadowRoot,XB as useViewportContext,bo as validateAction,_b as validateActions,MV as validateActivationConfig,TV as validateCondition,H6 as validateConfig,k8 as validateEventFilter,T9 as validateFrequencyEntry,L8 as validateNormalizedEvent,z$ as validateRecipe,t8 as validateRuntimeContext,E9 as validateStoredValue,RV as validateStrategy,r0 as widgetRegistry};
|
|
520
520
|
/*! Bundled license information:
|
|
521
521
|
|
|
522
522
|
react/cjs/react.production.js:
|