rivet-design 0.26.0 → 0.26.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-variants/contracts.d.ts +320 -320
- package/dist/agent-variants/workItemInput.d.ts +210 -210
- package/dist/routes/variantRequestSchema.d.ts +4 -4
- package/dist/services/GuidanceVerifierRunner.js +13 -2
- package/dist/storage/library/ProjectPreviewCache.d.ts +2 -2
- package/dist/types/guidance-verifier.d.ts +458 -59
- package/dist/types/guidance-verifier.js +35 -12
- package/dist/utils/skills/cli-guidance.d.ts +1 -1
- package/dist/utils/skills/cli-guidance.js +2 -2
- package/package.json +2 -2
- package/src/ui/dist/assets/{LibraryEntry-CFkd6v_O.js → LibraryEntry-Cr4GFYXW.js} +2 -2
- package/src/ui/dist/assets/{main-B_jie9r3.js → main-tPO1OCpZ.js} +4 -4
- package/src/ui/dist/index.html +1 -1
|
@@ -16,7 +16,7 @@ var _k=t=>{throw TypeError(t)};var cy=(t,e,n)=>e.has(t)||_k("Cannot "+n);var Z=(
|
|
|
16
16
|
* LICENSE file in the root directory of this source tree.
|
|
17
17
|
*/var Sk;function f7(){if(Sk)return mf;Sk=1;var t=Ox(),e=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,s=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function o(l,u,d){var f,h={},m=null,v=null;d!==void 0&&(m=""+d),u.key!==void 0&&(m=""+u.key),u.ref!==void 0&&(v=u.ref);for(f in u)r.call(u,f)&&!i.hasOwnProperty(f)&&(h[f]=u[f]);if(l&&l.defaultProps)for(f in u=l.defaultProps,u)h[f]===void 0&&(h[f]=u[f]);return{$$typeof:e,type:l,key:m,ref:v,props:h,_owner:s.current}}return mf.Fragment=n,mf.jsx=o,mf.jsxs=o,mf}var kk;function h7(){return kk||(kk=1,uy.exports=f7()),uy.exports}var S=h7();const p7="x-rivet-editor-token",Ek="editorToken",m7=["/api/account","/api/config","/api/auth/store","/api/auth/logout","/api/library/browser-launches","/api/integrations","/api/reference-profiles"],g7=/^\/api\/variants\/(?:[^/]+\/static\/|history\/[^/]+\/[^/]+\/(?:preview(?:\/|$)|site\/)|[^/]+\/[^/]+\/references\/[^/]+\/image\/?$)/,v7=(t,e="GET")=>{const n=t.split(/[?#]/)[0].toLowerCase();return/^\/api\/variants(?:\/|$)/.test(n)?!["GET","HEAD"].includes(e.toUpperCase())||!g7.test(n):m7.some(r=>n===r||n.startsWith(`${r}/`))},n2="rivet_editor_token";let r2;const y7=()=>{if(window.location.pathname.startsWith("/rivet/library"))return;const t=new URLSearchParams(window.location.hash.slice(1)),e=t.get(Ek);if(e===null)return;r2=e||null,t.delete(Ek);const n=t.toString();window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}${n?`#${n}`:""}`);try{e?window.sessionStorage.setItem(n2,e):window.sessionStorage.removeItem(n2)}catch{}},_7=()=>{if(r2!==void 0)return r2;try{return window.sessionStorage.getItem(n2)}catch{return null}};var g=Ox();const _e=zg(g),kd=l7({__proto__:null,default:_e},[g]);var w7={};const oe="u">typeof window?window:void 0,Tr="u">typeof globalThis?globalThis:oe,gr=Tr==null?void 0:Tr.navigator,ke=Tr==null?void 0:Tr.document,Ut=Tr==null?void 0:Tr.location,hh=Tr==null?void 0:Tr.fetch,Lx=Tr!=null&&Tr.XMLHttpRequest&&"withCredentials"in new Tr.XMLHttpRequest?Tr.XMLHttpRequest:void 0,Ck=Tr==null?void 0:Tr.AbortController,x7=Tr==null?void 0:Tr.CompressionStream,Vr=gr==null?void 0:gr.userAgent,gf=typeof globalThis<"u"?globalThis:oe;gf&&typeof self>"u"&&(gf.self=gf),gf&&typeof File>"u"&&(gf.File=function(){});const qe=oe??{},b7="0.10.2",Ho={DEBUG:!1,LIB_VERSION:b7,LIB_NAME:"browser-common"};var ji=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.AiCaptureQueue="ai_capture_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysInProgress="surveys_in_progress",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),s2=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({});const S7=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],k7=["token"];function je(t,e){return t.indexOf(e)!==-1}const rd=function(t){return t.trim()},i2=function(t){return t.replace(/^\$/,"")};function p5(t){var e;const n=[];return(e=JSON.stringify(t,function(r,s){if(typeof s=="bigint")return s.toString();if(typeof s!="function"&&typeof s!="symbol"){if(s instanceof Error)return{name:s.name,message:s.message,stack:s.stack};if(s&&typeof s=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(s))return"[Circular]";n.push(s)}return s}}))!==null&&e!==void 0?e:"null"}const m5=Object.prototype,Nx=m5.hasOwnProperty,Ug=m5.toString,ze=Array.isArray||function(t){return Ug.call(t)==="[object Array]"},gn=t=>typeof t=="function",nt=t=>t===Object(t)&&!ze(t),ts=t=>{if(nt(t)){for(const e in t)if(Nx.call(t,e))return!1;return!0}return!1},ae=t=>t===void 0,rt=t=>Ug.call(t)=="[object String]",Bf=t=>rt(t)&&t.trim().length===0,dn=t=>t===null,Xe=t=>ae(t)||dn(t),Cn=t=>Ug.call(t)=="[object Number]"&&t==t,Ao=t=>Cn(t)&&t>0,Hr=t=>Ug.call(t)==="[object Boolean]",E7=t=>je(S7,t),C7=t=>je(k7,t);function g5(t){return t===null||typeof t!="object"}function Om(t,e){return{}.toString.call(t)===`[object ${e}]`}function Ed(t){switch({}.toString.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return v5(t,Error)}}function Dx(t){return"u">typeof Event&&v5(t,Event)}function v5(t,e){try{return t instanceof e}catch{return!1}}const P7=[!0,"true",1,"1","yes"],fy=t=>je(P7,t),A7=[!1,"false",0,"0","no"];function Pk(t,e,n,r,s,i,o){try{var l=t[i](o),u=l.value}catch(d){return void n(d)}l.done?e(u):Promise.resolve(u).then(r,s)}function Wt(t){return function(){var e=this,n=arguments;return new Promise(function(r,s){var i=t.apply(e,n);function o(u){Pk(i,r,s,o,l,"next",u)}function l(u){Pk(i,r,s,o,l,"throw",u)}o(void 0)})}}const T7=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],y0=new Map,Ak=function(t,e=[]){if(!t)return!1;const n=(function(o,l){let u="";for(let d=0;l.length>d;d++){const f=l[d];u+=f.length+":"+f}return o.length+":"+o+"|"+l.length+":"+u})(t,e),r=y0.get(n);if(r!==void 0)return r;const s=t.toLowerCase(),i=T7.concat(e).some(o=>s.indexOf(o.toLowerCase())!==-1);return 256>y0.size||y0.clear(),y0.set(n,i),i};function Zi(t,e,n,r,s){return e>n&&(r.warn("min cannot be greater than max."),e=n),Cn(t)?t>n?(r.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+s),Zi(s??n,e,n,r))}var R7=class{constructor(t){this.C={},this.I=t.I,this.R=Zi(t.bucketSize,0,100,t.$),this.A=Zi(t.refillRate,0,this.R,t.$),this.O=Zi(t.refillInterval,0,864e5,t.$)}F(t,e){const n=Math.floor((e-t.lastAccess)/this.O);n>0&&(t.tokens=Math.min(t.tokens+n*this.A,this.R),t.lastAccess=t.lastAccess+n*this.O)}consumeRateLimit(t){var e;const n=Date.now(),r=String(t);let s=this.C[r];return s?this.F(s,n):(s={tokens:this.R,lastAccess:n},this.C[r]=s),s.tokens===0||(s.tokens--,s.tokens===0&&((e=this.I)===null||e===void 0||e.call(this,t)),s.tokens===0)}stop(){this.C={}}};const sd="Mobile",ph="Android",Lm="Tablet",y5="Android Tablet",_5="iPad",w5="Apple Watch",em="Safari",Bg="BlackBerry",x5="Samsung Internet",tm="Chrome",b5="Chrome iOS",S5="Internet Explorer",k5="Internet Explorer Mobile",E5="Opera",C5="Microsoft Edge",nm="Firefox",P5="Firefox iOS",Nm="Nintendo",Dm="PlayStation",Wg="Xbox",A5="Android Mobile",T5="Mobile Safari",hy="Windows",R5="Windows Phone",Tk="Nokia",o2="Ouya",I7="Generic "+sd.toLowerCase(),I5="Generic "+Lm.toLowerCase(),a2="Konqueror",M5="Oculus Browser",O5="Vivaldi",L5="Yandex",N5="Whale",D5="DuckDuckGo",j5="Pale Moon",$5="Waterfox",l2="Brave",F5="Claude",V5="Codex",H5="ChatGPT",z5="Google Search App",py=new RegExp("Version/(\\d+(\\.\\d+)?)"),my=new RegExp("(Claude|Codex|ChatGPT)\\/(\\d+(\\.\\d+)?)"),M7=new RegExp(Wg,"i"),O7=new RegExp("PlayStation \\w+","i"),L7=new RegExp("Nintendo \\w+","i"),jx=new RegExp("BlackBerry|PlayBook|BB10","i"),N7={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},U5=function(t,e,n,r){return e=e||"",(function(i){return i!=null&&i.brave?l2:null})(n)||(r!=null&&r.detectGoogleSearchApp&&je(t,"GSA/")?z5:je(t," OPR/")&&je(t,"Mini")?"Opera Mini":je(t," OPR/")?E5:jx.test(t)?Bg:je(t,"IEMobile")||je(t,"WPDesktop")?k5:je(t,"OculusBrowser")?M5:je(t,"SamsungBrowser")?x5:je(t,"Edge")||je(t,"Edg/")?C5:je(t,"Vivaldi/")?O5:je(t,"YaBrowser/")?L5:je(t,"Whale/")?N5:je(t,"DuckDuckGo/")||je(t,"Ddg/")?D5:je(t,"Claude/")?F5:je(t,"Codex/")?V5:je(t,"ChatGPT/")?H5:je(t,"FBIOS")?"Facebook Mobile":je(t,"UCWEB")||je(t,"UCBrowser")?"UC Browser":je(t,"CriOS")?b5:je(t,"CrMo")||je(t,tm)?tm:je(t,ph)&&je(t,em)?A5:je(t,"FxiOS")?P5:je(t.toLowerCase(),a2.toLowerCase())?a2:je(t,"Brave/")?l2:((i,o)=>o&&je(o,"Apple")||(function(l){return je(l,em)&&!je(l,tm)&&!je(l,ph)})(i))(t,e)?je(t,sd)?T5:em:je(t,"PaleMoon/")?j5:je(t,"Waterfox/")?$5:je(t,nm)?nm:je(t,"MSIE")||je(t,"Trident/")?S5:je(t,"Gecko")?nm:"")},D7={[k5]:[new RegExp("rv:(\\d+(\\.\\d+)?)")],[C5]:[new RegExp("Edge?\\/(\\d+(\\.\\d+)?)")],[tm]:[new RegExp("(Chrome|CrMo)\\/(\\d+(\\.\\d+)?)")],[b5]:[new RegExp("CriOS\\/(\\d+(\\.\\d+)?)")],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/(\\d+(\\.\\d+)?)")],[em]:[py],[T5]:[py],[E5]:[new RegExp("(Opera|OPR)\\/(\\d+(\\.\\d+)?)")],[nm]:[new RegExp("Firefox\\/(\\d+(\\.\\d+)?)")],[P5]:[new RegExp("FxiOS\\/(\\d+(\\.\\d+)?)")],[a2]:[new RegExp("Konqueror[:/]?(\\d+(\\.\\d+)?)","i")],[Bg]:[new RegExp("BlackBerry (\\d+(\\.\\d+)?)"),py],[A5]:[new RegExp("android\\s(\\d+(\\.\\d+)?)","i")],[x5]:[new RegExp("SamsungBrowser\\/(\\d+(\\.\\d+)?)")],[M5]:[new RegExp("OculusBrowser\\/(\\d+(\\.\\d+)?)")],[O5]:[new RegExp("Vivaldi\\/(\\d+(\\.\\d+)?)")],[L5]:[new RegExp("YaBrowser\\/(\\d+(\\.\\d+)?)")],[N5]:[new RegExp("Whale\\/(\\d+(\\.\\d+)?)")],[l2]:[new RegExp("Brave\\/(\\d+(\\.\\d+)?)")],[F5]:[my],[V5]:[my],[H5]:[my],[D5]:[new RegExp("(DuckDuckGo|Ddg)\\/(\\d+(\\.\\d+)?)")],[j5]:[new RegExp("PaleMoon\\/(\\d+(\\.\\d+)?)")],[$5]:[new RegExp("Waterfox\\/(\\d+(\\.\\d+)?)")],[z5]:[new RegExp("GSA\\/(\\d+(\\.\\d+)?)")],[S5]:[new RegExp("(rv:|MSIE )(\\d+(\\.\\d+)?)")],Mozilla:[new RegExp("rv:(\\d+(\\.\\d+)?)")]},j7=function(t,e,n,r){const s=U5(t,e,n,r),i=D7[s];if(ae(i))return null;for(let o=0;i.length>o;o++){const l=t.match(i[o]);if(l)return parseFloat(l[l.length-2])}return null},Rk=[[new RegExp("Xbox; Xbox (.*?)[);]","i"),t=>[Wg,t&&t[1]||""]],[new RegExp(Nm,"i"),[Nm,""]],[new RegExp(Dm,"i"),[Dm,""]],[jx,[Bg,""]],[new RegExp(hy,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[R5,""];if(new RegExp(sd).test(e)&&!/IEMobile\b/.test(e))return["Windows Mobile",""];const n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){let r=N7[n[1]]||"";return/arm/i.test(e)&&(r="RT"),[hy,r]}return[hy,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?["iOS",[t[3],t[4],t[5]||"0"].join(".")]:["iOS",""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=ae(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("(Android (\\d+)\\.(\\d+)\\.?(\\d+)?|Android)","i"),t=>t&&t[2]?[ph,[t[2],t[3],t[4]||"0"].join(".")]:[ph,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{const e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,["Chrome OS",""]],[/Linux|debian/i,["Linux",""]]],B5=function(t){for(let e=0;Rk.length>e;e++){const[n,r]=Rk[e],s=n.exec(t),i=s&&(gn(r)?r(s,t):r);if(i)return i}return["",""]},W5=function(t){return L7.test(t)?Nm:O7.test(t)?Dm:M7.test(t)?Wg:new RegExp(o2,"i").test(t)?o2:new RegExp("(Windows Phone|WPDesktop)","i").test(t)?R5:/iPad/.test(t)?_5:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?w5:jx.test(t)?Bg:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(Tk,"i").test(t)?Tk:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(sd).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?ph:y5:new RegExp("(pda|Mobile)","i").test(t)?I7:new RegExp(Lm,"i").test(t)&&!new RegExp("Tablet pc","i").test(t)?I5:""},$7=function(t,e){var n;const r=W5(t);return r===_5||r===y5||r==="Kobo"||r==="Kindle Fire"||r===I5?Lm:r===Nm||r===Wg||r===Dm||r===o2?"Console":r===w5?"Wearable":r?sd:(e==null?void 0:e.userAgentDataPlatform)==="Android"&&((n=e==null?void 0:e.maxTouchPoints)!==null&&n!==void 0?n:0)>0?600>Math.min((s=e==null?void 0:e.screenWidth)!==null&&s!==void 0?s:0,(i=e==null?void 0:e.screenHeight)!==null&&i!==void 0?i:0)/((o=e==null?void 0:e.devicePixelRatio)!==null&&o!==void 0?o:1)?sd:Lm:"Desktop";var s,i,o},gy=/\bFBAV\/(\d+(?:\.\d+)*)/i,Ik=[[/\bInstagram(?:[ /](\d+(?:\.\d+)*))?\b/i,"Instagram"],[/\bBarcelona[ /](\d+(?:\.\d+)*)?/i,"Threads"],[/\b(?:MessengerForiOS|(?:FBAN|FB_IAB)\/Orca-Android)\b/i,"Messenger",gy],[/\bFBAN\/EMA\b/i,"Facebook Lite",gy],[/\b(?:FBIOS|(?:FBAN|FB_IAB)\/(?:FB4A|FBIOS))\b/i,"Facebook",gy],[/\bLinkedInApp(?:\]?\/(\d+(?:\.\d+)*))?\b/i,"LinkedIn"],[/\bTwitter(?:Android| for (?:iPhone|iPad|Android))(?:\/(\d+(?:\.\d+)*))?\b/i,"Twitter"],[/\b(?:musical_ly|trill)(?:[_/](\d+\.\d+(?:\.\d+)*))?(?=\b|_)/i,"TikTok",/\bapp_version\/(\d+(?:\.\d+)*)/i],[/\b(?:MicroMessenger|WeChat)\/(\d+(?:\.\d+)*)?/i,"WeChat"],[/\bLine\/(\d+(?:\.\d+)*)?/i,"Line"],[/\bGSA\/(\d+(?:\.\d+)*)?/i,"Google"],[/\[Pinterest\/(?:iOS|Android)\b|\bPinterest(?: for (?:Android(?: Tablet)?|iOS))?\/(\d+(?:\.\d+)*)/i,"Pinterest"],[/\b(?:WA4A|WAiOS)\/(\d+(?:\.\d+)*)?/i,"WhatsApp"],[/\bSnapchat[ /](\d+(?:\.\d+)*)?/i,"Snapchat"],[/\bBing(?:Web|Sapphire)\/(\d+(?:\.\d+)*)?/i,"Bing"],[/\bNAVER\(inapp; search;/i,"Naver",/\bNAVER\(inapp; search;[^;)]*; (\d+(?:\.\d+)*)/i],[/\bKAKAOTALK[ /](\d+\.\d+(?:\.\d+)*)?/i,"KakaoTalk"]],c2="[Truncated]",Yh="[Unserializable]";function Nu(t){let e="";for(let n=0;t.length>n;n++){const r=t.charCodeAt(n);if(55296>r||r>56319)e+=56320>r||r>57343?t[n]:"�";else{const s=t.charCodeAt(n+1);56320>s||s>57343?e+="�":(e+=t[n]+t[n+1],n++)}}return e}function Z5(t,e){if(!e)return t;let n=[];try{n=Object.keys(e)}catch{n=[]}for(const r of n){let s;try{s=e[r]}catch{s=Yh}Object.defineProperty(t,r,{value:s,enumerable:!0,writable:!0,configurable:!0})}return t}const rm=3e5;var q5=class{record(t){if(t.kind==="too-large")return;if(t.kind!=="retry-later")return void this.reset();if(!t.retryAfterMs)return;const e=this.isOpen(),n=Date.now(),r=Math.min(t.retryAfterMs,rm);if(!e)return this.ts=n,void(this.es=n+r);this.es=Math.max(this.es,Math.min(n+r,this.ts+rm))}remainingMs(){const t=Date.now();if(this.ts-5e3>t)return this.reset(),0;const e=Math.min(rm,Math.max(0,this.es-t));return e===0&&this.reset(),e}isOpen(){return this.remainingMs()>0}reset(){this.es=0,this.ts=0}constructor(){this.es=0,this.ts=0}};const F7=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Mk(t,e){return typeof(n=t)=="string"&&F7.test(n)?t:e();var n}function G5(t,e){const n=new Error(e);try{Object.defineProperty(n,"name",{value:t,writable:!0,enumerable:!0,configurable:!0})}catch{}return n}function Ya(t){return t&&t.split("#")[0]}function Ok(t){try{return t()}catch{return}}function K5(t,e){const n=setTimeout(t,e);return n!=null&&n.unref&&(n==null||n.unref()),n}function Lk(t,e,n){return Y5.apply(this,arguments)}function Y5(){return(Y5=Wt(function*(t,e,n){let r;try{return yield Promise.race([t,new Promise((s,i)=>{r=K5(()=>{try{n==null||n(),s()}catch(o){i(o)}},e)})])}finally{clearTimeout(r)}})).apply(this,arguments)}function Wf(t){return Wf=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Wf(t)}function V7(t,e,n){return(e=(function(r){var s=(function(i){if(Wf(i)!="object"||!i)return i;var o=i[Symbol.toPrimitive];if(o!==void 0){var l=o.call(i,"string");if(Wf(l)!="object")return l;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(i)})(r);return Wf(s)=="symbol"?s:s+""})(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Nk(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function $(t){for(var e=1;arguments.length>e;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Nk(Object(n),!0).forEach(function(r){V7(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Nk(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}let vf,Dk,jk,lu;function H7(t){var e;const n=globalThis._posthogChunkIds,r=globalThis._debugIds;if(!n&&!r)return;const s=n?Object.keys(n):[],i=r?Object.keys(r):[];if(lu&&$k(n,s,Dk)&&$k(r,i,jk))return lu;Dk=n?$({},n):void 0,jk=r?$({},r):void 0,lu={},(e=vf)!==null&&e!==void 0||(vf={});const o=(l,u)=>{for(const f of l){const h=u[f];if(!h)continue;const m=vf==null?void 0:vf[f];if(m){lu[m]=h;continue}const v=t(f);for(let w=v.length-1;w>=0;w--){var d;const _=(d=v[w])===null||d===void 0?void 0:d.filename;if(_){lu[_]=h,vf[f]=_;break}}}};return r&&o(i,r),n&&o(s,n),lu}function $k(t,e,n){return t&&n?e.length===Object.keys(n).length&&e.every(r=>t[r]===n[r]):t===n}var z7=class{constructor(t,e,n=[]){this.coercers=t,this.stackParser=e,this.modifiers=n}buildFromUnknown(t,e={}){const n=e&&e.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(n,e,0).apply(t),s=this.buildParsingContext(e),i=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(i,n),$exception_level:"error"}}modifyFrames(t){var e=this;return Wt(function*(){for(const n of t)n.stacktrace&&n.stacktrace.frames&&ze(n.stacktrace.frames)&&(n.stacktrace.frames=yield e.applyModifiers(n.stacktrace.frames));return t})()}coerceFallback(t){var e;return{type:"Error",value:"Unknown error",stack:(e=t.syntheticException)===null||e===void 0?void 0:e.stack,synthetic:!0}}parseStacktrace(t,e){var n;let r,s;if(t.cause!=null&&(r=this.parseStacktrace(t.cause,e)),t.stack!=""&&t.stack!=null)try{s=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?e.skipFirstLines:0),e.chunkIdMap)}catch{}return $($({},t),{},{cause:r,stack:s,errors:(n=t.errors)===null||n===void 0?void 0:n.map(i=>this.parseStacktrace(i,e))})}applyChunkIds(t,e){return t.map(n=>(n.filename&&e&&(n.chunk_id=e[n.filename]),n))}applyCoercers(t,e){for(const n of this.coercers)if(n.match(t))return n.coerce(t,e);return this.coerceFallback(e)}applyModifiers(t){var e=this;return Wt(function*(){let n=t;for(const r of e.modifiers)n=yield r(n);return n})()}convertToExceptionList(t,e){const n=[],r=(s,i,o)=>{var l;const u=n.length,d=i===void 0?$($({type:typeof e.type=="string"&&e.type.length>0?e.type:"generic"},typeof e.handled=="boolean"?{handled:e.handled}:e.handled===void 0?{handled:!0}:{}),{},{synthetic:typeof e.synthetic=="boolean"?e.synthetic:s.synthetic,exception_id:u}):{type:"chained",source:o,synthetic:s.synthetic,exception_id:u,parent_id:i},f={type:s.type,value:s.value,mechanism:d};s.stack&&(f.stacktrace={type:"raw",frames:s.stack}),n.push(f),s.cause&&r(s.cause,u,"cause");for(const h of(l=s.errors)!==null&&l!==void 0?l:[])r(h,u,"member")};return r(t),n}buildParsingContext(t){var e;return{chunkIdMap:H7(this.stackParser),skipFirstLines:(e=t.skipFirstLines)!==null&&e!==void 0?e:1}}getAggregateErrors(t){try{if(Ed(t)){let n=Object.getPrototypeOf(t);for(let r=0;n&&100>r;r++){var e;const s=(e=Object.getOwnPropertyDescriptor(n,"constructor"))===null||e===void 0?void 0:e.value;if(typeof s=="function"&&s.name==="AggregateError"){const i=t.errors;return ze(i)?i:void 0}n=Object.getPrototypeOf(n)}}}catch{}}buildCoercingContext(t,e,n=0){let r=0,s=0,i=!1;const o=new Set,l=[],u={},d=(m,v,w=0)=>{const _=f(v,w),x=_.apply;if(_.apply=M=>{l.push(m);try{return x(M)}finally{l.pop()}},w>4||w>0&&l.indexOf(m)!==-1)return this.coerceFallback(_);const b=typeof m=="object"&&m!==null||typeof m=="function";if(w===0&&r>=50||b&&o.has(m))return;b&&o.add(m),w===0&&r++;const k=this.getAggregateErrors(m);let C,P;i||(i=!!k);try{if(C=this.applyCoercers(m,_),!C)throw u}catch(M){if(M===u)return void(w===0&&r--);if(!i)throw M;C=this.coerceFallback(_)}if(!k||r>=50)return C;try{P=k.length}catch{return C}if(!Number.isInteger(P)||0>P||P>4294967295)return C;const T=[];for(let M=0;50>r&&1e3>s&&P>M;M++){let I;s++;try{I=_.next(k[M])}catch{r++,I=this.coerceFallback(f(v+1))}I&&T.push(I)}return $($({},C),{},{errors:T})},f=(m,v=0)=>$($({},e),{},{syntheticException:m==0?e.syntheticException:void 0,mechanism:m==0?t:{},apply(w){const _=d(w,m,v+1);if(!_)throw u;return _},next:w=>d(w,m+1)}),h=f(n);return $($({},h),{},{apply:m=>{var v;return(v=d(m,n))!==null&&v!==void 0?v:this.coerceFallback(h)}})}};const U7=/^([a-z][a-z0-9.+-]+):/i,B7=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function W7(t){if(!t||t==="<anonymous>")return!1;const e=U7.exec(t);return!e||B7.includes(e[1].toLowerCase())}function u2(t,e,n,r,s){const i={platform:t,filename:e,function:n==="<anonymous>"?"?":n,in_app:W7(e)};return ae(r)||(i.lineno=r),ae(s)||(i.colno=s),i}const X5=(t,e)=>{const n=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return n||r?[t.indexOf("@")!==-1?t.split("@")[0]:"?",n?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]},Z7=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,q7=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,G7=/\((\S*)(?::(\d+))(?::(\d+))\)/,K7=(t,e)=>{const n=Z7.exec(t);if(n){const[,s,i,o]=n;return u2(e,s,"?",+i,+o)}const r=q7.exec(t);if(r){if(r[2]&&r[2].indexOf("eval")===0){const o=G7.exec(r[2]);o&&(r[2]=o[1],r[3]=o[2],r[4]=o[3])}const[s,i]=X5(r[1]||"?",r[2]);return u2(e,i,s,r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},Y7=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,X7=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Q7=(t,e)=>{const n=Y7.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){const i=X7.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}let r=n[3],s=n[1]||"?";return[s,r]=X5(s,r),u2(e,r,s,n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Fk=/\(error: (.*)\)/;function $x(t,e){return t.filename===e.filename&&t.function===e.function&&t.module===e.module&&t.lineno===e.lineno&&t.colno===e.colno}function J7(t){for(let e=1;10>=e;e++){const n=t.length-2*e;if(0>n)break;let r=!0;for(let s=0;e>s;s++)if(!$x(t[n+s],t[n+e+s])){r=!1;break}if(r){for(let s=0;e>s;s++)t[n+s]=t[n+e+s];return t.length=n+e,{start:n,length:e}}}}function e$(t,e){const n=e.start+e.length,r=J5(t,e);r&&t.splice(n+r===t.length?n:e.start,r)}function Q5(t,e){let n=e.start;for(;n>0&&$x(t[n-1],t[n-1+e.length]);)n--;return e.start-n}function J5(t,e){const n=e.start+e.length;let r=n;for(;t.length>r&&$x(t[r],t[r-e.length]);)r++;return r-n}function t$(t,e){const n=e[0];let r=t.length-(n?Q5(t,n):0);for(const s of e)r-=J5(t,s);return r}function n$(t,e,n){for(let r=0;t.length>r;r++){const s=t[(e+r)%t.length],i=t[(n+r)%t.length];if(s!==i)return i>s}return!1}var r$=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,e){const n=rt(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:n?t.stack:void 0,cause:t.cause?e.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){const e=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${e}: ${t.message}`:e}isDOMException(t){return Om(t,"DOMException")}isDOMError(t){return Om(t,"DOMError")}},s$=class{match(t){return Ed(t)}coerce(t,e){var n;const r=this.getStack(t),s=r===void 0?(n=e.syntheticException)===null||n===void 0?void 0:n.stack:void 0,i=!!s;return{type:this.getType(t),value:this.getMessage(t,e),stack:r??s,cause:t.cause?e.next(t.cause):void 0,synthetic:i}}getType(t){return t.name||t.constructor.name}getMessage(t,e){const n=t.message;return String(n.error&&typeof n.error.message=="string"?n.error.message:n)}getStack(t){try{const e=t.stacktrace;if(typeof e=="string"&&e.length>0)return e;const n=t.stack;return typeof n=="string"&&n.length>0?n:void 0}catch{return}}},i$=class{match(t){return!!Om(t,"ErrorEvent")&&(t.error!=null||this.hr(t))}coerce(t,e){var n;if(t.error!=null)return e.apply(t.error);const r=e.apply(t.message);return $($({},r),{},{stack:(n=this.vr(t))!==null&&n!==void 0?n:r.stack,synthetic:!0})}hr(t){return rt(t.message)&&t.message.length>0}vr(t){var e,n;const r=t,s=(e=r.lineno)!==null&&e!==void 0?e:0,i=(n=r.colno)!==null&&n!==void 0?n:0;if(rt(r.filename)&&r.filename.length!==0&&s!==0)return`Error
|
|
18
18
|
at ${r.filename}:${s}:${i}`}};const o$=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;var a$=class{match(t){return typeof t=="string"}coerce(t,e){var n;const[r,s]=this.getInfos(t);return{type:r??"Error",value:s??t,stack:(n=e.syntheticException)===null||n===void 0?void 0:n.stack,synthetic:!0}}getInfos(t){let e="Error",n=t;const r=t.match(o$);return r&&(e=r[1],n=r[2]),[e,n]}};const l$=["fatal","error","warning","log","info","debug"];function eT(t,e=40){const n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(let r=n.length;r>0;r--){const s=n.slice(0,r).join(", ");if(e>=s.length)return r===n.length?s:s.length>e?`${s.slice(0,e)}...`:s}return""}var c$=class{match(t){return typeof t=="object"&&t!==null}coerce(t,e){var n,r;const s=this.getErrorPropertyFromObject(t);return s?e.apply(s):{type:this.getType(t),value:this.getValue(t),stack:(n=this.getStack(t))!==null&&n!==void 0?n:(r=e.syntheticException)===null||r===void 0?void 0:r.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){if(Dx(t))return t.constructor.name;const e="name"in t?t.name:void 0;return rt(e)&&!Bf(e)?e:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;const e=this.getObjectClassName(t);return`${e&&e!=="Object"?`'${e}'`:"Object"} captured as exception with keys: ${eT(t)}`}isSeverityLevel(t){return rt(t)&&!Bf(t)&&l$.indexOf(t)>=0}getStack(t){try{return rt(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:rt(t.stack)&&t.stack.length>0?t.stack:void 0}catch{return}}getErrorPropertyFromObject(t){for(const e in t)if({}.hasOwnProperty.call(t,e)){const n=t[e];if(Ed(n))return n}}getObjectClassName(t){try{const e=Object.getPrototypeOf(t);return e?e.constructor.name:void 0}catch{return}}},u$=class{match(t){return Dx(t)}coerce(t,e){var n;const r=t.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${eT(t)}`,stack:(n=e.syntheticException)===null||n===void 0?void 0:n.stack,synthetic:!0}}},d$=class{match(t){return g5(t)}coerce(t,e){var n;return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:(n=e.syntheticException)===null||n===void 0?void 0:n.stack,synthetic:!0}}},f$=class{match(t){return Om(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Dx(t))return!1;try{const e=t.detail;return e!=null&&typeof e=="object"&&"reason"in e}catch{return!1}}coerce(t,e){var n;const r=this.getUnhandledRejectionReason(t);return g5(r)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:(n=e.syntheticException)===null||n===void 0?void 0:n.stack,synthetic:!0}:e.apply(r)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};const jm="$message",$m="$timestamp",h$=new Set([jm,$m]),vy={enabled:!0,max_bytes:32768};function Fm(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:vy.enabled,max_bytes:m$(t.max_bytes,vy.max_bytes)}:$({},vy)}var p$=class{constructor(t){this.ns=[],this.ss=0,this.Ar=Fm(t)}setConfig(t){this.Ar=Fm(t),this.rs()}add(t){const e=(function(r){let s;try{s=p5(r)}catch{return}try{const i=JSON.parse(s);if(!nt(i))return;const o=i,l=o[jm],u=o[$m];return!rt(l)||l.trim().length===0||!rt(u)&&!Cn(u)?void 0:{step:o,json:s}}catch{return}})(t);if(!e)return;const n=(function(r){if("u">typeof TextEncoder)return new TextEncoder().encode(r).length;const s=encodeURIComponent(r);let i=0;for(let o=0;s.length>o;o++)s[o]==="%"?(i+=1,o+=2):i+=1;return i})(e.json);n>this.Ar.max_bytes||(this.ns.push({step:e.step,bytes:n}),this.ss+=n,this.rs())}getAttachable(){return this.ns.map(t=>t.step)}clear(){this.ns=[],this.ss=0}size(){return this.ns.length}rs(){for(;this.ss>this.Ar.max_bytes&&this.ns.length>0;){const t=this.ns.shift();t&&(this.ss-=t.bytes)}}};function m$(t,e){if(!Cn(t)||t===1/0||t===-1/0)return e;const n=Math.floor(t);return 0>n?e:n}const Vk=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Hk(t){return typeof t=="string"||t}function zk(t){return typeof t=="string"?t:void 0}const g$=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],tT="NativeGzipValidationError",d2=t=>t.length>=2&&t[0]===31&&t[1]===139,Uk=(t,e)=>t===s2.GZipJS||e===s2.GZipJS||e==="gzip",Bk=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError";let yf;const _0=t=>{throw G5(tT,`Native gzip produced invalid output: ${t}`)},v$=(Wk=Wt(function*(t,e){18>t.size&&_0("too-short");const n=new Uint8Array(yield t.slice(0,10).arrayBuffer());d2(n)&&n[2]===8||_0("invalid-header");const r=new DataView(yield t.slice(t.size-8).arrayBuffer());r.getUint32(0,!0)!==(i=>{const o=(()=>{if(yf)return yf;yf=[];for(let u=0;256>u;u++){let d=u;for(let f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;yf[u]=d>>>0}return yf})();let l=4294967295;for(let u=0;i.length>u;u++)l=o[255&(l^i[u])]^l>>>8;return(4294967295^l)>>>0})(e)&&_0("invalid-crc");const s=e.length>>>0;r.getUint32(4,!0)!==s&&_0("invalid-size")}),function(t,e){return Wk.apply(this,arguments)});var Wk;function f2(){return f2=Wt(function*(t,e=!0,n){try{const s=new TextEncoder().encode(t),i=new globalThis.CompressionStream("gzip"),o=i.writable.getWriter(),l=o.write(s).then(()=>o.close()).catch((r=Wt(function*(f){try{yield o.abort(f)}catch{}throw f}),function(f){return r.apply(this,arguments)})),u=new Response(i.readable).blob(),[d]=yield Promise.all([u,l]);return yield v$(d,s),d}catch(s){if(n!=null&&n.rethrow)throw s;return e&&console.error("Failed to gzip compress data",s),null}var r}),f2.apply(this,arguments)}function nT(t,e){if(t==null)return{};var n,r,s=(function(o,l){if(o==null)return{};var u={};for(var d in o)if({}.hasOwnProperty.call(o,d)){if(l.includes(d))continue;u[d]=o[d]}return u})(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;i.length>r;r++)e.includes(n=i[r])||{}.propertyIsEnumerable.call(t,n)&&(s[n]=t[n])}return s}const Pr="[redacted]",y$=/^[A-Za-z0-9+/\n\r]+=*$/,_$=/^[A-Za-z0-9_-]+={0,2}$/,w$=/[-_]/,x$=/^data:[^,\s]*;base64,/i,b$=/^[A-Za-z0-9+/_-]+={0,2}$/,S$=/\bph[a-z]_[A-Za-z0-9_-]{20,}\b/g,k$=/^(authorization|cookie|set-cookie|x-api-key|api[-_]?key|api[-_]?token|access[-_]?token|refresh[-_]?token|token|password|secret|client[-_]?secret|private[-_]?key)$/i,rT=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi,E$=/[\s<>"]/,sT=new RegExp(rT.source,"i"),iT=/[a-z][a-z0-9+.-]{0,63}:\/\//i,C$=new RegExp(`^${iT.source}`,"i"),P$=new RegExp(iT.source,"gi"),A$=/(^|[-_./;])(auth|token|secret|password|passwd|pwd|credential|signature|sig|key|hmac|sas|bearer|jwt|session|sessionid)([-_./;]|$)/i,T$=/^(code|AWSAccessKeyId|GoogleAccessId|Policy)$/i,R$=/[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/g,I$=/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,M$=/\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b/g,O$=/(^|[^\w:])((?:(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}|(?:[0-9A-Fa-f]{1,4}:){1,7}:|(?:[0-9A-Fa-f]{1,4}:){1,6}:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){0,5}|::(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){0,6})))(?=$|[^\w:])/g,L$=/\b\d{3}[ .-]\d{2}[ .-]\d{4}\b/g,N$=/\b\d(?:[ ./-]?\d){12,}\b/g,Zk=/\d+/g,D$=/(^|[^\w+])((?:\+?1[ ./-]?)?(?:\(\d{3}\)[ ./-]?|\d{3}[ ./-])\d{3}[ ./-]\d{4})(?![\w])/g,j$=/(^|[^\w])(\+\d{1,3}(?:[ ./()-]{0,2}\d){7,13})(?![\w])/g;function h2(t){return(function(e){return k$.test(e)})(t)||A$.test(t)||T$.test(t)}function yy(t){return t.split("&",129).length>128}function $$(t,e,n){return h2(t)||e.includes(";")&&(function(r){return r.split(";").some(s=>h2(s.split("=",1)[0]))})(e)?Pr:sT.test(e)?n?Fx(e,{allowNestedUrls:!1,stripPunctuation:!0}):Pr:e}function oT(t,e){const n=new URLSearchParams;let r=!1,s=!1;for(const[i,o]of new URLSearchParams(t)){const l=Vm(i),u=Vm(o);r||(r=l!==i||u!==o);const d=$$(l,u,e);r||(r=d!==u),s=h2(l)||d!==u,n.append(l,d)}return{changed:r,lastFieldSensitive:s,serialized:n.toString()}}function qk(t,e){if(!t.includes("="))return{value:F$(t,e),lastFieldSensitive:!1};const n=oT(t,e);return{value:n.changed?n.serialized:t,lastFieldSensitive:n.lastFieldSensitive}}function F$(t,e){return e?Fx(t,{allowNestedUrls:!1,stripPunctuation:!0}):sT.test(t)?Pr:t}function V$(t,e,n){return t==="#"?!e.fragment&&(e.fragment=!0):t==="?"&&(e.fragment?n!=="="&&!e.fragmentQuery&&(e.fragmentQuery=!0):!e.query&&(e.query=!0))}function _y(t,e){var n;if(t.length>8192&&C$.test(t))return Pr;const{address:r,suffix:s}=e.stripPunctuation?(function(x){let b=x.length;for(;b>0&&".,;:!?)]}'".includes(x[b-1]);)b--;return{address:x.slice(0,b),suffix:x.slice(b)}})(t):{address:t,suffix:""};let i;try{i=new URL(r)}catch{return Pr+s}const o=i.search.slice(1),l=i.hash!=="",u=(function(x){const b=x.slice(1),k=b.indexOf("?");return 0>k?{head:b,tail:null}:{head:b.slice(0,k),tail:b.slice(k+1)}})(i.hash);if(yy(o)||yy(u.head)||yy((n=u.tail)!==null&&n!==void 0?n:""))return Pr+s;let d=!1;(i.username||i.password)&&(i.username=Pr,i.password="",d=!0);const f=oT(o,e.allowNestedUrls);f.changed&&(i.search=f.serialized,d=!0);const h=qk(u.head,e.allowNestedUrls),m=u.tail===null?null:(v=u.tail,h.lastFieldSensitive?{value:v===""?"":Pr,lastFieldSensitive:!0}:qk(v,e.allowNestedUrls));var v;const w=m===null?h.value:`${h.value}?${m.value}`;w!==i.hash.slice(1)&&(i.hash=w,d=!0);const _=l?m??h:f;return(d?Vm(i.toString()):r)+(_.lastFieldSensitive?"":s)}function Fx(t,e){return t.replace(rT,n=>(function(r,s){const i=(function(u){if(!u.includes("://"))return[];const d=[...u.matchAll(P$)].map(_=>_.index),f=[],h={query:!1,fragment:!1,fragmentQuery:!1};let m=0,v=!1,w="";for(let _=0;u.length>_&&d.length>m;_++){d[m]===_&&(_>0&&w!=="="&&f.push(_),m++);const x=u[_];V$(x,h,w)?(w=x,v=!0):v&&"=&".includes(x)&&(w=x)}return f})(r);if(i.length===0)return _y(r,s);let o="",l=0;for(const u of i)o+=_y(r.slice(l,u),$($({},s),{},{stripPunctuation:!1})),l=u;return o+_y(r.slice(l),s)})(n,$($({},e),{},{stripPunctuation:e.stripPunctuation&&n.length!==t.length})))}function Vm(t){return t.replace(S$,Pr)}function aT(t,e){return(function(n){return n.length>=10240&&(y$.test(n)||(function(r){const s=x$.exec(r);if(!s)return!1;let i;try{i=decodeURIComponent(r.slice(s[0].length))}catch{return!1}return b$.test(i.replace(/[\r\n]/g,""))})(n)||w$.test(n)&&_$.test(n))})(t)?"[binary data redacted - not supported by PostHog MCP analytics]":(function(n,r,s){const i=4*s.maxStringLength;if(n.length>i){const o=r(n.slice(0,(function(l,u){let d=u;for(;d>0&&!E$.test(l[d-1]);)d--;return d})(n,i)));if(o.length>=2*s.maxStringLength)return o+s.truncationSuffix}return r(n)})(t,n=>(function(r){return Fx(r,{allowNestedUrls:!0,stripPunctuation:!0})})((function(r){let s=r.replace(R$," ");return s=s.replace(I$,Pr),s=s.replace(M$,Pr),s=s.replace(O$,`$1${Pr}`),s=s.replace(N$,z$),s=s.replace(L$,Pr),s=s.replace(D$,`$1${Pr}`),s=s.replace(j$,`$1${Pr}`),s})(Vm(n))),e)}function H$(t){let e=0,n=!1;for(let r=t.length-1;r>=0;r--){let s=t.charCodeAt(r)-48;if(0>s||s>9)return!1;n&&(s*=2,s>9&&(s-=9)),e+=s,n=!n}return e%10==0}function z$(t){const e=[];for(let i=Zk.exec(t);i!==null;i=Zk.exec(t))e.push({digits:i[0],start:i.index,end:i.index+i[0].length});let n="",r=0,s=0;for(;e.length>s;){let i="",o=-1;for(let l=s;e.length>l&&(i+=e[l].digits,19>=i.length);l++)i.length>=13&&H$(i)&&(o=l);0>o?s++:(n+=t.slice(r,e[s].start)+Pr,r=e[o].end,s=o+1)}return n+t.slice(r)}const U$={}.propertyIsEnumerable;function Hm(t,e){try{return lT(t,e,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function Vx(t,e,n,r){if(0>=n.remainingNodes)return{stringValue:c2};if(n.remainingNodes--,Hr(t))return{boolValue:t};if(typeof t=="bigint")return(function(s,i){const o=s.toString(),l=BigInt("9223372036854775808");return s>=l||-l>s?(i==null||i.debug(`Attribute ${o} is outside the int64 range; encoding it as a string`),{stringValue:o}):{intValue:o}})(t,e);if(typeof t=="number"){if(!Number.isFinite(t))return{stringValue:String(t)};if(Number.isInteger(t)){if(Number.isSafeInteger(t))return{intValue:String(t)};if(typeof BigInt>"u")return{stringValue:String(t)};const s=BigInt(t).toString();return t>=9223372036854776e3||-9223372036854776e3>t?(e==null||e.debug(`Attribute ${s} is outside the int64 range; encoding it as a string`),{stringValue:s}):{intValue:s}}return{doubleValue:t}}if(typeof t=="string")return{stringValue:Nu(t)};if(typeof t=="function")return{stringValue:"[Function]"};if(typeof t=="symbol")return{stringValue:String(t)};if(typeof t=="object"&&t!==null){if(n.ancestors.has(t))return{stringValue:"[Circular]"};if(r>=20)return{stringValue:c2};if(t instanceof Date){const s=t.getTime(),i=Number.isFinite(s)?t.toISOString():String(t);return{stringValue:typeof i=="string"?Nu(i):String(i)}}n.ancestors.add(t);try{try{const s=t.toJSON;if(typeof s=="function")return Vx(s.call(t),e,n,r+1)}catch{}return ze(t)?{arrayValue:{values:B$(t,e,n,r+1)}}:{kvlistValue:{values:lT(t,e,n,r+1)}}}finally{n.ancestors.delete(t)}}return{stringValue:Nu(String(t))}}function B$(t,e,n,r){const s=[],i=Math.min(t.length,1e3);let o=0;for(;i>o&&n.remainingNodes>0;o++)try{const l=o in t?t[o]:void 0;if(Xe(l))continue;s.push(Vx(l,e,n,r))}catch{s.push({stringValue:Yh})}return t.length>o&&s.push({stringValue:c2}),s}function lT(t,e,n,r){const s=[];for(const i in t)if(U$.call(t,i)){if(!i){e==null||e.debug("Dropping an attribute with an empty key");continue}if(s.length>=1e3||0>=n.remainingNodes){e==null||e.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{const o=t[i];if(dn(o)||ae(o))continue;s.push({key:Nu(i),value:Vx(o,e,n,r)})}catch{s.push({key:Nu(i),value:{stringValue:Yh}})}}return s}function cT(t,e,n){return $($($($({},Z5({},t.resourceAttributes)),{},{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment}),t.serviceVersion&&{"service.version":t.serviceVersion}),{},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}const W$=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function uT(t,e){const n=Z5({},t),r={};for(const s of W$)({}).hasOwnProperty.call(n,s)&&(r[s]=n[s],delete n[s]);return[...Hm(n,e),...Hm(r,e)]}const Gk={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"},dT={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},Z$=dT.info;function q$(t){try{return Nu(String(t))}catch{return Yh}}function G$(t,e,n,r){const s=t.level||"info",{text:i,number:o}=dT[s]||Z$,l=(function(m=Date.now()){return String(m)+"000000"})(Cn(r)?r:void 0),u={};e.distinctId&&(u.posthogDistinctId=e.distinctId),e.sessionId&&(u.sessionId=e.sessionId),e.windowId&&(u["window.id"]=e.windowId),Xe(e.sessionStartTimestamp)||(u.sessionStartTimestamp=String(e.sessionStartTimestamp)),Xe(e.lastActivityTimestamp)||(u.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(u["url.full"]=e.currentUrl),e.screenName&&(u["screen.name"]=e.screenName),e.appState&&(u["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(u.feature_flags=e.activeFeatureFlags);const d=$({},u),f=t.attributes;if(f){let m=[];try{m=Object.keys(f)}catch{m=[]}for(const v of m){let w;try{w=f[v]}catch{w=Yh}Object.defineProperty(d,v,{value:w,enumerable:!0,writable:!0,configurable:!0})}}const h={timeUnixNano:l,observedTimeUnixNano:l,severityNumber:o,severityText:i,body:{stringValue:q$(t.body)},attributes:Hm(d,n)};return t.trace_id&&(h.traceId=t.trace_id),t.span_id&&(h.spanId=t.span_id),ae(t.trace_flags)||(h.flags=t.trace_flags),h}function fT(t,e,n){return cT(t,e,n)}function hT(t,e,n,r){return{resourceLogs:[{resource:{attributes:uT(e)},scopeLogs:[{scope:{name:n,version:r},logRecords:t}]}]}}var pT=class{constructor(t){this.ls=t,this.us=0}get pending(){return!!this.cs}arm(t){this.clear(),this.us=Date.now()+t,this.cs=K5(()=>{this.cs=void 0,this.ls()},t)}armNoEarlierThan(t){this.cs&&Date.now()+t<=this.us||this.arm(t)}clear(){this.cs&&(clearTimeout(this.cs),this.cs=void 0)}};function mT(){return .75+.5*Math.random()}function gT(t,e,n,r){const s=Math.min(Math.max(0,e-1),6),i=t*Math.pow(2,s);return Math.round(Math.min(i,Math.max(r,t))*n)}var K$=class{constructor(t,e,n,r,s,i=()=>Promise.resolve(),o){var l;this._instance=t,this.Ar=e,this.$=n,this.hs=r,this.ds=s,this.vs=i,this.fs=o,this.ps=new pT(()=>this.gs()),this.ys=null,this.bs=0,this._s=0,this.ws=new q5,this.ks=0,this.Ss=1,this.xs=0,this.$s=0,this.Cs=!1,this.Ts=e.maxBufferSize,this.Is=Math.max((l=e.maxQueueSize)!==null&&l!==void 0?l:e.maxBufferSize,e.maxBufferSize),this.Ms=e.flushIntervalMs,this.Es=e.maxBatchRecordsPerPost,this.Ps=e.rateCapWindowMs,this.Rs=e.maxLogsPerInterval}clearQueue(){this._s++,this._instance.setPersistedProperty(ji.LogsQueue,[])}reset(){this.ps.clear(),this.xs=0,this.$s=0,this.Cs=!1,this.ks=0,this.Ss=1,this.ws.reset(),this.Es=this.Ar.maxBatchRecordsPerPost}onReconnect(){this.ks=0,this.Ss=1,this.ws.isOpen()?this.As()&&this.Fs():this.gs()}captureLog(t,e){var n;if(this._instance.isDisabled||this._instance.optedOut||!(t!=null&&t.body))return;const r=this.Os(t);if(r===null)return;if(!r.body)return void this.$.info("Log was rejected in beforeSend function");if(!this.Ds())return;const s={record:G$(r,(n=e==null?void 0:e.context)!==null&&n!==void 0?n:this.hs(),this.$,e==null?void 0:e.occurredAtMs)};this.ds(()=>this.Ls(s))}Os(t){const e=this.Ar.beforeSend;if(!e)return t;const n=ze(e)?e:[e];let r=t;for(const s of n)try{const i=s(r);if(!i)return this.$.info("Log was rejected in beforeSend function"),null;r=i}catch(i){return this.$.error("Error in beforeSend function for log:",i),null}return r}Ds(){if(this.Rs===void 0)return!0;const t=Date.now(),e=t-this.xs;return this.Ps>e&&e>=0||(this.xs=t,this.$s=0,this.Cs=!1),this.Rs>this.$s?(this.$s++,!0):(this.Cs||(this.$.warn(`captureLog dropping logs: exceeded ${this.Rs} logs per ${this.Ps}ms`),this.Cs=!0),!1)}flush(){var t=this;return Wt(function*(){if(!t._instance.isDisabled)return t.ys||(t.ys=t.Ns().finally(()=>{t.ys=null})),t.ys})()}Ns(){var t=this;return Wt(function*(){var e;t.ps.clear();let n=(e=t._instance.getPersistedProperty(ji.LogsQueue))!==null&&e!==void 0?e:[];if(n.length===0)return;const r=n.length;let s=0;for(;n.length>0&&r>s;){var i,o;const l=t._s;t.bs=0;const u=Math.min(n.length,t.Es),d=n.slice(0,u),f=hT(d.map(m=>m.record),t.qs(),(i=t.fs)!==null&&i!==void 0?i:t._instance.getLibraryId(),t._instance.getLibraryVersion()),h=yield t._instance.js(f);if(t._s!==l)return;if(h.kind==="too-large"&&d.length>1)t.Es=Math.max(1,Math.floor(d.length/2)),t.$.warn(`Logs batch of size ${d.length} was too large for the ingestion endpoint, reducing batch size to ${t.Es}`);else if(t.ws.record(h),t.ps.pending&&t.ps.arm(Math.max(t.Ms,t.ws.remainingMs())),h.kind==="retry-later"||(h.kind==="too-large"?t.$.warn("Dropping a single log record with batch size 1 — the record is larger than the server cap and cannot be split further."):h.kind==="ok"&&t.Ar.maxBatchRecordsPerPost>t.Es&&(t.Es=Math.min(t.Ar.maxBatchRecordsPerPost,t.Es+1)),yield t.Bs(d.length),n=(o=t._instance.getPersistedProperty(ji.LogsQueue))!==null&&o!==void 0?o:[],s+=d.length,h.kind==="fatal"))throw h.error}})()}Bs(t){var e=this;return Wt(function*(){var n;const r=Math.max(0,t-e.bs),s=(n=e._instance.getPersistedProperty(ji.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(ji.LogsQueue,s.slice(r)),yield e.vs()})()}qs(){return fT(this.Ar,this._instance.getLibraryId(),this._instance.getLibraryVersion())}Ls(t){var e;if(this._instance.optedOut)return;const n=(e=this._instance.getPersistedProperty(ji.LogsQueue))!==null&&e!==void 0?e:[];this.Is>n.length||(n.shift(),this.bs++,this.$.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(ji.LogsQueue,n),this.Ts>n.length||this.ws.isOpen()?this.Fs():this.gs()}Fs(){this.ps.pending||this.ps.arm(Math.max(this.Ms,this.ws.remainingMs()))}zs(){return Math.max(gT(this.Ms,this.ks,this.Ss,3e4),this.ws.remainingMs())}As(){const t=this._instance.getPersistedProperty(ji.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return Wt(function*(){e.ps.clear();const n=e.flush().catch(()=>{});t!==void 0?yield Lk(n,t):yield n})()}flushWithTimeout(t){var e=this;return Wt(function*(){const n=e.flush();yield Lk(n,t,()=>{n.catch(()=>{})})})()}gs(){this.flush().then(()=>{this.ks=0,this.Ss=1},t=>{this.ks++,this.Ss=mT(),this.$.error("PostHog logs flush failed:",t)}).finally(()=>{!this._instance.isDisabled&&this.As()&&this.ps.armNoEarlierThan(this.zs())})}};const Y$=/^[0-9a-f]+$/;function Kk(t,e,n){return typeof t=="string"&&t.length===e&&t!==n&&Y$.test(t)}const X$=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/,Q$="00",wy=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function p2(t){return String(t)+"000000"}function Yk(t,e,n,r){let s="";return r&&(s=Object.keys(r).sort().map(i=>`${JSON.stringify(i)}:${JSON.stringify(r[i])}`).join(",")),`${t}\0${e}\0${n??""}\0${s}`}var J$=class{constructor(t,e,n){this._instance=t,this.Ar=e,this.$=n,this.Hs=new Map,this.ps=new pT(()=>this.flush().catch(r=>{this.$.error("Metrics flush failed:",r)})),this.ys=null,this.Us=!1,this.Ws=new Map,this.Vs=new Set,this.ws=new q5,this.ks=0,this.Ss=1,this.Gs=0}count(t,e=1,n){this.Qs({name:t,type:"count",value:e,unit:n==null?void 0:n.unit,attributes:n==null?void 0:n.attributes})}gauge(t,e,n){this.Qs({name:t,type:"gauge",value:e,unit:n==null?void 0:n.unit,attributes:n==null?void 0:n.attributes})}histogram(t,e,n){this.Qs({name:t,type:"histogram",value:e,unit:n==null?void 0:n.unit,attributes:n==null?void 0:n.attributes})}flush(){var t=this;const e=this.ys,n=(function(){var r=Wt(function*(){e&&(yield e.catch(()=>{})),yield t.Zs()});return function(){return r.apply(this,arguments)}})()().finally(()=>{this.ys===n&&(this.ys=null)});return this.ys=n,n}drainWindow(){if(this.Hs.size===0)return null;const t=this.Hs;return this.Hs=new Map,this.Us=!1,this.Ws=new Map,this.Vs=new Set,this.Js(t)}reset(){this.Gs++,this.ws.reset(),this.ks=0,this.Ss=1,this.ps.clear(),this.Hs=new Map,this.ys=null,this.Us=!1,this.Ws=new Map,this.Vs=new Set}Qs(t){if(this._instance.isDisabled||this._instance.optedOut)return;const e=this.Os(t);if(e===null)return;if(!e.name||typeof e.name!="string")return void this.$.warn("Dropping metric with empty name");if(typeof e.value!="number"||!Number.isFinite(e.value))return void this.$.warn(`Dropping metric '${e.name}': value must be a finite number`);if(e.type==="count"&&0>e.value)return void this.$.warn(`Dropping count '${e.name}': counters are monotonic, value must be >= 0`);let n,r;try{n=e.attributes?$({},e.attributes):void 0,r=Yk(e.type,e.name,e.unit,n)}catch(l){return void this.$.warn(`Dropping metric '${e.name}': attributes could not be serialized`,l)}let s=this.Hs.get(r);if(!s){if(!this.Ks())return;s={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Hs.set(r,s)}const i=this.Ws.get(e.name);i===void 0?this.Ws.set(e.name,e.type):i===e.type||this.Vs.has(e.name)||(this.Vs.add(e.name),this.$.warn(`Metric name '${e.name}' is already used as a ${i}; recording it as a ${e.type} too will blend both series in charts. Use a distinct name.`)),this.Xs(s,e.value);const o=this.Ys();o&&(s.exemplar=$($({},o),{},{value:e.value,timeMs:Date.now()})),this.Fs()}Ys(){try{var t,e;const n=(function(r){const s=(function(o){if(typeof o!="string")return;const l=X$.exec(o.trim());if(!l)return;const[,u,d,f,h,m]=l;return u==="ff"||u==="00"&&m||!(function(v){return Kk(v,32,"00000000000000000000000000000000")})(d)||!(function(v){return Kk(v,16,"0000000000000000")})(f)?void 0:{version:u,traceId:d,spanId:f,flags:h}})(r);return s&&{traceId:s.traceId,spanId:s.spanId,flags:(i=s.flags,1&parseInt(i,16)?"01":Q$)};var i})((t=(e=this._instance).getActiveSpan)===null||t===void 0||(t=t.call(e))===null||t===void 0?void 0:t.traceparent());if(n&&n.flags==="01")return{traceId:n.traceId,spanId:n.spanId}}catch{}}Ks(){return this.Ar.maxSeriesPerFlush>this.Hs.size||(this.Us||(this.Us=!0,this.$.warn(`Metric series cap reached (${this.Ar.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}Xs(t,e){switch(t.type){case"count":var n;t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":{t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(wy.length+1).fill(0)});const r=t.hist;r.count+=1,r.sum+=e,r.min=Math.min(r.min,e),r.max=Math.max(r.max,e),r.bucketCounts[(function(s,i){for(let o=0;i.length>o;o++)if(i[o]>=s)return o;return i.length})(e,wy)]+=1;break}}}Os(t){const e=this.Ar.beforeSend;if(!e)return t;const n=ze(e)?e:[e];let r=t;for(const s of n)try{const i=s(r);if(!i)return this.$.info("Metric was rejected in beforeSend function"),null;r=i}catch(i){return this.$.error("Error in beforeSend function for metric:",i),null}return r}Fs(){this.ps.pending||this.ps.arm(this.zs())}zs(){return Math.max(gT(this.Ar.flushIntervalMs,this.ks,this.Ss,3e4),this.ws.remainingMs())}Zs(){var t=this;return Wt(function*(){if(t.ps.clear(),t.Hs.size===0)return;const e=t.Hs;t.Hs=new Map,t.Us=!1,t.Ws=new Map,t.Vs=new Set;const n=t.Gs,r=yield t._instance.po(t.Js(e));if(n===t.Gs)switch(t.ws.record(r),r.kind==="retry-later"?(t.ks++,t.Ss=mT()):(t.ks=0,t.Ss=1),t.ps.pending&&t.ps.arm(t.zs()),r.kind){case"ok":return;case"retry-later":return t.mo(e),void t.ps.armNoEarlierThan(t.zs());case"too-large":return void t.$.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.$.error("Failed to send metrics batch:",r.error)}})()}Js(t){return e=this.yo(t),n=(function(i,o,l){return cT(i,o,l)})(this.Ar,this._instance.getLibraryId(),this._instance.getLibraryVersion()),r=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:uT(n)},scopeMetrics:[{scope:{name:r,version:s},metrics:e}]}]};var e,n,r,s}yo(t){const e=p2(Date.now()),n=new Map;for(const o of t.values()){var r;const l=Yk(o.type,o.name,o.unit,void 0);let u=n.get(l);u||(u=$({name:o.name},o.unit&&{unit:o.unit}),o.type==="count"?u.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:o.type==="gauge"?u.gauge={dataPoints:[]}:u.histogram={aggregationTemporality:1,dataPoints:[]},n.set(l,u));const d=Hm((r=o.attributes)!==null&&r!==void 0?r:{},this.$),f=p2(o.windowStartMs),h=eF(o.exemplar);if(o.type==="count"){var s;const m=$({attributes:d,startTimeUnixNano:f,timeUnixNano:e,asDouble:(s=o.total)!==null&&s!==void 0?s:0},h);u.sum.dataPoints.push(m)}else if(o.type==="gauge"){var i;const m=$({attributes:d,timeUnixNano:e,asDouble:(i=o.last)!==null&&i!==void 0?i:0},h);u.gauge.dataPoints.push(m)}else if(o.hist){const m=$({attributes:d,startTimeUnixNano:f,timeUnixNano:e,count:o.hist.count,sum:o.hist.sum,min:o.hist.min,max:o.hist.max,bucketCounts:o.hist.bucketCounts,explicitBounds:wy},h);u.histogram.dataPoints.push(m)}}return Array.from(n.values())}mo(t){for(const[s,i]of t){var e;const o=this.Hs.get(s);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,i.windowStartMs),o.exemplar=(e=o.exemplar)!==null&&e!==void 0?e:i.exemplar,o.type){case"count":var n,r;o.total=((n=o.total)!==null&&n!==void 0?n:0)+((r=i.total)!==null&&r!==void 0?r:0);break;case"gauge":break;case"histogram":if(i.hist)if(o.hist){o.hist.count+=i.hist.count,o.hist.sum+=i.hist.sum,o.hist.min=Math.min(o.hist.min,i.hist.min),o.hist.max=Math.max(o.hist.max,i.hist.max);for(let l=0;o.hist.bucketCounts.length>l;l++)o.hist.bucketCounts[l]+=i.hist.bucketCounts[l]}else o.hist=i.hist}else this.Ks()&&this.Hs.set(s,i)}}};function eF(t){return t?{exemplars:[{filteredAttributes:[],timeUnixNano:p2(t.timeMs),asDouble:t.value,traceId:t.traceId,spanId:t.spanId}]}:{}}const vT=(t,{debugEnabled:e}={})=>{const n={N(r,...s){let i;try{i=typeof window>"u"?void 0:window}catch{return}i&&(Ho.DEBUG||i.POSTHOG_DEBUG||e)&&!ae(i.console)&&i.console&&("__rrweb_original__"in i.console[r]?i.console[r].__rrweb_original__:i.console[r])(t,...s)},debug(...r){n.N("debug",...r)},info(...r){n.N("log",...r)},warn(...r){n.N("warn",...r)},error(...r){n.N("error",...r)},critical(...r){console.error(t,...r)},uninitializedWarning(r){n.error(`You must initialize PostHog before calling ${r}`)},createLogger:(r,s)=>vT(`${t} ${r}`,s)};return n},he=vT("[PostHog.js]"),an=he.createLogger,tF=an("[ExternalScriptsLoader]"),zm=t=>{const e=ke==null?void 0:ke.querySelectorAll("script");if(e){for(let n=0;e.length>n;n++)if(e[n].src===t||e[n].getAttribute("src")===t)return e[n]}},Bl=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return tF.warn(`${e} was requested but loading of external scripts is disabled.`),n("Loading of external scripts is disabled");const r=zm(e);if(r){if(r.__posthog_loading_callback_fired)return n();const i=r.__posthog_loading_error;return i?n(i):(r.addEventListener("load",o=>{r.__posthog_loading_callback_fired=!0,n(void 0,o)}),void r.addEventListener("error",o=>{r.__posthog_loading_error=o,n(o)}))}const s=()=>{if(!ke)return n("document not found");if(zm(e))return Bl(t,e,n);let i=ke.createElement("script");if(i.type="text/javascript",i.crossOrigin="anonymous",i.src=e,i.onload=l=>{i.__posthog_loading_callback_fired=!0,n(void 0,l)},i.onerror=l=>{i.__posthog_loading_error=l,n(l)},t.config.prepare_external_dependency_script&&(i=t.config.prepare_external_dependency_script(i)),!i)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")ke.head.appendChild(i);else{const l=ke.querySelectorAll("body > script");var o;l.length>0?(o=l[0].parentNode)===null||o===void 0||o.insertBefore(i,l[0]):ke.body.appendChild(i)}};ke!=null&&ke.body?s():ke==null||ke.addEventListener("DOMContentLoaded",s)},xy={},Xk=(t,e)=>{let n=`/static/${e}.js?v=${t.version}`;return e==="toolbar"&&(n=`${n}&t=${Math.floor(Date.now()/3e5)*3e5}`),t.requestRouter.endpointFor("assets",n)};qe.__PosthogExtensions__=qe.__PosthogExtensions__||{},qe.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e==="remote-config"){const s=t.requestRouter.endpointFor("assets",`/array/${t.config.token}/config.js`);return void Bl(t,s,n)}const r=t.config.strict_script_versioning;if(r){const s=t.requestRouter.endpointFor("assets",`/static/${t.version}/${e}.js`),i=xy[s];if(r==="fallback"&&i){if(zm(i))return void Bl(t,i,n);delete xy[s]}return void Bl(t,s,r==="fallback"?(o,l)=>{if(o)if(typeof o=="string")n(o);else{var u;const d=Xk(t,e);xy[s]=d;const f=zm(s);f==null||(u=f.parentNode)===null||u===void 0||u.removeChild(f),Bl(t,d,n)}else n(void 0,l)}:n)}Bl(t,Xk(t,e),n)},qe.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{const r=t.requestRouter.endpointFor("api",e);Bl(t,r,n)},Ho.DEBUG=!1,Ho.LIB_VERSION="1.442.1",Ho.LIB_NAME="web";var Jr=Ho;const m2="$early_access_features",jo="$active_feature_flags",lc="$feature_flag_details",mh="$feature_flag_errors",Ba="$feature_flag_evaluated_at",cc="$feature_flag_request_id",Zf="$minimal_flag_called_events",wi="$enabled_feature_flags",ja="$stored_group_properties",$a="$stored_person_properties",$o="$flag_call_reported",Lf="$flag_call_reported_session_id",Fa="$feature_flag_payloads",Di="$override_feature_flags",Wl="$override_feature_flag_payloads",Du="visibilitychange",yT="$autocapture_disabled_server_side",Nf="$surveys",Um="$surveys_loaded_at",Hx="PostHog loadExternalDependency extension not found.",g2="$surveys_activated",sm="$surveys_activated_session",im="$surveys_activated_timestamps",nF="$people_distinct_id",qs="distinct_id",zx="$device_id",by="$device_model",Bm="__alias",rF="__cmpns",Qk="$fbc",ju="$fbc_persistence",Jk="$fbp",qf="$fbp_persistence",v2="__timers",y2="$heatmaps_enabled_server_side",_2="$exception_capture_enabled_server_side",_T="$error_tracking_suppression_rules",w2="$error_tracking_capture_extension_exceptions",x2="$web_vitals_enabled_server_side",Ux="$dead_clicks_enabled_server_side",Bx="$product_tours_enabled_server_side",wT="$logs_capture_enabled_server_side",xT="$web_vitals_allowed_metrics",Gf="$session_recording_remote_config",sF="$session_recording_enabled_server_side",iF="$replay_sample_rate",oF="$replay_override_sampling",aF="$replay_override_linked_flag",lF="$replay_override_url_trigger",cF="$replay_override_event_trigger",Cu="$sesid",bT="$session_is_sampled",uF="$session_past_minimum_duration",dF="$session_recording_url_trigger_activated_session",fF="$session_recording_event_trigger_activated_session",hF="$debug_first_full_snapshot_timestamp",pF="$sess_rec_flush_size",ST="$groups",b2="ph_product_tours",mF="$product_tours_activated",gF="$product_tours_activated_session",vF="$conversations_widget_session_id",yF="$conversations_ticket_id",_F="$conversations_widget_state",wF="$conversations_user_traits",Cr="$user_state",S2="$client_session_props",xF="$capture_rate_limit",kT="$initial_campaign_params",ET="$initial_referrer_info",Pu="$initial_person_info",Wx="$epp",Sy="$posthog_cookieless",CT="$cookieless_mode",PT="$sdk_debug_extensions_init_method",AT="$sdk_debug_extensions_init_time_ms",Zx="$sdk_debug_recording_script_not_loaded",qx="$sdk_debug_replay_stale_config",TT="$sdk_debug_replay_event_trigger_status",RT="$sdk_debug_replay_linked_flag_trigger_status",IT="$sdk_debug_replay_matched_recording_trigger_groups",MT="$sdk_debug_replay_pending_trigger_conditions",OT="$sdk_debug_replay_remote_trigger_matching_config",LT="$sdk_debug_replay_trigger_groups_count",NT="$sdk_debug_replay_url_trigger_status",bF="$session_recording_start_reason",Fo="anonymous",om="identified",DT="identified_only",Wm="beforeunload",Gx="$pageview",e8="$pageleave",jT="$identify",t8="$groupidentify";function Au(t,e){ze(t)&&t.forEach(e)}function Pt(t,e){if(!Xe(t))if(ze(t))t.forEach(e);else if((n=>n instanceof FormData)(t))t.forEach((n,r)=>e(n,r));else for(const n in t)Nx.call(t,n)&&e(t[n],n)}const en=function(t,...e){for(const n of e)for(const r in n)n[r]!==void 0&&(t[r]=n[r]);return t};function am(t){const e=Object.keys(t);let n=e.length;const r=new Array(n);for(;n--;)r[n]=[e[n],t[e[n]]];return r}const SF=function(t){return function(...e){try{return t.apply(this,e)}catch(n){he.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),he.critical(n)}}},Kx=function(t){const e={};return Pt(t,function(n,r){(rt(n)&&n.length>0||Cn(n))&&(e[r]=n)}),e};function $T(t){const e=$({},t);for(const n of["name","message","stack","cause","errors"])try{n in t&&(e[n]=t[n])}catch{}return e}const kF=["herokuapp.com","vercel.app","netlify.app"];function EF(t){const e=t==null?void 0:t.hostname;if(!rt(e))return!1;const n=e.split(".").slice(-2).join(".");for(const r of kF)if(n===r)return!1;return!0}function _t(t,e,n,r){const{capture:s=!1,passive:i=!0}=r??{};t==null||t.addEventListener(e,n,{capture:s,passive:i})}function k2(t){return t.name==="ph_toolbar_internal"}const Kf=t=>{if(ke){try{const e=t+"=",n=ke.cookie.split(";").filter(r=>r.length);for(let r=0;n.length>r;r++){let s=n[r];for(;s.charAt(0)==" ";)s=s.substring(1,s.length);if(s.indexOf(e)===0)return decodeURIComponent(s.substring(e.length,s.length))}}catch{}return null}};var CF=class E2{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,r,s){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(r)||!Number.isInteger(s)||0>e||0>n||0>r||0>s||e>0xffffffffffff||n>4095||r>1073741823||s>4294967295)throw new RangeError("invalid field value");const i=new Uint8Array(16);return i[0]=e/Math.pow(2,40),i[1]=e/Math.pow(2,32),i[2]=e/Math.pow(2,24),i[3]=e/Math.pow(2,16),i[4]=e/256,i[5]=e,i[6]=112|n>>>8,i[7]=n,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=s>>>24,i[13]=s>>>16,i[14]=s>>>8,i[15]=s,new E2(i)}toString(){let e="";for(let n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new E2(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let n=0;16>n;n++){const r=this.bytes[n]-e.bytes[n];if(r!==0)return Math.sign(r)}return 0}},PF=class{generate(){const t=this.generateOrAbort();if(!ae(t))return t;{this.Ct=0;const e=this.generateOrAbort();if(ae(e))throw new Error("Could not generate UUID after timestamp reset");return e}}generateOrAbort(){const t=(()=>{const e=Date.now();return Cn(e)&&isFinite(e)?Math.min(Math.max(Math.floor(e),0),0xffffffffffff):0})();if(t>this.Ct)this.Ct=t,this.It();else{if(this.Ct>=t+1e4)return;this.Mt++,this.Mt>4398046511103&&(this.Ct++,this.It())}return CF.fromFieldsV7(this.Ct,Math.trunc(this.Mt/Math.pow(2,30)),this.Mt&Math.pow(2,30)-1,this.Tt.nextUint32())}It(){this.Mt=1024*this.Tt.nextUint32()+(1023&this.Tt.nextUint32())}constructor(){this.Ct=0,this.Mt=0,this.Tt=new AF}};const n8=t=>{if("u">typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(let e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};let r8;var AF=class{nextUint32(){var t;return this.Rt.length>this.$t||(((t=r8)!==null&&t!==void 0?t:r8="u">typeof window&&!ae(window.crypto)&&crypto.getRandomValues?e=>{try{return crypto.getRandomValues(e)}catch{return n8(e)}}:n8)(this.Rt),this.$t=0),this.Rt[this.$t++]}constructor(){this.Rt=new Uint32Array(8),this.$t=1/0}};let s8;const xi=()=>TF().toString(),TF=()=>(s8||(s8=new PF)).generate();let _f="";const RF=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;let cu=null;const Qt={Et(){if(!dn(cu))return cu;if(cu=!1,ke)try{const t=`__ph_cookie_support_${xi()}`;Qt.At(t,"xyz"),cu=Kf(t)==='"xyz"',Qt.Pt(t)}catch{cu=!1}return cu},Ft(t){he.error("cookieStore error: "+t)},Ot:Kf,Lt(t){let e;try{e=JSON.parse(Qt.Ot(t))||{}}catch{}return e},At(t,e,n,r,s){if(!ke)return!1;try{let i="",o="";const l=(function(d,f){if(f){let h=(function(m,v=ke){if(_f)return _f;if(!v||["localhost","127.0.0.1"].includes(m))return"";const w=m.split(".");let _=Math.min(w.length,8);const x="dmn_chk_"+xi();for(;!_f&&_--;){const b=w.slice(_).join("."),k=x+"=1;domain=."+b+";path=/";v.cookie=k+";max-age=3",v.cookie.includes(x)&&(v.cookie=k+";max-age=0",_f=b)}return _f})(d);if(!h){const m=(v=>{const w=v.match(RF);return w?w[0]:""})(d);m!==h&&he.info("Warning: cookie subdomain discovery mismatch",m,h),h=m}return h?"; domain=."+h:""}return""})(ke.location.hostname,r);if(n){const d=new Date;d.setTime(d.getTime()+864e5*n),i="; expires="+d.toUTCString()}s&&(o="; secure");const u=t+"="+encodeURIComponent(JSON.stringify(e))+i+"; SameSite=Lax; path=/"+l+o;return u.length>3686.4&&he.warn("cookieStore warning: large cookie, len="+u.length),ke.cookie=u,!0}catch{return!1}},Pt(t,e){if(ke!=null&&ke.cookie&&(!e||!dn(Kf(t))))try{Qt.At(t,"",-1,e)}catch{return}}};let ky=null;const gt={Et(){if(!dn(ky))return ky;let t=!0;if(ae(oe))t=!1;else try{const e="__mplssupport__";gt.At(e,"xyz"),gt.Ot(e)!=='"xyz"'&&(t=!1),gt.Pt(e)}catch{t=!1}return t||he.error("localStorage unsupported; falling back to cookie store"),ky=t,t},Ft(t){he.error("localStorage error: "+t)},Ot(t){try{return oe==null?void 0:oe.localStorage.getItem(t)}catch(e){gt.Ft(e)}return null},Lt(t){try{return JSON.parse(gt.Ot(t))||{}}catch{}return null},At(t,e){try{return oe==null||oe.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){gt.Ft(n)}return!1},Pt(t){try{oe==null||oe.localStorage.removeItem(t)}catch(e){gt.Ft(e)}}},Ey=[$a,jo,wi,lc,Fa,cc,Ba,mh,$o],Zl=[zx,qs,Cu,bT,Wx,Pu,ju,Cr],Yf=t=>t+"_cpm",IF=["__proto__","constructor","prototype"],Cy=t=>{if(!nt(t))return{};const e={};return Object.keys(t).forEach(n=>{IF.indexOf(n)===-1&&(e[n]=t[n])}),e},Py=(t,e=[])=>{const n={};return[...Zl,...e].forEach(r=>{const s=t[r];ae(s)||dn(s)||s===""||(n[r]=s)}),n},FT=t=>{let e=5381,n=2166136261;for(let r=0;t.length>r;r++){const s=t.charCodeAt(r);e=33*e^s,n=Math.imul(n^s,16777619)}return t.length.toString(36)+"."+(e>>>0).toString(36)+"."+(n>>>0).toString(36)},i8=(t,e)=>({p:e,f:FT(JSON.stringify(t))}),o8=(t,e)=>{if(!e)return{properties:[],isValid:!1};try{const n=Qt.Lt(Yf(t)),r=(n==null?void 0:n.f)===FT(e)&&ze(n.p);return{properties:r?n.p:[],isValid:r}}catch{return{properties:[],isValid:!1}}},Ay=(t,e)=>e+"|"+(Qt.Ot(Yf(t))||""),uu={},C2={Et:()=>!0,Ft(t){he.error("memoryStorage error: "+t)},Ot:t=>t in uu?uu[t]:null,Lt:t=>t in uu?uu[t]:null,At:(t,e)=>(uu[t]=e,!0),Pt(t){delete uu[t]}};let Il=null;const Bt={Et(){if(!dn(Il))return Il;if(Il=!0,ae(oe))Il=!1;else try{const t="__support__";Bt.At(t,"xyz"),Bt.Ot(t)!=='"xyz"'&&(Il=!1),Bt.Pt(t)}catch{Il=!1}return Il},Ft(t){he.error("sessionStorage error: ",t)},Ot(t){try{return oe==null?void 0:oe.sessionStorage.getItem(t)}catch(e){Bt.Ft(e)}return null},Lt(t){try{return JSON.parse(Bt.Ot(t))||null}catch{}return null},At(t,e){try{return oe==null||oe.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){Bt.Ft(n)}return!1},Pt(t){try{oe==null||oe.sessionStorage.removeItem(t)}catch(e){Bt.Ft(e)}}};var MF=class{constructor(t){this._instance=t}get Ar(){return this._instance.config}get consent(){return this.Sl()?0:this.xl}isOptedOut(){return this.Ar.cookieless_mode==="always"||this.isRejected()||this.consent===-1&&this.Ar.cookieless_mode==="on_reject"}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ar.opt_out_capturing_by_default}optInOut(t){this.$l.At(this.Cl,t?1:0,this.Ar.cookie_expiration,this.Ar.cross_subdomain_cookie,this.Ar.secure_cookie)}reset(){this.$l.Pt(this.Cl,this.Ar.cross_subdomain_cookie)}get Cl(){const{token:t,opt_out_capturing_cookie_prefix:e,consent_persistence_name:n}=this._instance.config;return n||(e?e+t:"__ph_opt_in_out_"+t)}get xl(){const t=this.$l.Ot(this.Cl);return fy(t)?1:je(A7,t)?0:-1}get $l(){const t=this.Ar.opt_out_capturing_persistence_type,e=t==="localStorage"?gt:Qt,n=e.Et()?e:C2;if(!this.Tl||this.Tl!==n){this.Tl=n;const r=t==="localStorage"?Qt:gt;r.Ot(this.Cl)&&(this.Tl.Ot(this.Cl)||this.optInOut(fy(r.Ot(this.Cl))),r.Pt(this.Cl,this.Ar.cross_subdomain_cookie))}return this.Tl}Sl(){return!!this.Ar.respect_dnt&&[gr==null?void 0:gr.doNotTrack,gr==null?void 0:gr.msDoNotTrack,qe.doNotTrack,gr==null?void 0:gr.globalPrivacyControl].some(t=>fy(t))}};function VT(t,e){var n;const r=t==null||(n=t.config)===null||n===void 0?void 0:n.get_current_url;if(!gn(r))return e;try{const s=r(e);return rt(s)&&s?s:e}catch(s){return he.error("Error in get_current_url, falling back to window.location.href",s),e}}function a8(t){var e;return t instanceof Element&&(t.id==="__POSTHOG_TOOLBAR__"||!!(!((e=t.closest)===null||e===void 0)&&e.call(t,".toolbar-global-fade-container")))}function ei(t){return!!t&&t.nodeType===1}function Nn(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function HT(t){return!!t&&t.nodeType===3}function Zm(t){return!!t&&t.nodeType===11&&ei(t.host)}function Yx(t){return t?rd(t).split(/\s+/):[]}function l8(t,e){const n=(function(r){var s;const i=typeof window>"u"?void 0:window,o=i==null||(s=i.location)===null||s===void 0?void 0:s.href;return ae(o)?void 0:VT(r,o)})(e);return!!(n&&t&&t.some(r=>n.match(r)))}function uc(t){let e="";switch(typeof t.className){case"string":e=t.className;break;case"object":e=(t.className&&"baseVal"in t.className?t.className.baseVal:null)||t.getAttribute("class")||"";break;default:e=""}return Yx(e)}function zT(t){return Xe(t)?null:rd(t).split(/(\s+)/).filter(e=>$u(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function gh(t){let e="";return Wa(t)&&!id(t)&&t.childNodes&&t.childNodes.length&&Pt(t.childNodes,function(n){var r;HT(n)&&n.textContent&&(e+=(r=zT(n.textContent))!==null&&r!==void 0?r:"")}),rd(e)}function Xf(t){var e;return ae(t.target)?t.srcElement||null:!((e=t.target)===null||e===void 0)&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}const Xx=["a","button","form","input","select","textarea","label"];function Df(t,e){const n=t.matches||t.matchesSelector||t.msMatchesSelector||t.mozMatchesSelector||t.webkitMatchesSelector||t.oMatchesSelector;try{return!!n&&n.call(t,e)}catch{return!1}}function P2(t,e){if(ae(e))return!0;for(const n of t)if(e.some(r=>Df(n,r)))return!0;return!1}function UT(t){const e=t.parentNode;return!(!e||!ei(e))&&e}const w0=[".ph-no-autocapture","[data-ph-no-autocapture]"],BT=["next","previous","prev",">","<","→","←","›","‹","»","«","▶","◀","❯","❮"],Qx=[...BT,"+","-","−","–"],c8=Qx.length+10,OF=["button","a","input","select","textarea","label"],LF=["button","link","tab","menuitem","option"],u8=(t,e)=>/[a-z0-9]/i.test(e)?je(Qx,e)?new RegExp(`\\b${e}\\b`).test(t):t.includes(e):t===e,NF=t=>je(OF,t.tagName.toLowerCase())||je(LF,(t.getAttribute("role")||"").toLowerCase());function Ty(t){let e="",n="";const r=o=>{ei(o)&&Wa(o)&&!id(o)&&(e+=` ${gh(o)}`,n=n||o.getAttribute("aria-label")||"",Pt(o.childNodes,r))};r(t),e=rd(e.replace(/\s+/g," "));const s=($u(e)?e:"").toLowerCase(),i=t.getAttribute("aria-label")||(s?"":n);return{safeText:s,ariaLabel:rd(i).toLowerCase()}}const d8=[".ph-no-rageclick",".ph-no-capture"],DF=["","text","search","email","password","url","tel","number"];function WT(t,e){if(!(!(typeof window>"u")&&window)||Jx(t))return!1;let n,r,s;var i,o;if(Hr(e)?(n=!!e&&d8,r=void 0,s=!1):(n=(i=e==null?void 0:e.css_selector_ignorelist)!==null&&i!==void 0?i:d8,r=e==null?void 0:e.content_ignorelist,s=(o=e==null?void 0:e.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||s&&(function(u){return!(!u||!ei(u))&&(!!Nn(u,"textarea")||(Nn(u,"input")?je(DF,(u.getAttribute("type")||"").toLowerCase()):(function(d){var f;if(d.isContentEditable)return!0;const h=(f=d.getAttribute)===null||f===void 0?void 0:f.call(d,"contenteditable");return h==="true"||h===""})(u)))})(t))return!1;const{targetElementList:l}=ZT(t,!1);return!(r&&(function(u,{safeText:d,ariaLabel:f}){let h;if(u===!0)h=BT;else{if(!ze(u))return!1;if(u.length>c8)return he.error(`[PostHog] content_ignorelist array cannot exceed ${c8} items. Use css_selector_ignorelist for more complex matching.`),!1;h=u.map(m=>m.toLowerCase())}return h.some(m=>u8(d,m)||u8(f,m))})(r,(function(u,d){for(const h of d)if(NF(h))return Ty(h);for(const h of d){try{var f;if(((f=window)===null||f===void 0?void 0:f.getComputedStyle(h).getPropertyValue("cursor"))!=="pointer")break}catch{break}const m=Ty(h);if(m.safeText||m.ariaLabel)return m}return Ty(u)})(t,l))||P2(l,n))}const Jx=t=>!t||Nn(t,"html")||!ei(t),ZT=(t,e)=>{const n=typeof window>"u"?void 0:window;if(!n||Jx(t))return{parentIsUsefulElement:!1,targetElementList:[]};let r=!1;const s=[t];let i=t;for(;i.parentNode&&!Nn(i,"body");){if(Zm(i.parentNode)){s.push(i.parentNode.host),i=i.parentNode.host;continue}const o=UT(i);if(!o)break;if(e||Xx.indexOf(o.tagName.toLowerCase())>-1)r=!0;else try{const l=n.getComputedStyle(o);l&&l.getPropertyValue("cursor")==="pointer"&&(r=!0)}catch{}s.push(o),i=o}return{parentIsUsefulElement:r,targetElementList:s}};function Wa(t){const e=new Set;let n=0;for(let i=t;i.parentNode&&!Nn(i,"body");i=i.parentNode){if(n++>=1e3||e.has(i))return!1;e.add(i);const o=uc(i);if(je(o,"ph-sensitive")||je(o,"ph-no-capture"))return!1}if(je(uc(t),"ph-include"))return!0;const r=t.type||"";if(rt(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}const s=t.name||t.id||"";return!rt(s)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(s.replace(/[^a-zA-Z0-9]/g,""))}function id(t){return!!(Nn(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Nn(t,"select")||Nn(t,"textarea")||t.getAttribute("contenteditable")==="true")}const f8=new RegExp("^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$"),h8=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,jF=[16,15,14,13],$F=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),p8=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),m8=/[0-9A-Za-z_]/;function FF(t){let e=0,n=!1;for(let r=t.length-1;r>=0;r--){let s=t.charCodeAt(r)-48;n&&(s*=2,s>9&&(s-=9)),e+=s,n=!n}return e%10==0}function $u(t,e=!0){return!(Xe(t)||rt(t)&&(t=rd(t),(e?f8.test((t||"").replace(/[- ]/g,"")):(function(n){let r;for(h8.lastIndex=0;r=h8.exec(n);){const s=r[2];if(!s)continue;const i=s.replace(/[- ]/g,"");for(let o=0;i.length>o;o++)for(const l of jF){const u=o+l;if(i.length>=u){const d=i.slice(o,u);if(f8.test(d)&&FF(d))return!0}}}return!1})(t))||(e?$F.test(t):(function(n){let r;for(p8.lastIndex=0;r=p8.exec(n);){const s=r[1],i=r[3];if(!(s&&i&&m8.test(s)&&m8.test(i)))return!0}return!1})(t))))}function g8(t){let e=gh(t);return e=`${e} ${qT(t)}`.trim(),$u(e)?e:""}function qT(t){let e="";return t&&t.childNodes&&t.childNodes.length&&Pt(t.childNodes,function(n){var r;if(n&&((r=n.tagName)===null||r===void 0?void 0:r.toLowerCase())==="span")try{const s=gh(n);e=`${e} ${s}`.trim(),n.childNodes&&n.childNodes.length&&(e=`${e} ${qT(n)}`.trim())}catch(s){he.error("[AutoCapture]",s)}}),e}function v8(t){return t.replace(/"|\\"/g,'\\"')}function VF(t){const e=t.attr__class;if(e)return ze(e)?e:Yx(e)}const x0=an("[Dead Clicks]"),HF=()=>!0,zF=t=>{var e;const n=!!(!((e=t.instance.persistence)===null||e===void 0)&&e.get_property(Ux)),r=t.instance.config.capture_dead_clicks;return Hr(r)?r:!!nt(r)||n};var y8=class{get lazyLoadedDeadClicksAutocapture(){return this.Il}constructor(t,e,n){this.instance=t,this.isEnabled=e,this.onCapture=n,this.startIfEnabledOrStop()}onRemoteConfig(t){if(!t.ok)return;const e=t.config;"captureDeadClicks"in e&&(this.instance.persistence&&this.instance.persistence.register({[Ux]:e.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this.Ml(()=>{this.El()}):this.stop()}Ml(t){var e,n,r;!((e=qe.__PosthogExtensions__)===null||e===void 0)&&e.initDeadClicksAutocapture?t():(n=qe.__PosthogExtensions__)===null||n===void 0||(r=n.loadExternalDependency)===null||r===void 0||r.call(n,this.instance,"dead-clicks-autocapture",s=>{s?x0.error("failed to load script",s):t()})}El(){var t;if(ke){if(!this.Il&&(!((t=qe.__PosthogExtensions__)===null||t===void 0)&&t.initDeadClicksAutocapture)){const e=nt(this.instance.config.capture_dead_clicks)?$({},this.instance.config.capture_dead_clicks):{};e.__onCapture=this.onCapture,this.onCapture&&(e.capture_dead_swipes=!1),this.Il=qe.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,e),this.Il.start(ke),x0.info("starting...")}}else x0.error("`document` not found. Cannot start.")}stop(){this.Il&&(this.Il.stop(),this.Il=void 0,x0.info("stopping..."))}};const wf=an("[SegmentIntegration]");function _8(t,e,n=!0){const r=t.config.segment;if(!r)return e();const{analytics:s,filterProperties:i}=(l=>gn(l.register))(o=r)?{analytics:o}:o;var o;(function(l,u,d,f){const h=v=>{const w=()=>v.anonymousId()||xi();l.config.get_device_id=w,f&&v.id()&&(l.register({distinct_id:v.id(),$device_id:w()}),l.persistence.set_property(Cr,om)),d(f?void 0:v.anonymousId()||void 0)},m=u.user();"then"in m&&gn(m.then)?m.then(h):h(m)})(t,s,l=>{s.register(((u,d,{filterProperties:f}={})=>{typeof Promise<"u"&&Promise.resolve||wf.warn("This browser does not have Promise support, and can not use the segment integration");const h=(m,v)=>{if(!v)return m;const w=!!d&&m.event.anonymousId===d&&!m.event.userId;w||m.event.userId||m.event.anonymousId===u.get_distinct_id()||(wf.info("No userId set, resetting PostHog"),u.reset()),w||(d=void 0),m.event.userId&&m.event.userId!==u.get_distinct_id()&&(wf.info("UserId set, identifying with PostHog"),u.identify(m.event.userId));let _=u.calculateEventProperties(v,m.event.properties);if(!Xe(f)){const x=m.event.properties||{},b={};for(const C of Object.keys(_))Nx.call(x,C)||(b[C]=_[C]);const k=((C,P)=>{const T=ze(C)?C:[C];let M=$({},P);for(const I of T)try{if(M=I(M),Xe(M))return null}catch(R){return wf.error("Error in Segment filterProperties:",R),null}return M})(f,b);if(Xe(k))return m;_=k}return m.event.properties=Object.assign({},_,m.event.properties),m};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded(){return!0},load(){return Promise.resolve()},track(m){return h(m,m.event.event)},page(m){return h(m,Gx)},identify(m){return h(m,jT)},screen(m){return h(m,"$screen")}}})(t,l,{filterProperties:i})).then(()=>{e()},u=>{wf.error("Failed to register the Segment integration",u),e()})},n)}const GT="posthog-js";function KT(t,{organization:e,projectId:n,prefix:r,severityAllowList:s=["error"],sendExceptionsToPostHog:i=!0}={}){return o=>{var l,u,d,f,h;if(s!=="*"&&!s.includes(o.level)||!t.__loaded)return o;o.tags||(o.tags={});const m=t.requestRouter.endpointFor("ui",`/project/${t.config.token}/person/${t.get_distinct_id()}`);o.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(o.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));const v=((l=o.exception)===null||l===void 0?void 0:l.values)||[],w=v.map(b=>$($({},b),{},{stacktrace:b.stacktrace?$($({},b.stacktrace),{},{type:"raw",frames:(b.stacktrace.frames||[]).map(k=>$($({},k),{},{platform:"web:javascript"}))}):void 0})),_={$exception_message:((u=v[0])===null||u===void 0?void 0:u.value)||o.message,$exception_type:(d=v[0])===null||d===void 0?void 0:d.type,$exception_level:o.level,$exception_list:w,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:((f=v[0])===null||f===void 0?void 0:f.value)||o.message,$sentry_exception_type:(h=v[0])===null||h===void 0?void 0:h.type,$sentry_tags:o.tags};var x;return e&&n&&(_.$sentry_url=(r||"https://sentry.io/organizations/")+e+"/issues/?project="+n+"&query="+o.event_id),i&&((x=t.exceptions)===null||x===void 0||x.sendExceptionEvent(_)),o}}var UF=class{constructor(t,e,n,r,s,i){this.name=GT,this.setupOnce=function(o){o(KT(t,{organization:e,projectId:n,prefix:r,severityAllowList:s,sendExceptionsToPostHog:i==null||i}))}}},w8=class{constructor(t){this.Pl=(e,n,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(he.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:e,changeReason:r}),this.Rl=void 0,this._instance.scrollManager.resetContext())},this._instance=t,this.Al()}Al(){var t;this.Fl=(t=this._instance.sessionManager)===null||t===void 0?void 0:t.onSessionId(this.Pl)}destroy(){var t;(t=this.Fl)===null||t===void 0||t.call(this),this.Fl=void 0}doPageView(t,e){var n;const r=this.Ol(t,e);return this.Rl={pathname:(n=oe==null?void 0:oe.location.pathname)!==null&&n!==void 0?n:"",pageViewId:e,timestamp:t},this._instance.scrollManager.resetContext(),r}doPageLeave(t){var e;return this.Ol(t,(e=this.Rl)===null||e===void 0?void 0:e.pageViewId)}doEvent(){var t;return{$pageview_id:(t=this.Rl)===null||t===void 0?void 0:t.pageViewId}}Ol(t,e){const n=this.Rl;if(!n)return{$pageview_id:e};let r={$pageview_id:e,$prev_pageview_id:n.pageViewId};const s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){let{maxScrollHeight:i,lastScrollY:o,maxScrollY:l,maxContentHeight:u,lastContentY:d,maxContentY:f}=s;if(!(ae(i)||ae(o)||ae(l)||ae(u)||ae(d)||ae(f))){i=Math.ceil(i),o=Math.ceil(o),l=Math.ceil(l),u=Math.ceil(u),d=Math.ceil(d),f=Math.ceil(f);const h=i>1?Zi(o/i,0,1,he):1,m=i>1?Zi(l/i,0,1,he):1,v=u>1?Zi(d/u,0,1,he):1,w=u>1?Zi(f/u,0,1,he):1;r=en(r,{$prev_pageview_last_scroll:o,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:m,$prev_pageview_last_content:d,$prev_pageview_last_content_percentage:v,$prev_pageview_max_content:f,$prev_pageview_max_content_percentage:w})}}return n.pathname&&(r.$prev_pageview_pathname=n.pathname),n.timestamp&&(r.$prev_pageview_duration=(t.getTime()-n.timestamp.getTime())/1e3),r}};const xf=["flags","surveys"],BF={[nF]:{exposure:"hidden"},[Bm]:{exposure:"hidden"},[rF]:{exposure:"hidden"},[v2]:{exposure:"hidden"},[ju]:{exposure:"hidden"},[qf]:{exposure:"hidden"},[yT]:{exposure:"event"},[y2]:{exposure:"hidden"},[wT]:{exposure:"hidden"},[_2]:{exposure:"event"},[_T]:{exposure:"hidden"},[w2]:{exposure:"event"},[x2]:{exposure:"event"},[Ux]:{exposure:"event"},[Bx]:{exposure:"hidden"},[xT]:{exposure:"event"},[Gf]:{exposure:"hidden"},[sF]:{exposure:"hidden"},[Cu]:{exposure:"hidden"},[bT]:{exposure:"event"},[iF]:{exposure:"event",shouldSkipFromEventProperties:t=>dn(t)},[uF]:{exposure:"event"},[dF]:{exposure:"event"},[fF]:{exposure:"event"},[hF]:{exposure:"event"},[pF]:{exposure:"hidden"},[wi]:{exposure:"hidden",storageGroup:"flags"},[jo]:{exposure:"hidden",storageGroup:"flags"},[m2]:{exposure:"hidden"},[lc]:{exposure:"hidden",storageGroup:"flags"},[Fa]:{exposure:"hidden",storageGroup:"flags"},[cc]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zf]:{exposure:"hidden",storageGroup:"flags"},[Di]:{exposure:"hidden"},[Wl]:{exposure:"hidden"},[$a]:{exposure:"hidden"},[ja]:{exposure:"hidden"},[Nf]:{exposure:"hidden",storageGroup:"surveys"},[Um]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[g2]:{exposure:"event"},[sm]:{exposure:"hidden"},[im]:{exposure:"hidden"},[b2]:{exposure:"hidden"},[mF]:{exposure:"hidden"},[gF]:{exposure:"hidden"},[vF]:{exposure:"event"},[yF]:{exposure:"event"},[_F]:{exposure:"event"},[wF]:{exposure:"event"},[$o]:{exposure:"hidden"},[Lf]:{exposure:"hidden"},[ST]:{exposure:"event"},[mh]:{exposure:"hidden"},[Ba]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Cr]:{exposure:"hidden"},[S2]:{exposure:"hidden"},[xF]:{exposure:"hidden"},[kT]:{exposure:"hidden"},[ET]:{exposure:"hidden"},[Pu]:{exposure:"hidden"},[Wx]:{exposure:"hidden"},[oF]:{exposure:"event"},[aF]:{exposure:"event"},[lF]:{exposure:"event"},[cF]:{exposure:"event"},[PT]:{exposure:"event"},[AT]:{exposure:"event"},[Zx]:{exposure:"hidden"},[qx]:{exposure:"hidden"},[TT]:{exposure:"hidden"},[RT]:{exposure:"hidden"},[IT]:{exposure:"hidden"},[MT]:{exposure:"hidden"},[OT]:{exposure:"hidden"},[LT]:{exposure:"hidden"},[NT]:{exposure:"hidden"},[bF]:{exposure:"event"}},WF=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],lr=t=>{const e=BF[t];if(e)return e;for(const[n,r]of WF)if(t.indexOf(n)===0)return r};function YT(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}const qo=t=>{const e=typeof document>"u"?void 0:document,n=e==null?void 0:e.createElement("a");return ae(n)?null:(n.href=t,n)},XT=()=>{try{return"u">typeof window&&window.navigator.onLine!==!1}catch{return!1}},QT=(t,e)=>t>=e&&XT(),JT=(t,e,n,r)=>{if(t===0){if(XT()){const s=e+1;return s===n&&r(),s}return e}return 0},Tu=(t,e)=>{try{let n;return JSON.stringify(t,(r,s)=>{var i;return Ed(s)?((i=n)!==null&&i!==void 0||(n=new WeakMap),n.has(s)||n.set(s,$T(s)),n.get(s)):typeof s=="bigint"?s.toString():s},e)}catch{return p5(t)}},od=function(t,e){const n=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&");let r;for(let s=0;n.length>s;s++){const i=n[s].split(/=(.*)/);if(i[0]===e){r=i;break}}if(!ze(r)||2>r.length)return"";{let s=r[1].replace(/\+/g," ");try{s=decodeURIComponent(s)}catch{he.error("Skipping decoding for malformed query param: "+s)}return s}},vh=function(t,e,n){if(!t||!e||!e.length)return t;const r=t.split(/#(.*)/),s=r[1],i=(r[0]||"").split(/\?(.*)/),o=i[1],l=i[0],u=(o||"").split("&"),d=[];for(let h=0;u.length>h;h++){const m=u[h].split("?");let v=0;for(;m.length>v&&!e.includes(m[v].split("=")[0]);)v++;d.push(m.length>v?m.slice(0,v).concat(m[v].split("=")[0]+"="+n).join("?"):u[h])}let f=l;return o!=null&&(f+="?"+d.join("&")),s!=null&&(f+="#"+s),f},qm=function(t,e){const n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},ad=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx"],ZF=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ad],yh="<masked>",qF=["li_fat_id"];function eR(t,e,n){if(!ke)return{};const r=e?[...ad,...n||[]]:[],s=tR(vh(ke.URL,r,yh),t),i=(function(){const o={};return Pt(qF,function(l){const u=Kf(l);o[l]=u||null}),o})();return en(i,s)}function tR(t,e){const n=ZF.concat(e||[]),r={};return Pt(n,function(s){const i=od(t,s);r[s]=i||null}),r}function nR(t){const e=(function(s){return s?s.search("https?://(.*)google.([^/?]*)")===0?"google":s.search("https?://(.*)bing.com")===0?"bing":s.search("https?://(.*)yahoo.com")===0?"yahoo":s.search("https?://(.*)duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",r={};if(!dn(e)){r.$search_engine=e;const s=ke?od(ke.referrer,n):"";s.length&&(r.ph_keyword=s)}return r}function rR(){return navigator.language||navigator.userLanguage}function GF(){const t=rR();return typeof t=="string"?t.split("-")[0]:void 0}const Gm="$direct";function sR(){return(ke==null?void 0:ke.referrer)||Gm}function iR(t,e,n=!1){const r=t?[...ad,...e||[]]:[],s=n?Ya(Ut==null?void 0:Ut.href):Ut==null?void 0:Ut.href,i=s==null?void 0:s.substring(0,1e3);return{r:sR().substring(0,1e3),u:i?vh(i,r,yh):void 0}}function oR(t,e=!1){var n;const{r,u:s}=t,i=e?Ya(s):s,o={$referrer:r,$referring_domain:r==null?void 0:r==Gm?Gm:(n=qo(r))===null||n===void 0?void 0:n.host};if(i){o.$current_url=i;const l=qo(i);o.$host=l==null?void 0:l.host,o.$pathname=l==null?void 0:l.pathname;const u=tR(i);en(o,u)}if(r){const l=nR(r);en(o,l)}return o}function KF(){try{return new Date().getTimezoneOffset()}catch{return}}const YF={flags:Ba,surveys:Um},XF=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],b0=t=>`${t}_cookie_identity_change_pending`,S0=t=>{let e="",n=0;for(const r of t){const s=encodeURIComponent(JSON.stringify(r).slice(1,-1)).length;if(n+s>1e3)break;e+=r,n+=s}return e},Vn="main",To=[wi,jo,lc,Fa,cc,Ba,Zf,$a],Ry=t=>To.indexOf(t)!==-1,aR=[ju,qf],x8=t=>aR.indexOf(t)!==-1,ba=(t,e)=>{try{return JSON.stringify(t)===JSON.stringify(e)}catch{return t===e}},du=t=>{if(!t)return{};const e=JSON.parse(t);return nt(e)?e:{}},b8=(t,e)=>{Pt(t,(n,r)=>{const s=lr(r);s&&s.exposure!=="event"||{}.hasOwnProperty.call(e,r)||delete t[r]})};var Iy=class{constructor(t,e,n=!0,r=!t.cookieless_mode){if(this.Dl={},this.Ll=!1,this.Nl=!1,this.ql=!1,this.jl=!1,this.Bl=!1,this.zl=new Map,this.Hl=!1,this.Ul=!1,this.Wl=!1,this.Vl=new Set,this.Gl=new Set,this.Ar=t,this.Ql=n,this.props={},this.Zl=void 0,this.Jl=(s=>{let i="";return s.token&&(i=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+i+"_posthog"})(t),this.hi=t.disable_persistence||!!e,this.$l=this.Kl(t),this.ql=this.Xl(t),this.load(r),this.Yl(),t.debug&&he.info("Persistence loaded",t.persistence,$({},this.props)),this.update_config(t,t,e),this.save(),oe){const s=()=>this.flush();_t(oe,"beforeunload",s,{capture:!1}),_t(oe,"pagehide",s,{capture:!1}),this.tu=i=>{if(this.Ll&&(!i.storageArea||i.storageArea===(oe==null?void 0:oe.localStorage))&&i.key)if(i.key!==this.Jl){if(this.ql){const o=xf.find(l=>i.key===this.eu(l));o&&this.iu(i.key,o)}}else this.iu(i.key,Vn)},_t(oe,"storage",this.tu)}}markCrossTabFeatureFlagChanges(t){Object.entries(t).forEach(([e,n])=>{const r=this.zl.get(e);if(!Ry(e)||r===!0)return;if(n===!0)return void this.nu(e,!0);const s=new Set(r||[]);n.forEach(i=>s.add(i)),s.size&&this.nu(e,s)})}onCrossTabFeatureFlagChange(t){return this.Gl.add(t),()=>this.Gl.delete(t)}destroy(){this.tu&&oe&&(oe.removeEventListener("storage",this.tu),this.tu=void 0),this.Gl.clear()}iu(t,e,n=!0){if(this.hi)return!1;let r,s;try{if(s=gt.Ot(t),dn(s)){const l=this.su(e);return l.storageValue=null,e!==Vn&&(l.persisted=!1),!1}r=du(s)}catch{return!1}const i=e===Vn?r:gt.Lt(this.Jl);if(i&&this.ru(i))return!1;const o=this.ou(r,e,n);return e===Vn&&this.ql&&!ba(this.au().main,r)||this.lu(r,e,!0,s),o}ru(t){const e=this.props[qs],n=t[qs];return!ae(e)&&!ae(n)&&e!==n}lu(t,e,n,r){const s=this.su(e);s.storageValue=r,e!==Vn&&(s.persisted=n);try{s.fingerprint=this.uu(t,e)}catch{s.fingerprint=void 0}}ou(t,e,n){let r=!1;return To.forEach(s=>{var i;const o=(i=lr(s))===null||i===void 0?void 0:i.storageGroup;if(e===Vn&&this.ql&&o||e!==Vn&&o!==e)return;const l=s in t,u=this.cu(s,l?t[s]:void 0),d=this.zl.has(s)?s in this.props:l;d===s in this.props&&ba(u,this.props[s])||(d?this.hu(s,u,!1):this.du(s,!1),r=!0)}),r&&n&&this.Gl.forEach(s=>s()),r}vu(){if(!this.Ll)return!1;try{this.Wl=!1;const t=gt.Ot(this.Jl),e=this.su(Vn);let n,r=!1,s=!1;if(t!==e.storageValue)if(dn(t))e.storageValue=null;else{if(n=du(t),this.Wl=!this.Ul&&this.ru(n),this.Wl)return!1;s=this.ou(n,Vn,!1),!this.ql||ba(this.au().main,n)?this.lu(n,Vn,!0,t):e.storageValue=t,r=!0}return this.ql&&xf.forEach(i=>{const o=gt.Ot(this.eu(i)),l=this.su(i),u=n||{},d=r&&To.some(h=>{var m;return((m=lr(h))===null||m===void 0?void 0:m.storageGroup)===i&&h in u});if(o===l.storageValue&&!d)return;if(dn(o))return l.storageValue=null,l.persisted=!1,void(d&&(s=this.ou(u,i,!1)||s));const f=du(o);s=this.ou(f,i,!1)||s,this.lu(f,i,!0,o)}),s}catch{return!1}}nu(t,e){this.zl.set(t,e);const n=lr(t);n!=null&&n.volatile||(this.su((this.ql?n==null?void 0:n.storageGroup:void 0)||Vn).fingerprint=void 0,this.fu(t))}pu(){To.forEach(t=>this.zl.set(t,!0))}Yl(){if(this.Ll)try{const t=gt.Ot(this.Jl),e=du(t);this.su(Vn).storageValue=t,To.forEach(n=>{var r;const s=this.ql?(r=lr(n))===null||r===void 0?void 0:r.storageGroup:void 0,i=s?gt.Ot(this.eu(s)):null;if(s){const l=this.su(s);l.storageValue=i,l.persisted=!dn(i)}const o=s&&!dn(i)?du(i):e;n in this.props?this.gu(n,o[n],this.props[n]):n in o&&this.nu(n,!0)})}catch{}}cu(t,e){const n=this.zl.get(t);if(!n)return e;if(n===!0)return this.props[t];if(t==="$active_feature_flags"){const i=new Set(ze(e)?e:[]),o=new Set(ze(this.props[t])?this.props[t]:[]);return n.forEach(l=>o.has(l)?i.add(l):i.delete(l)),Array.from(i)}const r=nt(e)?$({},e):{},s=nt(this.props[t])?this.props[t]:{};return n.forEach(i=>{i in s?r[i]=s[i]:delete r[i]}),r}gu(t,e,n){if(!Ry(t))return;const r=this.zl.get(t);if(r===!0)return;let s=e;if(this.Ll)try{var i;const l=this.ql?(i=lr(t))===null||i===void 0?void 0:i.storageGroup:void 0,u=l?this.eu(l):this.Jl;s=du(gt.Ot(u))[t]}catch{}const o=new Set(r||[]);if(t==="$active_feature_flags"){if(!ae(e)&&!ze(e)||!ae(s)&&!ze(s)||!ze(n))return void this.nu(t,!0);const l=new Set(e||[]),u=new Set(s||[]),d=new Set(n);new Set([...l,...d]).forEach(f=>{l.has(f)!==d.has(f)&&o.add(f)}),o.forEach(f=>{u.has(f)===d.has(f)&&o.delete(f)})}else{if(!nt(n))return void(ba(s,n)?this.zl.delete(t):this.nu(t,!0));{if(!ae(e)&&!nt(e)||ae(e)&&ts(n)&&ae(s))return void this.nu(t,!0);const l=nt(e)?e:{},u=nt(s)?s:{};new Set([...Object.keys(l),...Object.keys(n)]).forEach(d=>{d in l==d in n&&ba(l[d],n[d])||o.add(d)}),o.forEach(d=>{d in u==d in n&&ba(u[d],n[d])&&o.delete(d)})}}o.size?this.nu(t,o):this.zl.delete(t)}mu(){var t;const e=(t=this.Ar)===null||t===void 0?void 0:t.persistence_save_debounce_ms;return Cn(e)&&e>0?e:0}yu(t){if(this.Ar.cookieWinsOnConflict&&this.Ar.persistence.toLowerCase()==="localstorage+cookie")if(t)try{const e=Py(t,this.Ar.cookie_persisted_properties||[]),n=i8(e,this.Ar.cookie_persisted_properties||[]),r=JSON.stringify(e)+"|"+JSON.stringify(n),s=Qt.Ot(this.Jl)||void 0;s&&Ay(this.Jl,s)===r&&(this.bu=r,this._u=s)}catch{}else try{const e=Qt.Ot(this.Jl)||void 0;this.bu=e?Ay(this.Jl,e):void 0,this._u=e}catch{}}syncCookieProperties(){return this.wu(this.Ar)}wu(t,e=!1){if(this.hi&&!e||this.Bl||!t.cookieWinsOnConflict||t.persistence.toLowerCase()!=="localstorage+cookie")return!1;let n;try{n=Qt.Ot(this.Jl)||void 0}catch{}if(!n||n===this._u)return!1;const r=Ay(this.Jl,n);let s;try{s=Cy(JSON.parse(n))}catch{return!1}if((Qt.Ot(this.Jl)||void 0)!==n)return!1;this.bu=r,this._u=n;const i=o8(this.Jl,n),o=[...Zl,...i.properties],l={};if(Object.keys(s).forEach(_=>{const x=s[_];(ae(x)||dn(x)||x===""||_==="$user_state"&&x!=="anonymous"&&x!=="identified")&&(l[_]=!0,delete s[_])}),ts(s))return!1;const u="distinct_id"in s||s.$user_state==="anonymous"||s.$user_state==="identified",d=this.props,f=d[qs],h=d[Cr],m=en({},d);[...Zl,...t.cookie_persisted_properties||[]].forEach(_=>{if(o.indexOf(_)!==-1&&!(_ in s)&&!l[_]&&(u||_!=="distinct_id"&&_!=="$user_state")){const x=m[_];(i.isValid||Zl.indexOf(_)===-1||x!==!1&&x!==0)&&delete m[_]}}),this.props=en(m,s),To.forEach(_=>{const x=_ in this.props;_ in d===x&&ba(d[_],this.props[_])||(x?this.gu(_,d[_],this.props[_]):this.nu(_,!0))}),!u||"$user_state"in s||"$user_state"in this.props||this.hu(Cr,Fo);const v=this.props[qs],w=this.props[Cr];return!u||v===f&&w===h||(this.Ul=!0,this.jl=!0,Bt.At(b0(this.Jl),!0),this.du($a),this.du(jo),this.du(wi),this.du(lc),this.du(Fa),this.du(cc),this.du(Ba),this.du(mh),this.du($o),w!=="anonymous"||h!=="identified"&&s.$user_state!=="anonymous"&&(ae(f)||v===f)||(b8(this.props,s),this.du(ja)),w==="identified"?this.props.$user_id=v:delete this.props.$user_id,this.du(Bm)),!0}consumeCookieIdentityChange(){const t=b0(this.Jl),e=this.jl||!!Bt.Ot(t);return this.jl=!1,e&&Bt.Pt(t),e}ku(t=!1){return!(this.Bl||this.hi&&!t||!this.Ar.cookieWinsOnConflict||this.Ar.persistence.toLowerCase()!=="localstorage+cookie"||(this.Bl=!0,0))}Su(){this.Bl&&(ae(this.xu)||(clearTimeout(this.xu),this.xu=void 0),delete this.Dl[Vn],this.$u(!0))}Cu(t=!0){if(this.Bl)try{t?this.Su():ae(this.xu)||(clearTimeout(this.xu),this.xu=void 0)}finally{this.Bl=!1}}isDisabled(){return!!this.hi}Kl(t){XF.indexOf(t.persistence.toLowerCase())===-1&&(he.critical("Unknown persistence type "+t.persistence+"; falling back to localStorage+cookie"),t.persistence="localStorage+cookie");const e=((o=[],l=!1,u=()=>!1)=>{const d=[...Zl,...o];return $($({},gt),{},{Tu(f){return[Qt.Ot(f),Qt.Ot(Yf(f)),gt.Ot(f)].join("\0")},Lt(f){try{let m,v={};try{m=Qt.Ot(f)||void 0,v=m?Cy(JSON.parse(m)):{}}catch{}const w=JSON.parse(gt.Ot(f)||"{}");let _;if(l){const x=o8(f,m),b=[...Zl,...x.properties],k={};Object.keys(v).forEach(P=>{const T=v[P];dn(T)||T===""||P==="$user_state"&&T!=="anonymous"&&T!=="identified"||(k[P]=T)});const C="distinct_id"in k||k.$user_state==="anonymous"||k.$user_state==="identified";if(Object.keys(k).length>0){var h;const P=w[qs],T=(h=w.$user_state)!==null&&h!==void 0?h:Fo;d.forEach(M=>{if(b.indexOf(M)!==-1&&!(M in v)&&(C||M!=="distinct_id"&&M!=="$user_state")){const I=w[M];(x.isValid||Zl.indexOf(M)===-1||I!==!1&&I!==0)&&delete w[M]}}),!C||"$user_state"in v||"$user_state"in w||(w[Cr]=Fo),!C||("distinct_id"in k?k[qs]:w[qs])===P&&("$user_state"in k?k[Cr]:w[Cr])===T||(Ey.forEach(M=>delete w[M]),k.$user_state==="identified"&&"distinct_id"in k?w.$user_id=k[qs]:delete w.$user_id,k.$user_state!=="identified"&&(delete w[ST],delete w[ja]),delete w.__alias)}_=en(w,k)}else _=en(v,w);return u()||gt.At(f,_),_}catch{}return null},At(f,h,m,v,w,_){const x=gt.At(f,h,void 0,void 0,_);try{const b=Py(h,o);if(Object.keys(b).length){if(l){const k=Yf(f),C=i8(b,o);if(Qt.At(k,C,m,v,w,_),Qt.Ot(k)!==JSON.stringify(C)){Qt.Pt(k,v);const P=Py(h);return Qt.At(f,P,m,v,w,_),x}}Qt.At(f,b,m,v,w,_)}}catch(b){gt.Ft(b)}return x},Pt(f,h){try{oe==null||oe.localStorage.removeItem(f),Qt.Pt(f,h),Qt.Pt(Yf(f),h)}catch(m){gt.Ft(m)}}})})(t.cookie_persisted_properties||[],t.cookieWinsOnConflict,()=>!!this.hi);let n,r=!1,s=!1;const i=t.persistence.toLowerCase();return i==="localstorage"&>.Et()?(n=gt,s=!0):i==="localstorage+cookie"&&e.Et()?(n=e,s=!0,r=!0):i==="sessionstorage"&&Bt.Et()?n=Bt:i==="memory"?n=C2:i==="cookie"&&Qt.Et()?(n=Qt,r=!0):e.Et()?(n=e,s=!0,r=!0):Qt.Et()?(n=Qt,r=!0):n=C2,this.Ll=s,this.Nl=r,n}eu(t){return`${this.Jl}__${t}`}Xl(t){return this.Ll&&!!t.split_storage}properties(){const t={};return Pt(this.props,(e,n)=>{const r=lr(n);if(!r||r.exposure==="event"){var s;if(!(r==null||(s=r.shouldSkipFromEventProperties)===null||s===void 0)&&s.call(r,e))return;t[n]=e}}),t}load(t=!1){if(this.hi&&!t)return;const e=this.Ar.cookieWinsOnConflict&&this.Ar.persistence.toLowerCase()==="localstorage+cookie",n=e?gt.Lt(this.Jl):null;let r={};if(e)try{r=Cy(Qt.Lt(this.Jl)),Pt(r,(l,u)=>{(ae(l)||dn(l)||l==="")&&delete r[u]})}catch{}const s=this.$l.Lt(this.Jl);if(s&&(this.props=en({},s)),this.ql&&this.Iu(),e&&s){var i,o;const l=n==null?void 0:n[qs],u=(i=n==null?void 0:n.$user_state)!==null&&i!==void 0?i:Fo,d=s[qs],f=(o=s.$user_state)!==null&&o!==void 0?o:Fo;if(d!==l||f!==u){this.jl=!0,this.hi||Bt.At(b0(this.Jl),!0);const h=en({},this.props);Ey.forEach(v=>delete h[v]),f!=="anonymous"||u!=="identified"&&r.$user_state!=="anonymous"&&(ae(l)||d===l)||(b8(h,r),delete h[ja]),this.props=h;const m=new Set;Ey.forEach(v=>{var w;const _=(w=lr(v))===null||w===void 0?void 0:w.storageGroup;_&&m.add(_)}),m.forEach(v=>{if(this.hi)return;const w={};Pt(this.props,(_,x)=>{var b;((b=lr(x))===null||b===void 0?void 0:b.storageGroup)===v&&(w[x]=_)}),ts(w)?(gt.Pt(this.eu(v)),this.Dl[v]={}):gt.At(this.eu(v),w)&&(this.Dl[v]={persisted:!0,fingerprint:this.uu(w,v)})})}}Bt.Ot(b0(this.Jl))&&(this.jl=!0)}Iu(){for(const t of xf){const e=gt.Lt(this.eu(t));if(e&&!ts(e)){const n=this.su(t);n.persisted=!0,this.Mu(t)||(n.fingerprint=this.uu(e,t)),this.Eu(t,e)||en(this.props,e)}}}Mu(t){return Object.keys(this.props).some(e=>{var n;return((n=lr(e))===null||n===void 0?void 0:n.storageGroup)===t})}Eu(t,e){const n=YF[t];if(!n)return!1;const r=e[n],s=this.props[n];return Cn(r)&&Cn(s)&&s>r}refreshKey(t){this.Pu([t])}Pu(t){if(this.hi)return;let e,n=!1;const r=()=>(n||(e=this.$l.Lt(this.Jl),n=!0),e);t.forEach(s=>{var i;if(this.Vl.has(s))return;const o=this.ql?(i=lr(s))===null||i===void 0?void 0:i.storageGroup:void 0,l=o?gt.Lt(this.eu(o)):r();if(l&&s in l)this.hu(s,l[s],!1);else{if(o){const u=r();if(u&&s in u)return void this.hu(s,u[s],!1)}this.du(s,!1)}})}refreshMetaIdentifiers(){if(this.hi)return;const t=this.Ru();(ae(t)||t!==this.Au)&&(this.Pu(aR),this.Fu(t))}Fu(t=this.Ru()){this.Au=this.Vl.size===0?t:void 0}Ru(){const t=this.$l.Tu?this.$l.Tu(this.Jl):this.$l.Ot(this.Jl);return rt(t)?t:void 0}save(){if(this.hi)return;const t=this.mu();t>0?ae(this.xu)&&(this.xu=setTimeout(()=>{this.xu=void 0,this.$u()},t)):this.$u()}flush(){ae(this.xu)||(clearTimeout(this.xu),this.xu=void 0,this.$u())}$u(t=!1){if(this.hi||this.Bl&&!t)return;t||(this.syncCookieProperties(),this.Ar.cookieWinsOnConflict&&this.Ar.persistence.toLowerCase()==="localstorage+cookie"||this.refreshMetaIdentifiers());const e=!t&&!this.Hl;e||(this.Wl=!1);const n=!!e&&this.vu();if(this.Wl)return void(this.Ar.debug&&he.warn("skipping persistence write because storage belongs to a different distinct ID"));if(this.ql)return this.Ou(),void(n&&this.Gl.forEach(s=>s()));const r=this.Du(this.$l,this.Jl,this.props,Vn);r==="written"&&this.yu(this.props),r!=="failed"&&(this.zl.clear(),this.Ul=!1,this.Vl.clear()),r==="written"&&this.Fu(),n&&this.Gl.forEach(s=>s())}Ou(){const{main:t,groups:e}=this.au(),n=this.Du(this.$l,this.Jl,t,Vn);n==="written"&&this.yu(t),n!=="failed"&&(this.Ul=!1,this.Vl.clear(),To.forEach(s=>{var i;!((i=lr(s))===null||i===void 0)&&i.storageGroup||this.zl.delete(s)})),n==="written"&&this.Fu();for(const s of xf){var r;const i=e[s];if(ts(i)&&!(!((r=this.Dl[s])===null||r===void 0)&&r.persisted)){To.forEach(l=>{var u;((u=lr(l))===null||u===void 0?void 0:u.storageGroup)===s&&this.zl.delete(l)});continue}const o=this.Du(gt,this.eu(s),i,s);o!=="failed"&&To.forEach(l=>{const u=lr(l);(u==null?void 0:u.storageGroup)!==s||o!=="written"&&u.volatile||this.zl.delete(l)})}}au(){const t={},e={flags:{},surveys:{}};return Pt(this.props,(n,r)=>{var s;const i=(s=lr(r))===null||s===void 0?void 0:s.storageGroup;i?e[i][r]=n:t[r]=n}),{main:t,groups:e}}uu(t,e){if(e===Vn)return JSON.stringify(t)+"|"+this.Lu+"|"+this.Nu+"|"+this.qu;const n={};return Pt(t,(r,s)=>{var i;n[s]=!((i=lr(s))===null||i===void 0)&&i.volatile?"__volatile__":r}),JSON.stringify(n)}Du(t,e,n,r){const s=this.su(r);if(r!==Vn&&!s.dirty&&!ae(s.fingerprint))return"skipped";let i;try{if(i=this.uu(n,r),i===s.fingerprint)return s.dirty=!1,"skipped"}catch{i=void 0}return t.At(e,n,this.Lu,this.Nu,this.qu,this.Ar.debug)?(s.dirty=!1,r!==Vn&&(s.persisted=!0),ae(i)||(s.fingerprint=i),this.Ll&&(s.storageValue=gt.Ot(e)),"written"):(this.Ar.debug&&he.warn(`failed to persist storage entry "${e}"; will retry on next save`),"failed")}remove({keepGroupEntries:t=!1}={}){if(this.pu(),ae(this.xu)||(clearTimeout(this.xu),this.xu=void 0),this.$l.Pt(this.Jl,!1),this.$l.Pt(this.Jl,!0),!t&&this.Ql)for(const e of xf)gt.Pt(this.eu(e));t?delete this.Dl[Vn]:this.Dl={},this.bu=void 0,this._u=void 0}clear(){this.remove(),this.props={}}register_once(t,e,n){if(nt(t)){this.syncCookieProperties(),ae(e)&&(e="None"),this.Lu=ae(n)?this.ju:n;let r=!1;if(Pt(t,(s,i)=>{this.props.hasOwnProperty(i)&&this.props[i]!==e||(this.hu(i,s),r=!0)}),r)return this.save(),!0}return!1}register(t,e){if(nt(t)){this.syncCookieProperties(),this.Lu=ae(e)?this.ju:e;let n=!1;if(Pt(t,(r,s)=>{t.hasOwnProperty(s)&&(this.props[s]!==r||nt(r)||ze(r))&&(this.hu(s,r),n=!0)}),n)return this.save(),!0}return!1}unregister(t){this.syncCookieProperties();const e=typeof t=="string"?[t]:t;let n=!1;for(const r of e)r in this.props&&(this.du(r),n=!0);n&&this.save()}update_campaign_params(){const t=ke==null?void 0:ke.URL;if(t===this.Zl)return;const e=eR(this.Ar.custom_campaign_params,this.Ar.mask_personal_data_properties,this.Ar.custom_personal_data_properties),n=!ts(Kx(e));return n&&this.register(e),this.Zl=t,n?e:void 0}update_search_keyword(){this.register((function(){const t=ke==null?void 0:ke.referrer;return t?nR(t):{}})())}update_referrer_info(){var t;this.register_once({$referrer:sR(),$referring_domain:(ke==null?void 0:ke.referrer)&&((t=qo(ke.referrer))===null||t===void 0?void 0:t.host)||Gm},void 0)}set_initial_person_info(){if(this.props.$initial_campaign_params||this.props.$initial_referrer_info)return;const t=iR(this.Ar.mask_personal_data_properties,this.Ar.custom_personal_data_properties,this.Ar.disable_capture_url_hashes);this.register_once({[Pu]:this.Nl?{r:S0(t.r),u:t.u?S0(t.u):void 0}:t},void 0)}get_initial_props(){const t={};Pt([ET,kT],n=>{const r=this.props[n];r&&Pt(r,function(s,i){t["$initial_"+i2(i)]=s})});const e=this.props[Pu];if(e){const n=(function(r,s=!1){const i=oR(r,s),o={};return Pt(i,function(l,u){o[`$initial_${i2(u)}`]=l}),o})(e,this.Ar.disable_capture_url_hashes);en(t,n)}return t}safe_merge(t){return Pt(this.props,function(e,n){n in t||(t[n]=e)}),t}update_config(t,e,n){const r=t.persistence!==e.persistence,s=!((v,w)=>{if(v.length!==w.length)return!1;const _=[...v].sort(),x=[...w].sort();return _.every((b,k)=>b===x[k])})(t.cookie_persisted_properties||[],e.cookie_persisted_properties||[]),i=r||s,o=t.cookieWinsOnConflict!==e.cookieWinsOnConflict,l=t.disable_persistence||!!n,u=!!this.hi&&!l;l||this.wu(e,u),this.Ar=t,!l&&(r||s||o)&&(this.bu=void 0,this._u=void 0,this.wu($($({},t),{},{cookie_persisted_properties:e.cookie_persisted_properties}),u));const d=i||o?this.Kl(t):this.$l;this.Bu();const f=this.Xl(t),h=i||f!==this.ql,m=!l&&(h||t.cross_subdomain_cookie!==this.Nu||t.secure_cookie!==this.qu)&&this.ku(u);this.Hl=h;try{if(this.ju=this.Lu=t.cookie_expiration,this.set_disabled(l),this.set_cross_subdomain(t.cross_subdomain_cookie),this.set_secure(t.secure_cookie),h){const v=this.props;this.clear(),this.$l=d,this.ql=f,this.props=v,this.save()}else o&&(this.$l=d,l||(delete this.Dl[Vn],this.$u()))}finally{this.Hl=!1,m&&this.Cu()}}Bu(){const t=this.props[Pu];if(!this.Nl||!nt(t)||typeof t.r!="string")return;const e=S0(t.r),n=typeof t.u=="string"?S0(t.u):t.u;e===t.r&&n===t.u||this.hu(Pu,$($({},t),{},{r:e,u:n}))}set_disabled(t){this.hi=t,this.hi?this.remove():this.save()}set_cross_subdomain(t){t!==this.Nu&&(this.Nu=t,this.remove({keepGroupEntries:!0}),this.save())}set_secure(t){t!==this.qu&&(this.qu=t,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(t,e){const n=this.props.__timers||{};n[t]=e,this.hu(v2,n),this.save()}remove_event_timer(t){const e=this.props.__timers||{},n=e[t];return ae(n)||(delete e[t],this.hu(v2,e),this.save()),n}get_property(t){return this.props[t]}set_property(t,e){this.hu(t,e),this.save()}hu(t,e,n=!0){var r;const s=this.props[t];this.props[t]=e,n&&(t!=="distinct_id"&&t!=="$user_state"||s===e||(this.Ul=!0),x8(t)&&!ba(s,e)&&this.Vl.add(t),this.gu(t,s,e),!((r=lr(t))===null||r===void 0)&&r.volatile||this.fu(t))}du(t,e=!0){delete this.props[t],e&&(Ry(t)&&this.nu(t,!0),x8(t)&&this.Vl.add(t),this.fu(t))}fu(t){var e;const n=(e=lr(t))===null||e===void 0?void 0:e.storageGroup;n&&(this.su(n).dirty=!0)}su(t){return this.Dl[t]||(this.Dl[t]={})}};const Ss={GZipJS:"gzip-js",Base64:"base64"},bf={Activation:"events",Cancellation:"cancelEvents"},My={Popover:"popover",API:"api",Widget:"widget"},bs={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Oy={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},A2={Popover:"popover",Inline:"inline"};function k0(t){let e=!0;return{dispose(){if(e){e=!1;const n=t();n&&gn(n.then)&&n.then(void 0,()=>{})}}}}const QF={SHOWN:"product tour shown"},S8={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},k8=an("[RateLimiter]");var JF=class{constructor(t){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=e=>{const n=e.text;if(n&&n.length)try{(JSON.parse(n).quota_limited||[]).forEach(r=>{k8.info(`${r||"events"} is quota limited.`),this.serverLimits[r]=new Date().getTime()+6e4})}catch(r){return void k8.warn(`could not rate limit - continuing. Error: "${r==null?void 0:r.message}"`,{text:n})}},this.instance=t,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var t;return((t=this.instance.config.rate_limiting)===null||t===void 0?void 0:t.events_per_second)||10}get captureEventsBurstLimit(){var t;return Math.max(((t=this.instance.config.rate_limiting)===null||t===void 0?void 0:t.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(t=!1){var e,n,r;const{captureEventsBurstLimit:s,captureEventsPerSecond:i}=this,o=new Date().getTime(),l=(e=(n=this.instance.persistence)===null||n===void 0?void 0:n.get_property("$capture_rate_limit"))!==null&&e!==void 0?e:{tokens:s,last:o};l.tokens+=Math.max(0,o-l.last)/1e3*i,l.last=Math.max(l.last,o),l.tokens>s&&(l.tokens=s);const u=1>l.tokens;if(u||t||(l.tokens=Math.max(0,l.tokens-1)),u&&!t){const d=(Cn(l.dropped)?l.dropped:0)+1;l.dropped=d,!this.lastEventRateLimited&&this.zu(d)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)===null||r===void 0||r.set_property("$capture_rate_limit",l),{isRateLimited:u,remainingTokens:l.tokens}}Hu(t){const e=this.instance.config.property_denylist;return!ze(e)||!e.includes(t)}Uu(){var t;if(this.Hu("$current_url")&&this.Hu("$pathname")&&(Ut!=null&&Ut.pathname))return`${(t=Ut.origin)!==null&&t!==void 0?t:""}${Ut.pathname}`}zu(t){var e,n;const{captureEventsBurstLimit:r,captureEventsPerSecond:s}=this,i=this.Uu(),o=this.Hu("$session_id")?(e=(n=this.instance).get_session_id)===null||e===void 0?void 0:e.call(n):void 0,l=[`${t} event(s) dropped since the last warning`,i?`triggered on ${i}`:void 0,o?`session ${o}`:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:`posthog-js client rate limited: ${l}. Config is set to ${s} events per second and ${r} events burst limit.`},{skip_client_rate_limiting:!0})}isServerRateLimited(t){const e=this.serverLimits[t||"events"]||!1;return e!==!1&&new Date().getTime()<e}};const Sa=an("[RemoteConfig]");var lR=class{constructor(t){this._instance=t}get remoteConfig(){var t;return(t=qe._POSTHOG_REMOTE_CONFIG)===null||t===void 0||(t=t[this._instance.config.token])===null||t===void 0?void 0:t.config}Wu(t){var e,n,r;!((e=qe.__PosthogExtensions__)===null||e===void 0)&&e.loadExternalDependency?(n=qe.__PosthogExtensions__)===null||n===void 0||(r=n.loadExternalDependency)===null||r===void 0||r.call(n,this._instance,"remote-config",()=>t(this.remoteConfig)):t()}Vu(t){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets",`/array/${this._instance.config.token}/config`),callback:t})}load(){try{if(this.remoteConfig)return Sa.info("Using preloaded remote config",this.remoteConfig),void this.Gu(this.remoteConfig);if(this._instance.Qu())return void Sa.warn("Remote config is disabled. Falling back to local config.");this.Wu(t=>{if(!t)return Sa.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vu(e=>{this.Gu(e.json,e)});this.Gu(t)})}catch(t){Sa.error("Error loading remote config",t),this.Gu()}}Gu(t,e){!t&&e&&(e.statusCode===0?e.error||Sa.warn("Failed to fetch remote config from PostHog."):Sa.error("Failed to fetch remote config from PostHog."));try{this._instance.Gu(t?{ok:!0,config:t}:{ok:!1})}catch(r){Sa.error("Error applying remote config",r)}if((t==null?void 0:t.hasFeatureFlags)!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var n;(n=this._instance.featureFlags)===null||n===void 0||n.ensureFlagsLoaded()}catch(r){Sa.error("Error loading feature flags",r)}}},ti=Uint8Array,rs=Uint16Array,ld=Uint32Array,eb=new ti([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),tb=new ti([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),E8=new ti([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),cR=function(t,e){for(var n=new rs(31),r=0;31>r;++r)n[r]=e+=1<<t[r-1];var s=new ld(n[30]);for(r=1;30>r;++r)for(var i=n[r];n[r+1]>i;++i)s[i]=i-n[r]<<5|r;return[n,s]},uR=cR(eb,2),T2=uR[1];uR[0][28]=258,T2[258]=28;for(var C8=cR(tb,0)[1],dR=new rs(32768),fn=0;32768>fn;++fn){var fu=(43690&fn)>>>1|(21845&fn)<<1;dR[fn]=((65280&(fu=(61680&(fu=(52428&fu)>>>2|(13107&fu)<<2))>>>4|(3855&fu)<<4))>>>8|(255&fu)<<8)>>>1}var Qf=function(t,e,n){for(var r=t.length,s=0,i=new rs(e);r>s;++s)++i[t[s]-1];var o,l=new rs(e);for(s=0;e>s;++s)l[s]=l[s-1]+i[s-1]<<1;for(o=new rs(r),s=0;r>s;++s)o[s]=dR[l[t[s]-1]++]>>>15-t[s];return o},wc=new ti(288);for(fn=0;144>fn;++fn)wc[fn]=8;for(fn=144;256>fn;++fn)wc[fn]=9;for(fn=256;280>fn;++fn)wc[fn]=7;for(fn=280;288>fn;++fn)wc[fn]=8;var Km=new ti(32);for(fn=0;32>fn;++fn)Km[fn]=5;var eV=Qf(wc,9),tV=Qf(Km,5),fR=function(t){return(t/8|0)+(7&t&&1)},hR=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var r=new(t instanceof rs?rs:t instanceof ld?ld:ti)(n-e);return r.set(t.subarray(e,n)),r},bo=function(t,e,n){var r=e/8|0;t[r]|=n<<=7&e,t[r+1]|=n>>>8},Sf=function(t,e,n){var r=e/8|0;t[r]|=n<<=7&e,t[r+1]|=n>>>8,t[r+2]|=n>>>16},Ly=function(t,e){for(var n=[],r=0;t.length>r;++r)t[r]&&n.push({s:r,f:t[r]});var s=n.length,i=n.slice();if(!s)return[new ti(0),0];if(s==1){var o=new ti(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort(function(T,M){return T.f-M.f}),n.push({s:-1,f:25001});var l=n[0],u=n[1],d=0,f=1,h=2;for(n[0]={s:-1,f:l.f+u.f,l,r:u};f!=s-1;)l=n[n[h].f>n[d].f?d++:h++],u=n[d!=f&&n[h].f>n[d].f?d++:h++],n[f++]={s:-1,f:l.f+u.f,l,r:u};var m=i[0].s;for(r=1;s>r;++r)i[r].s>m&&(m=i[r].s);var v=new rs(m+1),w=R2(n[f-1],v,0);if(w>e){r=0;var _=0,x=w-e,b=1<<x;for(i.sort(function(T,M){return v[M.s]-v[T.s]||T.f-M.f});s>r;++r){var k=i[r].s;if(e>=v[k])break;_+=b-(1<<w-v[k]),v[k]=e}for(_>>>=x;_>0;){var C=i[r].s;e>v[C]?_-=1<<e-v[C]++-1:++r}for(;r>=0&&_;--r){var P=i[r].s;v[P]==e&&(--v[P],++_)}w=e}return[new ti(v),w]},R2=function(t,e,n){return t.s==-1?Math.max(R2(t.l,e,n+1),R2(t.r,e,n+1)):e[t.s]=n},P8=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new rs(++e),r=0,s=t[0],i=1,o=function(u){n[r++]=u},l=1;e>=l;++l)if(t[l]==s&&l!=e)++i;else{if(!s&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(s),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(s);i=1,s=t[l]}return[n.subarray(0,r),e]},kf=function(t,e){for(var n=0,r=0;e.length>r;++r)n+=t[r]*e[r];return n},I2=function(t,e,n){var r=n.length,s=fR(e+2);t[s]=255&r,t[s+1]=r>>>8,t[s+2]=255^t[s],t[s+3]=255^t[s+1];for(var i=0;r>i;++i)t[s+i+4]=n[i];return 8*(s+4+r)},A8=function(t,e,n,r,s,i,o,l,u,d,f){bo(e,f++,n),++s[256];for(var h=Ly(s,15),m=h[0],v=h[1],w=Ly(i,15),_=w[0],x=w[1],b=P8(m),k=b[0],C=b[1],P=P8(_),T=P[0],M=P[1],I=new rs(19),R=0;k.length>R;++R)I[31&k[R]]++;for(R=0;T.length>R;++R)I[31&T[R]]++;for(var L=Ly(I,7),j=L[0],F=L[1],N=19;N>4&&!j[E8[N-1]];--N);var q,W,Y,H,J=d+5<<3,B=kf(s,wc)+kf(i,Km)+o,Q=kf(s,m)+kf(i,_)+o+14+3*N+kf(I,j)+(2*I[16]+3*I[17]+7*I[18]);if(B>=J&&Q>=J)return I2(e,f,t.subarray(u,u+d));if(bo(e,f,1+(B>Q)),f+=2,B>Q){q=Qf(m,v),W=m,Y=Qf(_,x),H=_;var V=Qf(j,F);for(bo(e,f,C-257),bo(e,f+5,M-1),bo(e,f+10,N-4),f+=14,R=0;N>R;++R)bo(e,f+3*R,j[E8[R]]);f+=3*N;for(var D=[k,T],G=0;2>G;++G){var le=D[G];for(R=0;le.length>R;++R)bo(e,f,V[re=31&le[R]]),f+=j[re],re>15&&(bo(e,f,le[R]>>>5&127),f+=le[R]>>>12)}}else q=eV,W=wc,Y=tV,H=Km;for(R=0;l>R;++R)if(r[R]>255){var re;Sf(e,f,q[257+(re=r[R]>>>18&31)]),f+=W[re+257],re>7&&(bo(e,f,r[R]>>>23&31),f+=eb[re]);var ie=31&r[R];Sf(e,f,Y[ie]),f+=H[ie],ie>3&&(Sf(e,f,r[R]>>>5&8191),f+=tb[ie])}else Sf(e,f,q[r[R]]),f+=W[r[R]];return Sf(e,f,q[256]),f+W[256]},nV=new ld([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),rV=(function(){for(var t=new ld(256),e=0;256>e;++e){for(var n=e,r=9;--r;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ny=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function sV(t,e){e===void 0&&(e={});var n=(function(){var h=4294967295;return{p(m){for(var v=h,w=0;m.length>w;++w)v=rV[255&v^m[w]]^v>>>8;h=v},d(){return 4294967295^h}}})(),r=t.length;n.p(t);var s,i,o,l,u,d=(l=10+((s=e).filename&&s.filename.length+1||0),u=8,(function(h,m,v,w,_,x){var b=h.length,k=new ti(w+b+5*(1+Math.floor(b/7e3))+_),C=k.subarray(w,k.length-_),P=0;if(!m||8>b)for(var T=0;b>=T;T+=65535){var M=T+65535;b>M?P=I2(C,P,h.subarray(T,M)):(C[T]=x,P=I2(C,P,h.subarray(T,b)))}else{for(var I=nV[m-1],R=I>>>13,L=8191&I,j=(1<<v)-1,F=new rs(32768),N=new rs(j+1),q=Math.ceil(v/3),W=2*q,Y=function(Ye){return(h[Ye]^h[Ye+1]<<q^h[Ye+2]<<W)&j},H=new ld(25e3),J=new rs(288),B=new rs(32),Q=0,V=0,D=(T=0,0),G=0,le=0;b>T;++T){var re=Y(T),ie=32767&T,ue=N[re];if(F[ie]=ue,N[re]=ie,T>=G){var fe=b-T;if((Q>7e3||D>24576)&&fe>423){P=A8(h,C,0,H,J,B,V,D,le,T-le,P),D=Q=V=0,le=T;for(var de=0;286>de;++de)J[de]=0;for(de=0;30>de;++de)B[de]=0}var ne=2,Ce=0,De=L,Ee=ie-ue&32767;if(fe>2&&re==Y(T-Ee))for(var ft=Math.min(R,fe)-1,At=Math.min(32767,T),zt=Math.min(258,fe);At>=Ee&&--De&&ie!=ue;){if(h[T+ne]==h[T+ne-Ee]){for(var wt=0;zt>wt&&h[T+wt]==h[T+wt-Ee];++wt);if(wt>ne){if(ne=wt,Ce=Ee,wt>ft)break;var Tt=Math.min(Ee,wt-2),sn=0;for(de=0;Tt>de;++de){var Re=T-Ee+de+32768&32767,it=Re-F[Re]+32768&32767;it>sn&&(sn=it,ue=Re)}}}Ee+=(ie=ue)-(ue=F[ie])+32768&32767}if(Ce){H[D++]=268435456|T2[ne]<<18|C8[Ce];var Fe=31&T2[ne],Qe=31&C8[Ce];V+=eb[Fe]+tb[Qe],++J[257+Fe],++B[Qe],G=T+ne,++Q}else H[D++]=h[T],++J[h[T]]}}P=A8(h,C,x,H,J,B,V,D,le,T-le,P)}return hR(k,0,w+fR(P)+_)})(i=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(i.length)))):12+o.mem,l,u,!0)),f=d.length;return(function(h,m){var v=m.filename;if(h[0]=31,h[1]=139,h[2]=8,h[8]=2>m.level?4:m.level==9?2:0,h[9]=3,m.mtime!=0&&Ny(h,4,Math.floor(new Date(m.mtime||Date.now())/1e3)),v){h[3]=8;for(var w=0;v.length>=w;++w)h[w+10]=v.charCodeAt(w)}})(d,e),Ny(d,f-8,n.d()),Ny(d,f-4,r),d}const iV=!!Lx||!!hh,pR=new WeakMap,mR="text/plain";let Dy=0,lm=!1;const gR=(t,e)=>{const[n,r]=t.split("#"),[s,i]=n.split("?");if(!i)return t;const o=i.split("&").filter(l=>l.split("=")[0]!==e).join("&");return`${s}${o?`?${o}`:""}${r?`#${r}`:""}`},Zg=(t,e,n=!0)=>{var r;const[s,i]=t.split("?"),o=$({},e),l=(r=i==null?void 0:i.split("&").map(d=>{var f;const[h,m]=d.split("="),v=n&&(f=o[h])!==null&&f!==void 0?f:m;return delete o[h],`${h}=${v}`}))!==null&&r!==void 0?r:[],u=(function(d,f="&"){let h,m;const v=[];return Pt(d,function(w,_){ae(w)||ae(_)||_==="undefined"||(h=encodeURIComponent((x=>x instanceof File)(w)?w.name:w.toString()),m=encodeURIComponent(_),v[v.length]=m+"="+h)}),v.join(f)})(o);return u&&l.push(u),l.length>0?`${s}?${l.join("&")}`:s},jy=t=>{if(t.lr)return t.lr;const{data:e,compression:n}=t;if(!e)return;if(n===Ss.GZipJS){const s=sV((function(i){var o=i.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(i);for(var l=new ti(i.length+(i.length>>>1)),u=0,d=function(v){l[u++]=v},f=0;o>f;++f){if(u+5>l.length){var h=new ti(u+8+(o-f<<1));h.set(l),l=h}var m=i.charCodeAt(f);128>m?d(m):2048>m?(d(192|m>>>6),d(128|63&m)):m>55295&&57344>m?(d(240|(m=65536+(1047552&m)|1023&i.charCodeAt(++f))>>>18),d(128|m>>>12&63),d(128|m>>>6&63),d(128|63&m)):(d(224|m>>>12),d(128|m>>>6&63),d(128|63&m))}return hR(l,0,u)})(Tu(e)),{mtime:0});return{contentType:mR,body:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),estimatedSize:s.byteLength}}if(n===Ss.Base64){const s=(function(o){return o&&btoa(encodeURIComponent(o).replace(/%([0-9A-F]{2})/g,(l,u)=>String.fromCharCode(parseInt(u,16))))})(Tu(e)),i=(o=>"data="+encodeURIComponent(typeof o=="string"?o:Tu(o)))(s);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}const r=Tu(e);return{contentType:"application/json",body:r,estimatedSize:new Blob([r]).size}},vR=t=>{const e=()=>t.transport==="sendBeacon"?{url:Zg(t.url,{compression:Ss.Base64}),encodedBody:jy($($({},t),{},{compression:Ss.Base64,lr:void 0}))}:{url:gR(t.url,"compression"),encodedBody:jy($($({},t),{},{compression:void 0,lr:void 0}))};let n;try{n=jy(t)}catch(s){if(Uk(t.compression,od(t.url,"compression")))return he.error("Failed to gzip request body, sending uncompressed payload",s),e();throw s}return n&&Uk(t.compression,od(t.url,"compression"))&&!((r=n.body)instanceof ArrayBuffer?d2(new Uint8Array(r)):ArrayBuffer.isView(r)&&d2(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)))?(lm=!0,e()):{url:t.url,encodedBody:n};var r},yR=t=>{try{return vR(t)}catch(n){var e;return he.error(n),void((e=t.callback)===null||e===void 0||e.call(t,{statusCode:0,error:n}))}},oV=(function(){var t=Wt(function*(e){const n=yield(function(s){return f2.apply(this,arguments)})(Tu(e.data),Jr.DEBUG,{rethrow:!0});if(!n)return e;const r=yield n.arrayBuffer();return $($({},e),{},{lr:{contentType:mR,body:r,estimatedSize:r.byteLength}})});return function(e){return t.apply(this,arguments)}})(),aV=/Failed to fetch|NetworkError|Load failed/i,_R=t=>(t==null?void 0:t.name)==="TypeError"&&aV.test((t==null?void 0:t.message)||""),wR=t=>{try{const e=(function(n,r=Date.now()){if(typeof n!="string"||!n)return;const s=n.trim(),i=/^\d+\s*,/.test(s)?s.slice(0,s.indexOf(",")).trim():s;if(/^\d+$/.test(i)){const u=1e3*Math.min(Number(i),300);return u>0?u:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(i))return;const o=/^\w{3} \w{3} /.test(i)?i+" GMT":i,l=Date.parse(o)-r;return Number.isFinite(l)&&l>0?Math.min(l,rm):void 0})(t());return ae(e)?void 0:Math.min(e,3e4)}catch{return}},xR=t=>{const e=yR(t);if(!e)return;const n=new Lx;pR.set(n,!0);const{url:r,encodedBody:s}=e;n.open(t.method||"GET",r,!0);const{contentType:i,body:o}=s??{};Pt(t.headers,function(l,u){n.setRequestHeader(u,l)}),i&&n.setRequestHeader("Content-Type",i),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var l;const u={statusCode:n.status,text:n.responseText};if(n.status===200)try{u.json=JSON.parse(n.responseText)}catch{}(l=t.callback)===null||l===void 0||l.call(t,u,wR(()=>n.getResponseHeader("Retry-After")))}},n.send(o)},bR=t=>{const e=yR(t);if(!e)return;const{url:n,encodedBody:r}=e,{contentType:s,body:i,estimatedSize:o}=r??{},l=new Headers;Pt(t.headers,function(w,_){l.append(_,w)}),s&&l.append("Content-Type",s);let u=null,d=!1;if(Ck){const w=new Ck;u={signal:w.signal,timeout:setTimeout(()=>{d=!0;try{w.abort(G5("AbortError","PostHog request timed out"+((_=t.timeout)?` after ${_}ms`:"")))}catch(x){h(x)}var _},t.timeout)}}let f=!1;const h=w=>{var _;f||(f=!0,d&&(w==null?void 0:w.name)==="AbortError"||_R(w)?he.warn(w):he.error(w),(_=t.callback)===null||_===void 0||_.call(t,{statusCode:0,error:w}))};let m=0;const v=()=>{Dy-=m,m=0,u&&clearTimeout(u.timeout)};try{const w=$({method:(t==null?void 0:t.method)||"GET",headers:l,referrerPolicy:"strict-origin",body:i,signal:u==null?void 0:u.signal},t.fetchOptions),_=o??(ae(i)?0:void 0);w.keepalive=w.method==="POST"&&!t.kl&&w.keepalive!==!1&&w.body===i&&!ae(_)&&_>=0&&52428.8>Dy+_,w.keepalive&&(m=_,Dy+=m),hh(n,w).then(x=>x.text().then(b=>{var k;if(f)return;const C={statusCode:x.status,text:b};if(x.status===200)try{C.json=JSON.parse(b)}catch(P){he.error(P)}f=!0,v(),(k=t.callback)===null||k===void 0||k.call(t,C,wR(()=>x.headers.get("Retry-After")))})).catch(x=>{v(),h(x)}).finally(v)}catch(w){v(),h(w)}},M2=t=>{try{var e;const{url:n,encodedBody:r}=vR(t),{contentType:s,body:i,estimatedSize:o}=r??{};if(!i)return;const l=i instanceof Blob?i:new Blob([i],{type:s});if(gr.sendBeacon(n,l))return;const u=ze(t.data)?t.data:(e=t.data)===null||e===void 0?void 0:e.batch;if(ze(u)&&u.length>1&&(o??0)>16384){const d=Math.ceil(u.length/2),f=h=>ze(t.data)?h:$($({},t.data),{},{batch:h});return M2($($({},t),{},{data:f(u.slice(0,d))})),void M2($($({},t),{},{data:f(u.slice(d))}))}he.warn(`Beacon of ~${o??0} bytes was rejected by the browser, falling back to ${hh?"fetch":"XHR"}`),hh?bR($($({},t),{},{kl:!0})):xR(t)}catch(n){he.warn("Beacon send failed",n)}},T8=(t,e,n,r)=>{const s=r==="query"?e==="POST"?"sent_at":"_":void 0;return Zg(n===Ss.GZipJS?gR(t,"compression"):t,$($({},s?{[s]:Date.now().toString()}:{}),n===Ss.GZipJS?{}:{compression:n}))},lV=(()=>{const t=[];return hh&&t.push({transport:"fetch",method:bR}),Lx&&t.push({transport:"XHR",method:xR}),gr!=null&&gr.sendBeacon&&t.push({transport:"sendBeacon",method:M2}),t})();let SR=!iV&&(Vr==null?void 0:Vr.indexOf("MSIE"))===-1&&(Vr==null?void 0:Vr.indexOf("Mozilla"))===-1;function kR(t,e,n){var r,s,i;n&&(e=$($({},e),{},{callback:o=>n(o)})),t.__loaded?SR?t.__request_queue.push(e):t.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&((s=e.callback)===null||s===void 0||s.call(e,{statusCode:429})):(e.transport=e.transport||t.config.api_transport,e.headers=$($({},t.config.request_headers),e.headers),e.compression=e.compression==="best-available"?(r=t.compression)!==null&&r!==void 0?r:e.compressionFallback:e.compression,(ae(t.config.disable_beacon)?t.config.__preview_disable_beacon:t.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||t.config.fetch_options,((o,l)=>{var u,d,f;const h=$($({},o),{},{callback:l??(x=>{var b;return(b=o.callback)===null||b===void 0?void 0:b.call(o,x)})});h.timeout=h.timeout||6e4;const m=(u=h.transport)!==null&&u!==void 0?u:"fetch";m==="sendBeacon"&&ae(h.compression)&&h.data&&(h.compression=Ss.Base64),h.method==="POST"&&h.data&&(h.timestampMode==="capture-body"?h.data=(x=>{var b,k;const C=(ze(x)?x:[x]).map(T=>$($({},T),T.timestamp instanceof Date&&!isNaN(T.timestamp.getTime())?{timestamp:T.timestamp.toISOString()}:{})),P=C[0];return{api_key:(b=P==null||(k=P.properties)===null||k===void 0?void 0:k.token)!==null&&b!==void 0?b:P==null?void 0:P.token,batch:C,sent_at:new Date().toISOString()}})(h.data):h.timestampMode==="body"&&(h.data=((x,b=new Date().toISOString())=>ze(x)?x.map(k=>$($({},k),{},{sent_at:b})):$($({},x),{},{sent_at:b}))(h.data))),h.url=T8(h.url,h.method,h.compression,h.timestampMode);const v=lV.filter(x=>!h.disableTransport||!x.transport||!h.disableTransport.includes(x.transport)),w=(d=(f=(function(x,b){for(let k=0;x.length>k;k++)if(b(x[k]))return x[k]})(v,x=>x.transport===m))===null||f===void 0?void 0:f.method)!==null&&d!==void 0?d:v[0].method;if(!w)throw new Error("No available transport method");const _=x=>{try{w(x)}catch(k){var b;_R(k)?he.warn(k):he.error(k),(b=h.callback)===null||b===void 0||b.call(h,{statusCode:0,error:k})}};m!=="sendBeacon"&&!h.preferSyncCompression&&h.data&&h.compression===Ss.GZipJS&&x7&&typeof Promise<"u"&&!lm?oV(h).then(x=>{_(x)}).catch(x=>{if(Bk(x))return lm=!0,void _($($({},h),{},{compression:void 0,url:T8(o.url,o.method,void 0,o.timestampMode)}));(b=>{if(!b||typeof b!="object")return!1;const k="name"in b?String(b.name):"";return Bk(b)||k===tT})(x)&&(lm=!0),_(h)}):_(h)})(e,(o,l)=>{var u,d,f;t.rateLimiter.checkForLimiting(o),400>o.statusCode||(u=(d=t.config).on_request_error)===null||u===void 0||u.call(d,o),n?n(o,l):(f=e.callback)===null||f===void 0||f.call(e,o)})):e.fireCallbackOnDrop&&((i=e.callback)===null||i===void 0||i.call(e,{statusCode:0}))}var cV=class{constructor(t,e){this.Zu=!0,this.Ju=[],this.Ku=Zi((e==null?void 0:e.flush_interval_ms)||3e3,250,5e3,he.createLogger("flush interval"),3e3),this.Xu=t}enqueue(t){this.Ju.push(t),this.Yu||this.tc()}unload(){this.ec();const t=this.Ju.length>0?this.nc():{},e=Object.values(t);[...e.filter(n=>n.url.indexOf("/e")===0),...e.filter(n=>n.url.indexOf("/e")!==0)].map(n=>{this.sc($($({},n),{},{callback:void 0}),"sendBeacon")})}enable(){this.Zu=!1,this.tc()}tc(){this.Zu||(this.Yu=setTimeout(()=>{this.ec(),this.rc()},this.Ku))}rc(){if(this.Ju.length>0){const t=this.nc();for(const e in t)this.sc(t[e])}}sc(t,e){try{this.Xu(t,e)}catch(n){he.error(n)}}ec(){clearTimeout(this.Yu),this.Yu=void 0}nc(){const t={},e={};Pt(this.Ju,n=>{var r;const s=n,i=((s?s.batchKey:null)||s.url)+(s.batchGroup?`:${s.batchGroup}`:"");ae(t[i])&&(t[i]=$($({},s),{},{data:[],callback:void 0,fireCallbackOnDrop:void 0}),e[i]=[]),(r=t[i].data)===null||r===void 0||r.push(s.data),s.callback&&e[i].push(s.callback)});for(const n in e){const r=e[n];r.length&&(t[n].callback=s=>{for(const i of r)i(s)})}return this.Ju=[],t}};const uV=["retriesPerformedSoFar"];var dV=class{constructor(t){this._instance=t,this.oc=!1,this.ac=3e3,this.Ju=[],this.Ju=[],this.lc=!0,this.resume()}resume(){if(!ae(oe)&&"onLine"in oe.navigator){if(this.lc=oe.navigator.onLine,this.uc)return;this.uc=()=>{this.lc=!0,this.rc()},this.cc=()=>{this.lc=!1},_t(oe,"online",this.uc),_t(oe,"offline",this.cc)}}get length(){return this.Ju.length}retriableRequest(t,e){let{retriesPerformedSoFar:n}=t,r=nT(t,uV);Ao(n)&&(r.url=Zg(r.url,{retry_count:n})),kR(this._instance,e?$($({},r),{},{transport:e}):r,(s,i)=>{var o;if(s.statusCode!==200&&(400>s.statusCode||s.statusCode>=500)){if((s.statusCode===0?3:10)>(n??0))return void this.Ls($({retriesPerformedSoFar:n},r),i);s.statusCode===0&&he.warn(`Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after ${n??0} retries.`)}(o=r.callback)===null||o===void 0||o.call(r,s)})}Ls(t,e){const n=t.retriesPerformedSoFar||0;t.retriesPerformedSoFar=n+1;const r=Math.max((function(o){const l=3e3*Math.pow(2,o),u=l/2,d=Math.min(18e5,l),f=(Math.random()-.5)*(d-u);return Math.ceil(d+f)})(n),e??0),s=Date.now()+r;this.Ju.push({retryAt:s,requestOptions:t});let i=`Enqueued failed request for retry in ${r}`;navigator.onLine||(i+=" (Browser is offline)"),he.warn(i),this.oc||(this.oc=!0,this.hc())}hc(){if(this.dc&&clearTimeout(this.dc),this.Ju.length===0)return this.oc=!1,void(this.dc=void 0);this.dc=setTimeout(()=>{this.lc&&this.Ju.length>0&&this.rc(),this.hc()},this.ac)}rc(){const t=Date.now(),e=[],n=this.Ju.filter(r=>t>r.retryAt||(e.push(r),!1));if(this.Ju=e,n.length>0)for(const{requestOptions:r}of n)this.retriableRequest(r)}unload(){this.dc&&(clearTimeout(this.dc),this.dc=void 0),this.oc=!1,ae(oe)||(this.uc&&(oe.removeEventListener("online",this.uc),this.uc=void 0),this.cc&&(oe.removeEventListener("offline",this.cc),this.cc=void 0));for(const{requestOptions:t}of this.Ju)try{this._instance._send_request($($({},t),{},{callback:ze(t.data)?void 0:t.callback,transport:"sendBeacon"}))}catch(e){he.error(e)}this.Ju=[]}},fV=class{constructor(t){this._instance=t,this.vc=()=>{var e,n,r,s;this.fc||(this.fc={});const i=this.scrollElement(),o=this.scrollY(),l=i?Math.max(0,i.scrollHeight-i.clientHeight):0,u=o+((i==null?void 0:i.clientHeight)||0),d=(i==null?void 0:i.scrollHeight)||0;this.fc.lastScrollY=Math.ceil(o),this.fc.maxScrollY=Math.max(o,(e=this.fc.maxScrollY)!==null&&e!==void 0?e:0),this.fc.maxScrollHeight=Math.max(l,(n=this.fc.maxScrollHeight)!==null&&n!==void 0?n:0),this.fc.lastContentY=u,this.fc.maxContentY=Math.max(u,(r=this.fc.maxContentY)!==null&&r!==void 0?r:0),this.fc.maxContentHeight=Math.max(d,(s=this.fc.maxContentHeight)!==null&&s!==void 0?s:0)}}get gc(){return this._instance.config.scroll_root_selector}getContext(){return this.fc}resetContext(){const t=this.fc;return this.fc=void 0,setTimeout(this.vc,0),t}startMeasuringScrollPosition(){_t(oe,"scroll",this.vc,{capture:!0}),_t(oe,"scrollend",this.vc,{capture:!0}),_t(oe,"resize",this.vc)}scrollElement(){if(this.gc){const n=ze(this.gc)?this.gc:[this.gc];for(const r of n){var t;const s=oe==null||(t=oe.document)===null||t===void 0?void 0:t.querySelector(r);if(s)return s}return}var e;return oe==null||(e=oe.document)===null||e===void 0?void 0:e.documentElement}mc(t){var e,n;const r=t==="y"?"scrollTop":"scrollLeft";if(this.gc){const s=this.scrollElement();return s&&s[r]||0}return oe?t==="y"?oe.scrollY||oe.pageYOffset||((e=oe.document)===null||e===void 0||(e=e.documentElement)===null||e===void 0?void 0:e.scrollTop)||0:oe.scrollX||oe.pageXOffset||((n=oe.document)===null||n===void 0||(n=n.documentElement)===null||n===void 0?void 0:n.scrollLeft)||0:0}scrollY(){return this.mc("y")}scrollX(){return this.mc("x")}};const hV=t=>iR(t==null?void 0:t.config.mask_personal_data_properties,t==null?void 0:t.config.custom_personal_data_properties,t==null?void 0:t.config.disable_capture_url_hashes);var R8=class{constructor(t,e,n,r){this.qe=s=>{const i=this.yc();if(i&&i.sessionId===s)return;const o={sessionId:s,props:this.bc(this._instance)};this._c.register({[S2]:o})},this._instance=t,this.wc=e,this._c=n,this.bc=r||hV,this.wc.onSessionId(this.qe)}yc(){return this._c.props[S2]}getSetOnceProps(){var t;const e=(t=this.yc())===null||t===void 0?void 0:t.props;return e?"r"in e?oR(e,this._instance.config.disable_capture_url_hashes):{$referring_domain:e.referringDomain,$pathname:e.initialPathName,utm_source:e.utm_source,utm_campaign:e.utm_campaign,utm_medium:e.utm_medium,utm_content:e.utm_content,utm_term:e.utm_term}:{}}getSessionProps(){const t={};return Pt(Kx(this.getSetOnceProps()),(e,n)=>{n==="$current_url"&&(n="url"),t[`$session_entry_${i2(n)}`]=e}),t}},Ym=class{on(t,e){return this.bo[t]||(this.bo[t]=[]),this.bo[t].push(e),()=>{this.bo[t]=this.bo[t].filter(n=>n!==e)}}emit(t,e){for(const n of this.bo[t]||[])n(e);for(const n of this.bo["*"]||[])n(t,e)}constructor(){this.bo={}}};const hu=an("[SessionId]"),I8=864e5;var M8=class{on(t,e){return this.kc.on(t,e)}constructor(t,e,n){var r;if(this.Sc=null,this.xc=null,this.$c=[],this.Cc=void 0,this.Tc=!1,this.kc=new Ym,this.Ic=(i,o)=>!(!Ao(i)||!Ao(o))&&Math.abs(i-o)>this.sessionTimeoutMs,!t.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(t.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ar=t.config,this._c=t.persistence,this.je=void 0,this.Xt=void 0,this._sessionStartTimestamp=null,this.Mc=void 0,this._sessionActivityTimestamp=null,this.Ec=e||xi,this.Pc=n||xi;const s=this.Ar.persistence_name||this.Ar.token;if(this._sessionTimeoutMs=1e3*Zi(this.Ar.session_idle_timeout_seconds||1800,60,36e3,hu.createLogger("session_idle_timeout_seconds"),1800),t.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.Rc(),this.Ac="ph_"+s+"_window_id",this.Fc="ph_"+s+"_primary_window_exists",this.Oc()){const i=Bt.Lt(this.Ac),o=Bt.Lt(this.Fc);i&&!o?this.je=i:Bt.Pt(this.Ac),Bt.At(this.Fc,!0)}!((r=this.Ar.bootstrap)===null||r===void 0)&&r.sessionID&&this.setBootstrapSessionId(this.Ar.bootstrap.sessionID),this.Dc()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(t){return ae(this.$c)&&(this.$c=[]),this.$c.push(t),this.Xt&&t(this.Xt,this.je),()=>{this.$c=this.$c.filter(e=>e!==t)}}Oc(){return this.Ar.persistence!=="memory"&&!this._c.hi&&Bt.Et()}Lc(t){t!==this.je&&(this.je=t,this.Oc()&&Bt.At(this.Ac,t))}Nc(){return this.je?this.je:this.Oc()?Bt.Lt(this.Ac):null}qc(t){const e=this.Sc;return!dn(e)&&!dn(t)&&5e3>Math.abs(t-e)}jc(t,e,n){const r=e!==this._sessionActivityTimestamp,s=!(t!==this.Xt||n!==this._sessionStartTimestamp);this._sessionStartTimestamp=n,this._sessionActivityTimestamp=e,this.Xt=t,s&&!r||s&&this.qc(e)||(this.Sc=e,this._c.register({[Cu]:[e,t,n]}))}Bc(){var t;const e=(t=this.Ar)===null||t===void 0?void 0:t.persistence_save_debounce_ms;return Ao(e)&&e>0}zc(){this.Bc()?this._c.refreshKey(Cu):(this._c.flush(),this._c.load())}Hc(){var t;if(dn(this._sessionActivityTimestamp)||this._sessionActivityTimestamp===this.Sc)return;this.zc();const[,e,n]=this.Uc();e===this.Xt&&n===this._sessionStartTimestamp&&(this.Sc=this._sessionActivityTimestamp,this._c.register({[Cu]:[this._sessionActivityTimestamp,(t=this.Xt)!==null&&t!==void 0?t:null,this._sessionStartTimestamp]}),this._c.flush())}Wc(){const[t]=this.Uc(),e=Ao(t)?t:0,n=Ao(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(e,n)}Vc(t){return this.zc(),this.Ic(t,this.Wc())}Uc(){const t=this._c.props[Cu];return ze(t)&&t.length===2&&t.push(t[0]),t||[0,null,0]}resetSessionId(){this.Sc=null,this.Mc=void 0,clearTimeout(this.Gc),this.Gc=void 0,this.jc(null,null,null)}setBootstrapSessionId(t,e=!1){const n=((r,s=new Date().getTime())=>{try{const i=(o=>{const l=o.replace(/-/g,"");if(l.length!==32)throw new Error("Not a valid UUID");if(l[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(l.substring(0,12),16)})(r);return i>s+6e4?void hu.error("Bootstrap sessionID cannot be in the future"):i}catch(i){return void hu.error("Invalid sessionID in bootstrap",i)}})(t);return!ae(n)&&(e?this.Mc={sessionId:t,sessionStartTimestamp:n}:this.jc(t,new Date().getTime(),n),!0)}destroy(){this.Tc=!0,this.Hc(),clearTimeout(this.Gc),this.Gc=void 0,this.Cc&&oe&&(oe.removeEventListener(Wm,this.Cc,{capture:!1}),this.Cc=void 0),this.$c=[]}Dc(){this.Cc=()=>{this.Hc(),this.Oc()&&Bt.Pt(this.Fc)},_t(oe,Wm,this.Cc,{capture:!1})}checkAndGetSessionAndWindowId(t=!1,e=null,n=!1){if(this.Ar.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');const r=e||new Date().getTime(),s=this.Xt;if(n)this.xc=r;else if(dn(this.xc)||this.xc>r||r-this.xc>=1e3){var i,o;(i=(o=this._c).syncCookieProperties)===null||i===void 0||i.call(o),this.xc=r}let[,l,u]=this.Uc();const d=!ae(s)&&l!==s,f=this.Wc();let h=this.Nc();const m=this.Mc,v=!!m&&(m.sessionStartTimestamp>r+6e4||r-m.sessionStartTimestamp>I8),w=m?v:Ao(u)&&Math.abs(r-u)>I8;let _=!1,x=d,b=!l||!!m;const k=l;let C=!b&&!t&&this.Ic(r,f);if(C&&(C=this.Vc(r),C||hu.info("cross-tab refresh kept the session alive",{sessionId:l}),[,l,u]=this.Uc(),C||(b=!l||!!m)),b||C||w){x=!1;const I=m&&!v;l=I?m.sessionId:this.Ec(),h=this.Pc(),hu.info("new session ID assigned",{sessionId:l,windowId:h,bootstrapped:!!I,changeReason:{noSessionId:b,activityTimeout:C,sessionPastMaximumLength:w}}),u=I?m.sessionStartTimestamp:r,this.Mc=void 0,_=!0}else h||(h=this.Pc(),_=!0),x=x||l!==k,x&&(hu.info("adopted cross-tab session id",{sessionId:l,windowId:h}),_=!0);const P=Ao(f)&&t&&!w?f:r,T=Ao(u)?u:new Date().getTime();this.Lc(h),this.jc(l,P,T),t||this.Rc();const M={noSessionId:b,activityTimeout:C,sessionPastMaximumLength:w,crossTabAdoption:x};return _&&this.$c.forEach(I=>I(l,h,M)),{sessionId:l,windowId:h,sessionStartTimestamp:T,changeReason:_?M:void 0,lastActivityTimestamp:f}}Rc(){this.Tc||(clearTimeout(this.Gc),this.Gc=setTimeout(()=>{if(!this.Tc)if(this.Vc(new Date().getTime())){const t=this.Xt;this.resetSessionId(),this.kc.emit("forcedIdleReset",{idleSessionId:t})}else this.Rc()},1.1*this.sessionTimeoutMs))}};const O8=Object.freeze(["2026-08-30","2026-08-29","2026-06-25","2026-05-30","2026-01-30","2025-11-30","2025-05-24"]),ER=function(t,e){if(!t)return!1;const n=t.userAgent;if(n&&Ak(n,e))return!0;try{const r=t==null?void 0:t.userAgentData;if(r!=null&&r.brands&&r.brands.some(s=>Ak(s==null?void 0:s.brand,e)))return!0}catch{}return!!t.webdriver};function CR(){return(CR=Wt(function*(){const t=gr==null?void 0:gr.userAgentData;if(t!=null&&t.getHighEntropyValues)try{const e=yield t.getHighEntropyValues(["model"]),n=e==null?void 0:e.model;return rt(n)&&n.length>0?n:void 0}catch(e){return void he.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",e)}})).apply(this,arguments)}function pV(t,e){let n=`$survey_${e}/${t.id}`;return t.current_iteration&&t.current_iteration>0&&(n=`$survey_${e}/${t.id}/${t.current_iteration}`),n}function PR(t){var e;return!!(!((e=t.conditions)===null||e===void 0||(e=e.events)===null||e===void 0||(e=e.values)===null||e===void 0)&&e.length)}const Xm=(t,e)=>{if(!(n=>{try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}},E0=t=>t.toLowerCase(),AR={exact:(t,e)=>e.some(n=>t.some(r=>n===r)),is_not:(t,e)=>e.every(n=>t.every(r=>n!==r)),regex:(t,e)=>e.some(n=>t.some(r=>Xm(n,r))),not_regex:(t,e)=>e.every(n=>t.every(r=>!Xm(n,r))),icontains:(t,e)=>e.map(E0).some(n=>t.map(E0).some(r=>n.includes(r))),not_icontains:(t,e)=>e.map(E0).every(n=>t.map(E0).every(r=>!n.includes(r))),gt:(t,e)=>e.some(n=>{const r=parseFloat(n);return!isNaN(r)&&t.some(s=>r>parseFloat(s))}),lt:(t,e)=>e.some(n=>{const r=parseFloat(n);return!isNaN(r)&&t.some(s=>r<parseFloat(s))})};function TR(t,e){return!t||Object.entries(t).every(([n,r])=>{const s=e==null?void 0:e[n];if(s==null)return!1;const i=AR[r.operator];return!!i&&i(r.values.map(String),[String(s)])})}function $y(t,e,n){return Tu({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}const O2="custom",L8="i.posthog.com",mV=/^\/static\//,gV=["/s/","/e/","/i/"];var vV=class{constructor(t){this.Qc={},this.instance=t}get apiHost(){const t=this.instance.config.api_host.trim().replace(/\/$/,"");return t==="https://app.posthog.com"?"https://us.i.posthog.com":t}get flagsApiHost(){const t=this.instance.config.flags_api_host;return t?t.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var t;let e=(t=this.instance.config.ui_host)===null||t===void 0?void 0:t.replace(/\/$/,"");return e||(e=this.apiHost.replace(`.${L8}`,".posthog.com")),e==="https://app.posthog.com"?"https://us.posthog.com":e}get region(){return this.Qc[this.apiHost]||(this.Qc[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":O2),this.Qc[this.apiHost]}Zc(t){if(!mV.test(t))return;const e=this.instance.config.asset_host;return typeof e=="string"&&e.trim().replace(/\/$/,"")||void 0}Jc(t){const e=qo(t);return e?e.protocol+"//"+e.host+e.pathname:void 0}Kc(t,e,n){if(t==="ui")return n;let r=n;const s=this.instance.config.rewriteRequestPath;if(s){var i;const o=((i=qo(n))===null||i===void 0?void 0:i.href)||n;r=s(new URL(o)).toString()}if(s&&t==="api"&&gV.some(o=>e.indexOf(o)===0)){const o=this.Jc(r);if(o){const l=this.apiHost;let u=this.Xc;(u==null?void 0:u.apiHost)===l&&u.rewriteRequestPath===s||(u={apiHost:l,rewriteRequestPath:s,urls:new Set},this.Xc=u),u.urls.add(o)}}return r}isIngestionEndpoint(t){const e=this.Xc,n=this.Jc(t);return(e==null?void 0:e.apiHost)===this.apiHost&&e.rewriteRequestPath===this.instance.config.rewriteRequestPath&&!!n&&e.urls.has(n)}endpointFor(t,e=""){if(e&&(e=e[0]==="/"?e:`/${e}`),t==="ui")return this.Kc(t,e,this.uiHost+e);if(t==="flags")return this.Kc(t,e,this.flagsApiHost+e);if(t==="assets"){const r=this.Zc(e);if(r)return this.Kc(t,e,`${r}${e}`)}if(this.region===O2)return this.Kc(t,e,this.apiHost+e);const n=L8+e;switch(t){case"assets":return this.Kc(t,e,`https://${this.region}-assets.${n}`);case"api":return this.Kc(t,e,`https://${this.region}.${n}`)}}};const Ct=an("[Surveys]"),RR=t=>{try{const e=(n=>((r,s)=>`seenSurvey_${(function(i){return i.current_iteration&&i.current_iteration>0?`${i.id}_${i.current_iteration}`:i.id})(s)}`)(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(e){Ct.error("Failed to persist survey seen state",e)}},yV=[My.Popover,My.Widget,My.API],_V={ignoreConditions:!1,ignoreDelay:!1,displayType:A2.Popover},wV=an("[PostHog ExternalIntegrations]"),xV={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};var bV=class{constructor(t){this._instance=t}Ml(t,e){var n,r;(n=qe.__PosthogExtensions__)===null||n===void 0||(r=n.loadExternalDependency)===null||r===void 0||r.call(n,this._instance,t,s=>{if(s)return wV.error("failed to load script",s);e()})}startIfEnabledOrStop(){var t;for(const[s,i]of Object.entries((t=this._instance.config.integrations)!==null&&t!==void 0?t:{})){var e,n,r;i&&!(!((e=qe.__PosthogExtensions__)===null||e===void 0||(e=e.integrations)===null||e===void 0)&&e[s])&&this.Ml(xV[s],()=>{var o;(o=qe.__PosthogExtensions__)===null||o===void 0||(o=o.integrations)===null||o===void 0||(o=o[s])===null||o===void 0||o.start(this._instance)}),!i&&(!((n=qe.__PosthogExtensions__)===null||n===void 0||(n=n.integrations)===null||n===void 0)&&n[s])&&((r=qe.__PosthogExtensions__)===null||r===void 0||(r=r.integrations)===null||r===void 0||(r=r[s])===null||r===void 0||r.stop())}}},IR=class{constructor(t){this.disabled=t===!1;const e=nt(t)?t:{};this.thresholdPx=e.threshold_px||30,this.timeoutMs=e.timeout_ms||1e3,this.clickCount=e.click_count||3,this.clicks=[]}isRageClick(t,e,n){if(this.disabled)return!1;const r=this.clicks[this.clicks.length-1];if(r&&Math.abs(t-r.x)+Math.abs(e-r.y)<this.thresholdPx&&this.timeoutMs>n-r.timestamp){if(this.clicks.push({x:t,y:e,timestamp:n}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:t,y:e,timestamp:n}];return!1}};const L2=()=>typeof window>"u"?void 0:window,Ef=()=>typeof document>"u"?void 0:document,Fy="$copy_autocapture",SV=["password","hidden","file","checkbox","button","submit","reset","image"],C0=an("[AutoCapture]");function Vy(t,e){return e.length>t?e.slice(0,t)+"...":e}function kV(t){if(t.previousElementSibling)return t.previousElementSibling;let e=t;do e=e.previousSibling;while(e&&!ei(e));return e}function EV(t,{e,maskAllElementAttributes:n,maskAllText:r,elementAttributeIgnoreList:s,elementsChainAsString:i,disableCaptureUrlHashes:o}){var l,u;if(!ei(t))return{props:{}};const d=[t],f=new Set([t]);let h=t;for(;h.parentNode&&!Nn(h,"body")&&1e3>d.length;){if(Zm(h.parentNode)){const M=h.parentNode.host;if(f.has(M))break;f.add(M),d.push(M),h=M;continue}if(!ei(h.parentNode)||f.has(h.parentNode))break;f.add(h.parentNode),d.push(h.parentNode),h=h.parentNode}const m=e.type==="click"&&t.namespaceURI==="http://www.w3.org/2000/svg"?d.findIndex(M=>Nn(M,"button")||Nn(M,"a")):-1;m>0&&(r=r||d.slice(0,m+1).some(M=>!Wa(M)||id(M)));const v=[],w={};let _,x=!1,b=!1;if(Pt(d,M=>{const I=Wa(M);if(Nn(M,"a")&&!n&&!(s!=null&&s.includes("href"))){const R=M.getAttribute("href");x=!!(I&&R&&$u(R))&&(o?Ya(R):R)}je(uc(M),"ph-no-capture")&&(b=!0),v.push((function(R,L,j,F,N=!1){const q=R.tagName.toLowerCase(),W={tag_name:q};Xx.indexOf(q)>-1&&!j&&(W.$el_text=q.toLowerCase()==="a"||q.toLowerCase()==="button"?Vy(1024,g8(R)):Vy(1024,gh(R)));const Y=uc(R);L||F!=null&&F.includes("class")||0>=Y.length||(W.classes=Y.filter(function(Q){return Q!==""})),Pt(R.attributes,function(Q){var V;if((!id(R)||["name","id","class","aria-label"].indexOf(Q.name)!==-1)&&!(F!=null&&F.includes(Q.name))&&!L&&$u(Q.value)&&(!rt(V=Q.name)||V.substring(0,10)!=="_ngcontent"&&V.substring(0,7)!=="_nghost")){let D=Q.value;Q.name==="class"&&(D=Yx(D).join(" ")),W["attr__"+Q.name]=Vy(1024,Q.name==="href"&&N?Ya(D):D)}});let H=1,J=1,B=R;for(;B=kV(B);)H++,B.tagName===R.tagName&&J++;return W.nth_child=H,W.nth_of_type=J,W})(M,n,r,s,o)),Pt((function(R){if(!Wa(R))return{};const L={};return Pt(R.attributes,function(j){if(j.name&&j.name.indexOf("data-ph-capture-attribute")===0){const F=j.name.replace("data-ph-capture-attribute-",""),N=j.value;F&&N&&$u(N)&&(L[F]=N)}}),L})(M),(R,L)=>{({}).hasOwnProperty.call(w,L)||(w[L]=R)})}),b)return{props:{},explicitNoCapture:b};if(m>0&&(t=d[m],v.splice(0,m)),r||(v[0].$el_text=Nn(t,"a")||Nn(t,"button")?g8(t):gh(t)),x){var k,C;v[0].attr__href=x;const M=(k=qo(x))===null||k===void 0?void 0:k.host,I=(C=L2())===null||C===void 0||(C=C.location)===null||C===void 0?void 0:C.host;M&&I&&M!==I&&(_=x)}return{props:en((T=e.type,{$event_type:T,$ce_version:1}),i?{}:{$elements:v},{$elements_chain:(P=v,ze(P)?(function(M){return M.map(I=>{var R,L;let j="";if(I.tag_name&&(j+=I.tag_name),I.attr_class){I.attr_class.sort();for(const q of I.attr_class)j+=`.${q.replace(/"/g,"")}`}const F=$($($($({},I.text?{text:I.text}:{}),{},{"nth-child":(R=I.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(L=I.nth_of_type)!==null&&L!==void 0?L:0},I.href?{href:I.href}:{}),I.attr_id?{attr_id:I.attr_id}:{}),I.attributes),N={};return am(F).sort(([q],[W])=>(function(Y,H){return H>Y?-1:Y>H?1:0})(q,W)).forEach(([q,W])=>N[v8(q.toString())]=v8(W.toString())),j+=":",j+=am(N).map(([q,W])=>`${q}="${W}"`).join(""),j}).join(";")})((function(M){return M.map(I=>{var R,L;const j={text:(R=I.$el_text)===null||R===void 0?void 0:R.slice(0,400),tag_name:I.tag_name,href:(L=I.attr__href)===null||L===void 0?void 0:L.slice(0,2048),attr_class:VF(I),attr_id:I.attr__id,nth_child:I.nth_child,nth_of_type:I.nth_of_type,attributes:{}};return am(I).filter(([F])=>F.indexOf("attr__")===0).forEach(([F,N])=>j.attributes[F]=N),j})})(P)):"")},!((l=v[0])===null||l===void 0)&&l.$el_text?{$el_text:(u=v[0])===null||u===void 0?void 0:u.$el_text}:{},_&&e.type==="click"?{$external_click_url:_}:{},w),target:t};var P,T}const MR="autocapture";var CV=class{el(){this.il=void 0,clearTimeout(this.nl),this.nl=void 0}sl(t){var e;if(!Wa(t))return!0;const n=(e=this.rl().css_selector_ignorelist)!==null&&e!==void 0?e:w0,r=new Set;let s=t;for(;s;){if(r.size>=1e3||r.has(s))return!0;r.add(s);const i=s,o=uc(i);if(je(o,"ph-no-capture")||je(o,"ph-sensitive")||id(i)||n.some(u=>Df(i,u)))return!0;const l=s.parentNode;s=Zm(l)?l.host:l&&ei(l)?l:null}return!1}ol(t){if(!this.isEnabled||t.type==="pointercancel")return void this.el();if(t.type==="pointerdown"){var e;this.el();const r=Xf(t);return void(t.isPrimary&&t.button===0&&!t.ctrlKey&&r&&ei(r)&&(this.il={target:r,excluded:this.sl(r),id:t.pointerId,x:t.clientX,y:t.clientY,released:!1,distinctId:(e=this.xa)===null||e===void 0?void 0:e.distinctId}))}const n=this.il;n&&(t.pointerId!==n.id||Math.abs(t.clientX-n.x)>5||Math.abs(t.clientY-n.y)>5?this.el():t.type==="pointerup"&&(n.released=!0,this.nl=setTimeout(()=>this.el(),0)))}al(t){var e;const n=this.il;this.el();const r=Xf(t);if(n!=null&&n.released&&n.target.isConnected&&n.distinctId===((e=this.xa)===null||e===void 0?void 0:e.distinctId)&&t.pointerId===n.id&&(t.detail>0||t.pointerType==="touch"||t.pointerType==="pen")&&t.button===0&&5>=Math.abs(t.clientX-n.x)&&5>=Math.abs(t.clientY-n.y)&&r&&(Nn(r,"html")||Nn(r,"body"))){var s,i,o;if(n.excluded)return null;const l=(s=this.rl().css_selector_ignorelist)!==null&&s!==void 0?s:w0;return[r,(i=Ef())===null||i===void 0?void 0:i.documentElement,(o=Ef())===null||o===void 0?void 0:o.body].some(u=>{if(!u)return!1;const d=uc(u);return je(d,"ph-no-capture")||je(d,"ph-sensitive")||!Wa(u)||id(u)||l.some(f=>Df(u,f))})?null:n.target}}constructor(t){this.Ta=t,this.name=MR,this.ll=!1,this.ul=null,this.cl=!1,this.hl=new Map,this.dl=!1,this.Ar={enabled:!1,rageclick:!1,maskAllElementAttributes:!1,maskAllText:!1,disableCaptureUrlHashes:!1,remoteRequestsDisabled:!1},this.Ci=!1,this.Ta.refresh(this.Ar),this.rageclicks=new IR(this.Ar.rageclick),this.vl=null}setup(t){this.fl(),this.xa=t;const e=t.onRemoteConfig(this.onRemoteConfig.bind(this));this.Ci?e.dispose():(this.qa=e,this.startIfEnabled())}dispose(){var t;this.Ci||(this.Ci=!0,this.xa=void 0,(t=this.qa)===null||t===void 0||t.dispose(),this.qa=void 0,this.hl.clear(),this.vl=null,this.pl())}rl(){return this.Ta.refresh(this.Ar),this.Ar}fl(){var t,e;return this.rl(),this.Ar.url_allowlist=(t=this.Ar.url_allowlist)===null||t===void 0?void 0:t.map(n=>new RegExp(n)),this.Ar.url_ignorelist=(e=this.Ar.url_ignorelist)===null||e===void 0?void 0:e.map(n=>new RegExp(n)),this.Ar}gl(){const t=L2(),e=Ef();if(!this.isBrowserSupported())return void C0.info("Disabling Automatic Event Collection because this browser is not supported");if(!t||!e)return;this.ml=t,this.yl=e;const n=this.bl=r=>{r=r||(t==null?void 0:t.event);try{if(r.type==="blur")return void this.el();if(r.type.indexOf("pointer")===0)return void this.ol(r);const s=r.type==="click"?this.al(r):void 0;if(dn(s))return;this._l(r,"$autocapture",s)}catch(s){C0.error("Failed to capture event",s)}};if(_t(t,"blur",n),_t(e,"submit",n,{capture:!0}),_t(e,"change",n,{capture:!0}),_t(e,"click",n,{capture:!0}),Pt(["pointerdown","pointermove","pointerup","pointercancel"],r=>{_t(e,r,n,{capture:!0})}),this.rl().capture_copied_text){const r=this.wl=s=>{s=s||(t==null?void 0:t.event);try{this._l(s,Fy)}catch(i){C0.error("Failed to capture clipboard event",i)}};_t(e,"copy",r,{capture:!0}),_t(e,"cut",r,{capture:!0}),_t(e,"paste",r,{capture:!0})}}pl(){const t=this.ml,e=this.yl;this.el(),this.bl&&(t==null||t.removeEventListener("blur",this.bl),Pt(["pointerdown","pointermove","pointerup","pointercancel"],n=>{e==null||e.removeEventListener(n,this.bl,!0)}),e==null||e.removeEventListener("submit",this.bl,!0),e==null||e.removeEventListener("change",this.bl,!0),e==null||e.removeEventListener("click",this.bl,!0),this.bl=void 0),this.wl&&(e==null||e.removeEventListener("copy",this.wl,!0),e==null||e.removeEventListener("cut",this.wl,!0),e==null||e.removeEventListener("paste",this.wl,!0),this.wl=void 0),this.ml=void 0,this.yl=void 0,this.ll=!1}startIfEnabled(){this.isEnabled||this.el(),!this.Ci&&this.xa&&this.isEnabled&&!this.ll&&(this.gl(),this.ll=!0)}onRemoteConfig(t){if(this.Ci)return;if(this.cl=!0,!t.ok)return void this.startIfEnabled();const e=t.config;e.elementsChainAsString&&(this.dl=e.elementsChainAsString);const n=e.autocapture_opt_out;var r;Hr(n)&&((r=this.xa)===null||r===void 0||r.kv.set("$autocapture_disabled_server_side",n),this.ul=n),this.startIfEnabled()}setElementSelectors(t,e=this){if(this.Ci)return;t.size?this.hl.set(e,new Set(t)):this.hl.delete(e);const n=new Set;this.hl.forEach(r=>{r.forEach(s=>n.add(s))}),this.vl=n}getElementSelectors(t,e){var n;const r=[];return(n=this.vl)===null||n===void 0||n.forEach(s=>{var i;const o=(i=Ef())===null||i===void 0?void 0:i.querySelectorAll(s);o==null||o.forEach(l=>{t!==l&&e!==l||je(r,s)||r.push(s)})}),r}get isEnabled(){var t,e;if(this.Ci)return!1;const n=(t=this.xa)===null||t===void 0?void 0:t.kv.get(yT),r=this.ul,s=this.rl();if(!s.remoteRequestsDisabled&&!this.cl)return!1;const i=s.remoteRequestsDisabled&&!this.cl;if(dn(r)&&!Hr(n)&&!i)return!1;const o=(e=this.ul)!==null&&e!==void 0?e:!!n;return!!s.enabled&&!o}_l(t,e="$autocapture",n){if(!this.isEnabled)return void this.el();let r=n||Xf(t);HT(r)&&(r=r.parentNode||null);const s=this.fl();var i;e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&s.rageclick&&(!((i=this.rageclicks)===null||i===void 0)&&i.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime()))&&WT(r,s.rageclick)&&this._l(t,"$rageclick",n);const o=e===Fy,l=o?$($({},s),{},{dom_event_allowlist:void 0}):s;if(r&&(function(m,v,w,_,x,b){var k;const C=typeof window>"u"?void 0:window;if(!C||Jx(m)||w!=null&&w.url_allowlist&&!l8(w.url_allowlist,b)||w!=null&&w.url_ignorelist&&l8(w.url_ignorelist,b))return!1;if(w!=null&&w.dom_event_allowlist){const I=w.dom_event_allowlist;if(I&&!I.some(R=>v.type===R))return!1}const{parentIsUsefulElement:P,targetElementList:T}=ZT(m,_);if(!(function(I,R){const L=R==null?void 0:R.element_allowlist;if(ae(L))return!0;for(const j of I)if(L.some(F=>j.tagName.toLowerCase()===F))return!0;return!1})(T,w)||!P2(T,w==null?void 0:w.css_selector_allowlist)||P2(T,(k=w==null?void 0:w.css_selector_ignorelist)!==null&&k!==void 0?k:w0))return!1;try{const I=C.getComputedStyle(m);if(I&&I.getPropertyValue("cursor")==="pointer"&&v.type==="click")return!0}catch{}const M=m.tagName.toLowerCase();switch(M){case"html":return!1;case"form":return(x||["submit"]).indexOf(v.type)>=0;case"input":case"select":case"textarea":return(x||["change","click"]).indexOf(v.type)>=0;default:return P?(x||["click"]).indexOf(v.type)>=0:(x||["click"]).indexOf(v.type)>=0&&(Xx.indexOf(M)>-1||m.getAttribute("contenteditable")==="true")}})(r,t,l,o,o?["copy","cut","paste"]:void 0,{config:{get_current_url:s.getCurrentUrl}})){var u;const{props:m,explicitNoCapture:v,target:w}=EV(r,{e:t,maskAllElementAttributes:s.maskAllElementAttributes,maskAllText:s.maskAllText,elementAttributeIgnoreList:s.element_attribute_ignorelist,elementsChainAsString:this.dl,disableCaptureUrlHashes:s.disableCaptureUrlHashes});if(v)return!1;const _=this.getElementSelectors(r,w);if(_&&_.length>0&&(m.$element_selectors=_),e===Fy){const x=t.type||"clipboard";if(x!=="paste"){var d,f;const b=(d=L2())===null||d===void 0||(d=d.getSelection())===null||d===void 0?void 0:d.toString(),k=zT(b);if(!k)return!1;m.$selected_content=k,m.$clipboard_text_length=(f=b==null?void 0:b.length)!==null&&f!==void 0?f:0}m.$copy_type=x}if(e==="$autocapture"&&t.type==="change"&&s.capture_value_css_selector_allowlist&&!s.maskAllText&&(Nn(h=r,"input")?!je(SV,h.type):Nn(h,"textarea")||Nn(h,"select")&&!h.multiple)&&(function(x,b){var k;if(!Wa(x))return!1;const C=(k=b.css_selector_ignorelist)!==null&&k!==void 0?k:w0,P=new Set;let T=x;for(Nn(x,"select")&&(T=x.options[x.selectedIndex]||x);T;){const M=T,I=uc(M);if(P.size>=1e3||P.has(T)||je(I,"ph-sensitive")||je(I,"ph-no-capture")||C.some(L=>Df(M,L)))return!1;P.add(T);const R=T.assignedSlot||T.parentNode;T=Zm(R)?R.host:R&&ei(R)?R:null}return!0})(r,s)&&!r.querySelector(".ph-no-capture, .ph-sensitive")){const x=s.capture_value_css_selector_allowlist;let b=!1;try{b=gn(x)?!!x(r):ze(x)&&x.some(k=>Df(r,k))}catch(k){C0.error("capture_value_css_selector_allowlist threw",k)}b&&(m.$input_value=r.value)}return(u=this.xa)===null||u===void 0||u.capture(e,m),!0}var h}isBrowserSupported(){var t;return gn((t=Ef())===null||t===void 0?void 0:t.querySelectorAll)}};const OR="featureFlags",LR="logs";var PV=class{constructor(t){this._instance=t}initialize(){}get(t){const e=this._instance.persistence;if(typeof t=="string")return e==null?void 0:e.get_property(t);const n={};for(const r of t){const s=e==null?void 0:e.get_property(r);ae(s)||(n[r]=s)}return n}set(t,e){var n;(n=this._instance.persistence)===null||n===void 0||n.register(typeof t=="string"?{[t]:e}:t)}remove(t){var e;(e=this._instance.persistence)===null||e===void 0||e.unregister(t)}},AV=class{constructor(t){this.instance=t,this.$=he,this.kv=new PV(t),this.onSession=e=>k0(this.instance.onSessionId(n=>{try{e(n)}catch(r){this.$.error("Browser extension session listener failed",r)}})),this.onEvent=e=>k0(this.instance._addCaptureHook((n,r)=>{if(r)try{e({event:n,properties:r.properties})}catch(s){this.$.error("Browser extension event listener failed",s)}})),this.onRemoteConfig=e=>{const n=s=>{try{e(s)}catch(i){this.$.error("Browser extension remote config listener failed",i)}},r=this.instance.ur.on("extensionsRemoteConfig",n);return this.instance.cr&&n(this.instance.cr),k0(r)}}get logger(){return this.$}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var t;return(t=this.instance.get_property("$device_id"))!==null&&t!==void 0?t:this.distinctId}get deviceId(){const t=this.instance.get_property(zx);return typeof t=="string"?t:void 0}get library(){return{name:Jr.LIB_NAME,version:Jr.LIB_VERSION}}get initialPersonProperties(){var t,e;return(t=(e=this.instance.persistence)===null||e===void 0?void 0:e.get_initial_props())!==null&&t!==void 0?t:{}}get groups(){return this.instance.getGroups()}get session(){try{var t,e,n,r,s;const i=(t=this.instance.sessionManager)===null||t===void 0?void 0:t.checkAndGetSessionAndWindowId(!0);return{sessionId:(e=i==null?void 0:i.sessionId)!==null&&e!==void 0?e:"",windowId:(n=i==null?void 0:i.windowId)!==null&&n!==void 0?n:"",sessionStartTimestamp:(r=i==null?void 0:i.sessionStartTimestamp)!==null&&r!==void 0?r:0,lastActivityTimestamp:(s=i==null?void 0:i.lastActivityTimestamp)!==null&&s!==void 0?s:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0,lastActivityTimestamp:0}}}get isOptedOut(){return this.instance.has_opted_out_capturing()}get canCapture(){return gn(this.instance.is_capturing)?this.instance.is_capturing():!this.isOptedOut}get projectToken(){return this.instance.config.token}getExtension(t){let e;switch(t){case OR:case"featureFlagsCommon":e=this.instance.featureFlags;break;case LR:e=this.instance.logs;break;case"surveys":e=this.instance.surveys;break;case MR:e=this.instance.autocapture}return e}capture(t,e,n){if(!n)return void this.instance.capture(t,e);const r=$({timestamp:n.timestamp,uuid:n.uuid,$set:n.set,$set_once:n.setOnce},n.delivery==="unload"?{transport:"sendBeacon",send_instantly:!0}:{});this.instance.capture(t,e,r)}registerDynamicEventProperties(t){return k0(this.instance.dr(t))}sendRequest(t){var e=this;return Wt(function*(n,r={}){var s;const i=(s=r.target)!==null&&s!==void 0?s:"api",o=r.query?Zg(n,r.query):n,l=e.instance.requestRouter.endpointFor(i,o),u={method:r.method,url:l,data:r.body,headers:r.headers,timeout:r.timeoutMs,fireCallbackOnDrop:!0,transport:r.transport,compression:r.compression,compressionFallback:r.target==="flags"&&r.compression==="best-available"?s2.Base64:void 0,timestampMode:r.sentAt};return i==="api"&&n==="/i/v1/logs"&&(u.batchKey="logs"),r.transport==="sendBeacon"?(e.instance._send_request(u),{statusCode:202}):new Promise(d=>{u.callback=d,e.instance._send_request(u)})}).apply(this,arguments)}};const Jf={};let Hy=0;const eh=()=>{},N8='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',pu="Surveys module not available",D8="sanitize_properties is deprecated. Use before_send instead",NR="Invalid value for property_denylist config: ",TV=["$recording_status","$sdk_debug_recording_script_not_loaded","$sdk_debug_replay_url_trigger_status","$sdk_debug_replay_event_trigger_status","$sdk_debug_replay_linked_flag_trigger_status","$sdk_debug_replay_rrweb_error","$sdk_debug_replay_internal_buffer_length","$sdk_debug_replay_flushed_size"],RV=["$feature_flag_called","$$heatmap","$snapshot"],j8=t=>t.charAt(0)==="$"&&!je(RV,t),IV=/^[A-Za-z0-9_-]{1,400}$/,$8=/^fb\.[0-9]+\.[0-9]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/,F8=/^fb\.[0-9]+\.[0-9]+\.[0-9]+$/,MV=["token","distinct_id",CT],jf="posthog",OV=[...O8].sort()[O8.length-1],LV=t=>{const e={};return t&&t!=="unset"&&("2025-11-30">t||(e.strictMinimumDuration=!0),"2026-05-30">t||(e.canvasCapture={resolutionScale:.6}),"2026-06-25">t||(e.streamNetworkBody=!0),"2026-08-30">t||(e.captureJsonLd=!0)),e},zy=t=>{var e;return $({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:EF(ke==null?void 0:ke.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:eh,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,__preview_replay_sync_fetch:!0,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:Ut&&rt(Ut==null?void 0:Ut.search)&&Ut.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,reuseAnonymousId:!1,disable_external_dependency_loading:!1,strict_script_versioning:"fallback",enable_recording_console_log:void 0,secure_cookie:(oe==null||(e=oe.location)===null||e===void 0?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_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,feature_flag_request_max_retries:1,surveys_request_timeout_ms:1e4,on_request_error(n){he.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:DT,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:3e3},error_tracking:{},_onCapture:eh},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Qx,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:LV(n),external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n),cookieWinsOnConflict:!(!n||n==="unset"||"2026-08-29">n)}))(t))},NV=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["__preview_disable_beacon","disable_beacon"],["store_google","save_campaign_params"],["verbose","debug"],["__preview_cookie_wins_on_conflict","cookieWinsOnConflict"]],V8=t=>{const e={};for(const[s,i]of NV)ae(t[s])||(e[i]=t[s]);const n=en({},e,t),r=t.__preview_external_dependency_versioned_paths;return ae(r)||(ae(t.strict_script_versioning)&&(n.strict_script_versioning=!!r),rt(r)&&ae(t.asset_host)&&(n.asset_host=r)),ze(t.property_blacklist)&&(ae(t.property_denylist)?n.property_denylist=t.property_blacklist:ze(t.property_denylist)?n.property_denylist=[...t.property_blacklist,...t.property_denylist]:he.error(NR+t.property_denylist)),n};var DV=class{constructor(){this.__forceAllowLocalhost=!1}get Yc(){return this.__forceAllowLocalhost}set Yc(t){he.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=t}},th=class Ea{th(e){if(!e)return;const n=this.eh.indexOf(e);n!==-1&&this.eh.splice(n,1)}ih(e,n){var r;return this.th(e),this.eh.push(n),(r=n.initialize)===null||r===void 0||r.call(n),n}nh(){return this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isRejected()}sh(){if(this.rh||this.config.reuseAnonymousId||this.config.segment||this.nh())return;const e=this.config.persistence==="memory"||this.config.persistence==="sessionStorage";if(!e&&!this.config.disable_persistence||this.oh)return;let n,r,s;e?(n=`persistence is set to '${this.config.persistence}'`,r=this.config.persistence==="memory"?"on every page load":"for every new browser tab or window",s="Either set persistence to 'localStorage+cookie', keep this persistence and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."):(n="persistence is disabled (disable_persistence is true)",r="on every page load",s="Either set disable_persistence to false, keep persistence disabled and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."),this.rh=!0,console.warn("[PostHog.js]",`${n} but no bootstrap.distinctID was provided. PostHog will mint a new distinct ID ${r}, so calling identify() merges a new ID onto the person each time. A person can then pass the distinct-ID limit and its events stop appearing on person pages and the session tab. ${s}`)}ah(){const e=this.persistence;if(!e||this.uh)return;if(this.nh())return void(this.config.cookieless_mode==="on_reject"&&this.get_distinct_id()!=="$posthog_cookieless"&&(this.hh(),this.dh()));if(this.get_distinct_id()!=="$posthog_cookieless")return;this.fh()||e.load(!0);const n=this.get_distinct_id();if(!n||n==="$posthog_cookieless"){const r=this.config.get_device_id(xi());this.register({distinct_id:r,$device_id:r}),e.set_property(Cr,Fo)}this.hh()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)===null||n===void 0?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)===null||n===void 0?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.ph=!1,this.gh=!1,this.webPerformance=new DV,this.mh=!1,this.version=Jr.LIB_VERSION,this.yh=new Set,this.bh="",this.ur=new Ym,this.eh=[],this._h=[],this.wh=!1,this.oh=!1,this.rh=!1,this.uh=!1,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=zy(),this.SentryIntegration=UF,this.sentryIntegration=r=>(function(s,i){const o=KT(s,i);return{name:GT,processEvent:l=>o(l)}})(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.kh=!1,this.Sh=null,this.xh=null,this.$h=null,this.scrollManager=new fV(this),this.pageViewManager=new w8(this),this.rateLimiter=new JF(this),this.requestRouter=new vV(this),this.consent=new MF(this),this.externalIntegrations=new bV(this);const n=(e=Ea.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(r,s,i)=>{const o=rt(r)?{[r]:s}:r;this.setPersonProperties(o),i==null||i({})},set_once:(r,s,i)=>{const o=rt(r)?{[r]:s}:r;this.setPersonProperties(void 0,o),i==null||i({})}},this.on("eventCaptured",r=>he.info(`send "${r==null?void 0:r.event}"`,r))}init(e,n,r){if(r&&r!==jf){var s;const i=(s=Jf[r])!==null&&s!==void 0?s:new Ea;return i._init(e,n,r),Jf[r]=i,Jf[jf][r]=i,i}return this._init(e,n,r)}_init(e,n={},r){var s,i,o;const l=rt(e)?e.trim():"";if(!l)return he.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;var u;if(this.__loaded)return l!==((u=this.config)===null||u===void 0?void 0:u.token)?console.warn("[PostHog.js]",`You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('${l}', { ... }, 'project2')`):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=zy(n.defaults),n.debug=this.Ch(n.debug),this.Th=n,this.Ih=[],n.person_profiles?this.xh=n.person_profiles:n.process_person&&(this.xh=n.process_person);const d=zy(n.defaults),f=V8(n),h=en({},d,f,{name:r,token:l});nt(d.rageclick)&&nt(f.rageclick)&&(h.rageclick=en({},d.rageclick,f.rageclick)),nt(d.session_recording)&&nt(f.session_recording)&&(h.session_recording=en({},d.session_recording,f.session_recording)),this.set_config(h),this.config.on_xhr_error&&he.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ss.GZipJS;const m=this.fh(),v=!this.nh();if(this.persistence=new Iy(this.config,m,!0,v),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Iy($($({},this.config),{},{persistence:"sessionStorage"}),m,!1,v),this.bh="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!m&&Bt.Et()){const k=Bt.Lt(this.bh);ze(k)&&k.forEach(C=>{rt(C)&&this.yh.add(C)})}else Bt.Pt(this.bh);const w=$({},this.persistence.props),_=$({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Mh=new cV((k,C)=>this.Eh(k,C),this.config.request_queue_config),this.Ph=new dV(this),this.__request_queue=[];const x=this.nh();x||(this.sessionManager=new M8(this),this.sessionPropsManager=new R8(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId((k,C,P)=>{(P!=null&&P.activityTimeout||P!=null&&P.sessionPastMaximumLength||P!=null&&P.crossTabAdoption)&&this.Rh()})),this.Ah(),this.config.__preview_deferred_init_extensions?(he.info("Deferring extension initialization to improve startup performance"),this.Fh=setTimeout(()=>{this.Fh=void 0,this.Oh(x)},0)):(he.info("Initializing extensions synchronously"),this.Oh(x)),Jr.DEBUG=Jr.DEBUG||this.config.debug,Jr.DEBUG&&he.info("Starting in debug mode",{this:this,config:n,thisC:$({},this.config),p:w,s:_}),this.config.identity_distinct_id&&!(!((s=n.bootstrap)===null||s===void 0)&&s.distinctID)&&(n.bootstrap=$($({},n.bootstrap),{},{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0}));const b=(i=n.bootstrap)===null||i===void 0?void 0:i.distinctID;if(this.oh=!!b&&!Bf(b),(o=n.bootstrap)===null||o===void 0?void 0:o.distinctID){const k=n.bootstrap.distinctID,C=this.get_distinct_id(),P=this.persistence.get_property(Cr);if(n.bootstrap.isIdentifiedID&&C!=null&&C!==k&&P==="anonymous")this.identify(k);else if(n.bootstrap.isIdentifiedID&&C!=null&&C!==k&&P==="identified")he.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{const T=this.config.get_device_id(xi()),M=n.bootstrap.isIdentifiedID?T:k;this.persistence.set_property(Cr,n.bootstrap.isIdentifiedID?om:Fo),this.register({distinct_id:k,$device_id:M})}}if(x)this.register_once({distinct_id:Sy,$device_id:null},"");else if(!this.get_distinct_id()){const k=this.config.get_device_id(xi());this.register_once({distinct_id:k,$device_id:k},""),this.persistence.set_property(Cr,Fo)}return _t(oe,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),_t(oe,"pageshow",k=>{if(this.ph=!1,!this.gh){var C;if(k.persisted&&this.persistence){const P=this.persistence.get_property(qs),T=this.persistence.get_property(Cr);this.persistence.load(),this.Dh()||P===this.persistence.get_property("distinct_id")&&T===this.persistence.get_property("$user_state")||this.Lh()}(C=this.Ph)===null||C===void 0||C.resume()}}),n.segment?_8(this,()=>this.Nh()):this.Nh(),gn(this.config._onCapture)&&this.config._onCapture!==eh&&(he.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",k=>this.config._onCapture(k.event,k))),this.config.ip&&he.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.config.disableDeviceModel||(function(){return CR.apply(this,arguments)})().then(k=>{k&&this.register({[by]:k})}).catch(eh),this}qh(e){const n=e;return rt(n.name)&&gn(n.setup)}jh(e,n){var r=this;this.qh(e)?n.push(Wt(function*(){try{yield e.setup(r.Bh())}catch(i){he.error(`Failed to set up extension "${e.name}"`,i);try{var s;yield(s=e.dispose)===null||s===void 0?void 0:s.call(e)}catch(o){he.error(`Failed to dispose extension "${e.name}"`,o)}}})):this.eh.push(e)}Ah(){var e,n,r,s=this;const i=(e=(n=this.config.__extensionClasses)===null||n===void 0?void 0:n.featureFlags)!==null&&e!==void 0?e:(r=Ea.__defaultExtensionClasses)===null||r===void 0?void 0:r.featureFlags;var o,l,u;if(i)if(this.featureFlags&&this.featureFlags instanceof i||((o=this.zh)===null||o===void 0||o.call(this),this.zh=void 0,this.featureFlags=new i(this)),gn(this.featureFlags.onReloading)&&gn(this.featureFlags.setup)){if(!this.zh){this.zh=this.featureFlags.onReloading(()=>{this.ur.emit("featureFlagsReloading",!0)});const d=this.featureFlags;Wt(function*(){try{yield d.setup(s.Bh())}catch(f){he.error("Failed to set up feature flags",f);const h=s.zh;s.zh=void 0;try{h==null||h()}catch(m){he.error("Failed to unsubscribe feature flag reloading",m)}try{yield d.dispose()}catch(m){he.error("Failed to dispose feature flags",m)}}})()}}else(l=(u=this.featureFlags).initialize)===null||l===void 0||l.call(u)}Oh(e){const n=performance.now(),r=$($({},Ea.__defaultExtensionClasses),this.config.__extensionClasses),s=[];var i,o,l,u,d,f,h,m;r.exceptions&&this.eh.push(this.exceptions=(i=this.exceptions)!==null&&i!==void 0?i:new r.exceptions(this)),r.historyAutocapture&&this.eh.push(this.historyAutocapture=new r.historyAutocapture(this)),r.tracingHeaders&&this.eh.push(this.tracingHeaders=new r.tracingHeaders(this)),r.siteApps&&this.eh.push(this.siteApps=new r.siteApps(this)),r.sessionRecording&&!e&&this.eh.push(this.sessionRecording=new r.sessionRecording(this)),this.config.disable_scroll_properties||s.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),r.autocapture&&this.jh(this.autocapture=new r.autocapture(this),s),r.surveys&&this.jh(this.surveys=(o=this.surveys)!==null&&o!==void 0?o:new r.surveys(this),s),r.logs&&this.jh(this.logs=(l=this.logs)!==null&&l!==void 0?l:new r.logs(this),s),r.metrics&&this.eh.push(this.metrics=(u=this.metrics)!==null&&u!==void 0?u:new r.metrics(this)),r.conversations&&this.eh.push(this.conversations=(d=this.conversations)!==null&&d!==void 0?d:new r.conversations(this)),r.productTours&&this.eh.push(this.productTours=new r.productTours(this)),r.heatmaps&&this.eh.push(this.heatmaps=new r.heatmaps(this)),r.webVitalsAutocapture&&this.eh.push(this.webVitalsAutocapture=new r.webVitalsAutocapture(this)),r.exceptionObserver&&this.eh.push(this.exceptionObserver=new r.exceptionObserver(this)),r.deadClicksAutocapture&&this.eh.push(this.deadClicksAutocapture=new r.deadClicksAutocapture(this,zF)),r.toolbar&&this.eh.push(this.toolbar=(f=this.toolbar)!==null&&f!==void 0?f:new r.toolbar(this)),r.experiments&&this.eh.push(this.experiments=(h=this.experiments)!==null&&h!==void 0?h:new r.experiments(this)),r.webMCP&&this.eh.push(this.webMCP=(m=this.webMCP)!==null&&m!==void 0?m:new r.webMCP(this)),this.eh.forEach(v=>{v.initialize&&s.push(()=>{var w;(w=v.initialize)===null||w===void 0||w.call(v)})}),s.push(()=>{if(this.Hh){const v=this.Hh;this.Hh=void 0,this.eh.forEach(w=>{var _;return(_=w.onRemoteConfig)===null||_===void 0?void 0:_.call(w,v)})}}),this.Uh(s,n)}Uh(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void(this.Fh=setTimeout(()=>{this.Fh=void 0,this.Uh(e,n)},0));const s=e.shift();if(s)try{s()}catch(i){he.error("Error initializing extension:",i)}}const r=Math.round(performance.now()-n);this.register_for_session({[PT]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[AT]:r}),this.config.__preview_deferred_init_extensions&&he.info(`PostHog extensions initialized (${r}ms)`)}Gu(e){if(!ke||!ke.body)return he.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.Gu(e)},500);if(this.config.__preview_deferred_init_extensions&&(this.Hh=e),this.cr=e,this.compression=void 0,e.ok){var n;const r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=je(r.supportedCompression,Ss.GZipJS)?Ss.GZipJS:je(r.supportedCompression,Ss.Base64)?Ss.Base64:void 0),!((n=r.analytics)===null||n===void 0)&&n.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xh?this.xh:DT}),this.ur.emit("extensionsRemoteConfig",e),this.eh.forEach(r=>{var s;return(s=r.onRemoteConfig)===null||s===void 0?void 0:s.call(r,e)})}Nh(){try{this.config.loaded(this)}catch(e){he.critical("`loaded` function failed",e)}if(this.Wh(),this.config.internal_or_test_user_hostname&&(Ut==null?void 0:Ut.hostname)){const e=Ut.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.nh())&&this.Vh()},1),this.Gh=new lR(this),this.Gh.load()}Wh(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.Mh)===null||e===void 0||e.enable())}_dom_loaded(){this.is_capturing()&&Au(this.__request_queue,e=>this.Eh(e)),this.__request_queue=[],this.Wh()}_handle_unload(){var e,n,r,s,i,o;this.ph=!0,(e=this.surveys)===null||e===void 0||(n=e.handlePageUnload)===null||n===void 0||n.call(e),(r=this.metrics)===null||r===void 0||r.flush("sendBeacon"),this.config.request_batching?(this.Qh()&&this.capture(e8),(s=this.logs)===null||s===void 0||s.flushLogs("sendBeacon"),(i=this.Mh)===null||i===void 0||i.unload(),(o=this.Ph)===null||o===void 0||o.unload()):this.Qh()&&this.capture(e8,null,{transport:"sendBeacon"})}_send_request(e){kR(this,e)}Eh(e,n){this.Ph?this.Ph.retriableRequest(e,n):this._send_request(n?$($({},e),{},{transport:n}):e)}_execute_array(e){Hy++;try{let n;const r=[],s=[],i=[];Au(e,l=>{if(l)if(n=l[0],ze(n))i.push(l);else if(gn(l))try{l.call(this)}catch(u){he.error("Error executing queued PostHog call",l,u)}else ze(l)&&n==="alias"?r.push(l):ze(l)&&n.indexOf("capture")!==-1&&gn(this[n])?i.push(l):s.push(l)});const o=function(l,u){Au(l,function(d){try{if(ze(d[0])){let f=u;Pt(d,function(h){f=f[h[0]].apply(f,h.slice(1))})}else u[d[0]].apply(u,d.slice(1))}catch(f){he.error("Error executing queued PostHog call",d,f)}})};o(r,this),o(s,this),o(i,this)}finally{Hy--}}push(e){if(Hy>0&&ze(e)&&rt(e[0])){const n=Ea.prototype[e[0]];return void(gn(n)&&n.apply(this,e.slice(1)))}this._execute_array([e])}get Zh(){return{property:Qk,persistenceKey:ju,cookieName:"_fbc",pattern:$8,register:(e,n)=>{var r;return(r=this.persistence)===null||r===void 0?void 0:r.register({[ju]:{value:e,delivered:n}})},unregister:()=>{var e;return(e=this.persistence)===null||e===void 0?void 0:e.unregister(ju)}}}get Jh(){return{property:Jk,persistenceKey:qf,cookieName:"_fbp",pattern:F8,register:(e,n)=>{var r;return(r=this.persistence)===null||r===void 0?void 0:r.register({[qf]:{value:e,delivered:n}})},unregister:()=>{var e;return(e=this.persistence)===null||e===void 0?void 0:e.unregister(qf)}}}Kh(e){var n;const r=(n=this.persistence)===null||n===void 0?void 0:n.get_property(e.persistenceKey);return rt(r)&&e.pattern.test(r)?{value:r,delivered:!1}:nt(r)&&rt(r.value)&&e.pattern.test(r.value)?{value:r.value,delivered:r.delivered===!0}:void 0}Xh(e,n,r){return n===(r==null?void 0:r.value)?{value:n,pending:!r.delivered}:(e.register(n,!1),{value:n,pending:!0})}Yh(e){if(!this.config.save_campaign_params||this.nh())return;const n=Kf(e.cookieName);return rt(n)&&e.pattern.test(n)?n:void 0}td(e,n,r,s){if(!this.persistence)return;const i=this.Zh;this.persistence.refreshMetaIdentifiers();const o=this.Kh(i);if(s)return void i.unregister();if(r)return rt(n)&&$8.test(n)?this.Xh(i,n,o):void i.unregister();const l=rt(e)&&IV.test(e)?e:void 0,u=this.Yh(i);return u&&((d,f,h)=>{const m=d.split(".");if(f)return m[3]===f;if(!h)return!0;const v=h.value.split(".");return m[3]===v[3]||Number(m[2])>Number(v[2])})(u,l,o)?this.Xh(i,u,o):l?(o==null?void 0:o.value.split(".")[3])===l?{value:o.value,pending:!o.delivered}:this.Xh(i,`fb.1.${Date.now()}.${l}`,o):o?{value:o.value,pending:!o.delivered}:void 0}ed(e,n,r){if(!this.persistence)return;const s=this.Jh;this.persistence.refreshMetaIdentifiers();const i=this.Kh(s);if(r)return void s.unregister();if(n)return rt(e)&&F8.test(e)?this.Xh(s,e,i):void s.unregister();const o=this.Yh(s);return o?this.Xh(s,o,i):i?{value:i.value,pending:!i.delivered}:void 0}nd(e,n){if(!this.persistence)return;this.persistence.refreshMetaIdentifiers();const r=this.Kh(e);(r==null?void 0:r.value)!==n||r.delivered||e.register(n,!0)}capture(e,n,r){var s,i;if(!(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Mh))return void he.uninitializedWarning("posthog.capture");if(!this.is_capturing())return void he.info(`Event "${e}" was not captured because capturing is disabled (opted out or consent pending).`);if(ae(e)||!rt(e))return void he.error("No event name provided to posthog.capture");if(this.ah(),e==="$snapshot"&&this.nh())return;const o=!this.config.opt_out_useragent_filter&&this._is_bot();if(o&&!this.config.__preview_capture_bot_pageviews)return void he.info(`Event "${e}" was not captured because the user agent looks like a bot. Set \`opt_out_useragent_filter: true\` to capture it.`);const l=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(l!=null&&l.isRateLimited)return void he.critical("This capture call is ignored due to client rate limiting.");let u;n!=null&&n.$current_url&&!rt(n==null?void 0:n.$current_url)&&(he.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||r!=null&&r.sd||he.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&(u=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();const d=new Date,f=(r==null?void 0:r.timestamp)||d,h=Mk(r==null?void 0:r.uuid,xi);let m={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&o&&(m.event="$bot_pageview",m.properties.$browser_type="bot"),l&&(m.properties.$lib_rate_limit_remaining_tokens=l.remainingTokens);const v=e==="$feature_flag_called"&&m.properties.$feature_flag_has_experiment===!1&&this.get_property("$minimal_flag_called_events")===!0;r!=null&&r.$set&&!v&&(m.$set=r==null?void 0:r.$set);const w=nt(n==null?void 0:n.$set)?n.$set:void 0,_=ze(n==null?void 0:n.$unset)?n.$unset:[],x=(r==null?void 0:r.$unset)||[],b=W=>{var Y;const H=!!(r!=null&&r.$set)&&W in r.$set;return{hasProvided:H||!!w&&W in w,provided:H?r==null||(Y=r.$set)===null||Y===void 0?void 0:Y[W]:w==null?void 0:w[W],unset:_.indexOf(W)!==-1||x.indexOf(W)!==-1}},k=b(Qk),C=b(Jk),P=[{channel:this.Zh,hasProvided:k.hasProvided,update:this.td(u==null?void 0:u.fbclid,k.provided,k.hasProvided,k.unset)},{channel:this.Jh,hasProvided:C.hasProvided,update:this.ed(C.provided,C.hasProvided,C.unset)}];for(const{channel:W,hasProvided:Y,update:H}of P)H&&m.properties.$process_person_profile===!0&&H.pending&&!Y&&!v&&(m.$set=$({[W.property]:H.value},m.$set));const T=r==null?void 0:r.$unset;T&&(m.$unset=T);const M=v?void 0:this.rd(r==null?void 0:r.$set_once,e!==t8,e===jT);if(M&&(m.$set_once=M),r!=null&&r._noTruncate||(I=this.config.properties_string_max_length,m=(function(W,Y){const H=new Set;return(function J(B,Q){if(B!==Object(B))return Y?Y(B):B;if(H.has(B))return;let V;if(H.add(B),ze(B))V=[],Au(B,D=>{V.push(J(D))});else{const D={};Pt(Ed(B)?$T(B):B,(G,le)=>{H.has(G)||(D[le]=J(G))}),V=D}return V})(W)})(m,W=>rt(W)?W.slice(0,I):W)),m.timestamp=f,ae(r==null?void 0:r.timestamp)||(m.properties.$event_time_override_provided=!0,m.properties.$event_time_override_system_time=d),v&&(m.properties=((W,Y=[])=>{const H={},J=B=>{W[B]!==void 0&&(H[B]=W[B])};return g$.forEach(J),Y.forEach(J),H})(m.properties,MV)),e===bs.DISMISSED||e===bs.SENT){const W=n==null?void 0:n[Oy.SURVEY_ID],Y=n==null?void 0:n[Oy.SURVEY_ITERATION];RR({id:W,current_iteration:Y}),m.$set=$($({},m.$set),{},{[pV({id:W,current_iteration:Y},e===bs.SENT?"responded":"dismissed")]:!0})}else e===bs.SHOWN&&(m.$set=$($({},m.$set),{},{[Oy.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var I;if(e===QF.SHOWN){const W=n==null?void 0:n[S8.TOUR_TYPE];W&&(m.$set=$($({},m.$set),{},{[`${S8.TOUR_LAST_SEEN_DATE}/${W}`]:new Date().toISOString()}))}const R=$($({},m.properties.$set),m.$set);if(ts(R)||this.setPersonPropertiesForFlags(R),!Xe(this.config.before_send)){const W=this.Os(m);if(!W)return;m=W,m.uuid=Mk(m.uuid,xi)}this.sessionRecording&&!this.wh&&j8(e)&&(this.wh=!0,setTimeout(()=>this.wh=!1,3e4));const L=P.filter(({channel:W,update:Y})=>{var H,J,B;const Q=(H=(J=m.$set)===null||J===void 0?void 0:J[W.property])!==null&&H!==void 0?H:nt((B=m.properties)===null||B===void 0?void 0:B.$set)?m.properties.$set[W.property]:void 0;return(Y==null?void 0:Y.pending)&&Q===Y.value});this.ur.emit("eventCaptured",m);const j=(s=r==null?void 0:r._url)!==null&&s!==void 0?s:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),F=(r==null?void 0:r._batchKey)==="recordings"||/\/s\/(?:\?|$)/.test(j),N=$($($({method:"POST",url:j,data:m,compression:"best-available",preferSyncCompression:r==null?void 0:r.send_instantly,timestampMode:F?"body":"capture-body",batchKey:r==null?void 0:r._batchKey},F&&(!((i=m.properties)===null||i===void 0)&&i.$session_id)?{batchGroup:m.properties.$session_id+(m.properties.$window_id?`-${m.properties.$window_id}`:"")}:{}),r!=null&&r.transport?{transport:r.transport}:{}),L.length?{fireCallbackOnDrop:!0,callback:W=>{if(W.statusCode>=200&&300>W.statusCode)for(const{channel:Y,update:H}of L)this.nd(Y,H.value)}}:{});if(!this.config.request_batching||r&&!(r!=null&&r._batchKey)||r!=null&&r.send_instantly){var q;let W;!N.transport&&!N.callback&&ts((q=this.config.request_headers)!==null&&q!==void 0?q:{})&&this.ph&&(W="sendBeacon"),this.Eh(N,W)}else this.Mh.enqueue(N);return m}_addCaptureHook(e){return this.on("eventCaptured",n=>e(n.event,n))}getExtension(e){var n;return(n=this.od)===null||n===void 0?void 0:n.getExtension(e)}Bh(){var e;return(e=this.od)!==null&&e!==void 0?e:this.od=new AV(this)}dr(e){this._h.push(e);let n=!0;return()=>{if(!n)return;n=!1;const r=this._h.indexOf(e);r!==-1&&this._h.splice(r,1)}}Dh(e=!0){var n;return!!(!((n=this.persistence)===null||n===void 0)&&n.consumeCookieIdentityChange())&&(this.Lh(e),!0)}Lh(e=!0){var n,r,s;this.$h=null,((n=this.persistence)===null||n===void 0?void 0:n.get_property("$user_state"))==="anonymous"&&((s=this.sessionPersistence)===null||s===void 0||s.clear(),this.yh.clear(),this.ad()),(r=this.featureFlags)===null||r===void 0||r.reset(),e&&this.reloadFeatureFlags()}calculateEventProperties(e,n,r,s,i){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return n;this.ah(),this.persistence.syncCookieProperties(),this.Dh();const o=i?void 0:this.persistence.remove_event_timer(e);let l=$({},n);if(l.token=this.config.token,l.$config_defaults=this.config.defaults==="latest"?OV:this.config.defaults,this.nh()&&(l[CT]=!0),e==="$snapshot"){const k=$($({},this.persistence.properties()),this.sessionPersistence.properties());return l.distinct_id=k.distinct_id,(!rt(l.distinct_id)&&!Cn(l.distinct_id)||Bf(l.distinct_id))&&he.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),l}const u=(function(k,C,P,T=!1){var M,I,R,L;if(!Vr)return{};const j=k?[...ad,...C||[]]:[],[F,N]=B5(Vr),[q,W]=(function(re){for(let ie=0;Ik.length>ie;ie++){const[ue,fe,de]=Ik[ie],ne=re.match(ue);if(ne){const Ce=de&&re.match(de)||ne;return[fe,(Ce==null?void 0:Ce[1])||""]}}return["",""]})(Vr),Y=(function(){const re="u">typeof navigator?navigator:void 0;return re!=null&&re.brave?{brave:!0}:{}})(),H={};ae(P)||(H.detectGoogleSearchApp=P);const J={},B=(M=navigator)===null||M===void 0||(M=M.userAgentData)===null||M===void 0?void 0:M.platform,Q=(I=navigator)===null||I===void 0?void 0:I.maxTouchPoints,V=oe==null||(R=oe.screen)===null||R===void 0?void 0:R.width,D=oe==null||(L=oe.screen)===null||L===void 0?void 0:L.height,G=oe==null?void 0:oe.devicePixelRatio;ae(B)||(J.userAgentDataPlatform=B),ae(Q)||(J.maxTouchPoints=Q),ae(V)||(J.screenWidth=V),ae(D)||(J.screenHeight=D),ae(G)||(J.devicePixelRatio=G);const le=en(Kx({$os:F,$os_version:N,$browser:U5(Vr,navigator.vendor,Y,H),$webview_app:q,$webview_app_version:W,$device:W5(Vr),$device_type:$7(Vr,J),$timezone:YT(),$timezone_offset:KF()}),{$current_url:vh(T?Ya(Ut==null?void 0:Ut.href):Ut==null?void 0:Ut.href,j,yh),$host:Ut==null?void 0:Ut.host,$pathname:Ut==null?void 0:Ut.pathname,$raw_user_agent:Vr.length>1e3?Vr.substring(0,997)+"...":Vr,$browser_version:j7(Vr,navigator.vendor,Y,H),$browser_language:rR(),$browser_language_prefix:GF(),$screen_height:oe==null?void 0:oe.screen.height,$screen_width:oe==null?void 0:oe.screen.width,$viewport_height:oe==null?void 0:oe.innerHeight,$viewport_width:oe==null?void 0:oe.innerWidth,$lib:Ho.LIB_NAME,$lib_version:Ho.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Ho.SDK_DIST_CHANNEL&&(le.$sdk_dist_channel=Ho.SDK_DIST_CHANNEL),le})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){const{sessionId:k,windowId:C}=this.sessionManager.checkAndGetSessionAndWindowId(i,r.getTime(),!0);l.$session_id=k,l.$window_id=C}this.sessionPropsManager&&en(l,this.sessionPropsManager.getSessionProps());try{var d;if(this.sessionRecording){const k=this.sessionRecording.sdkDebugProperties,C=!this.wh&&j8(e);for(const P in k)(C||je(TV,P))&&(l[P]=k[P])}l.$sdk_debug_retry_queue_size=(d=this.Ph)===null||d===void 0?void 0:d.length}catch(k){l.$sdk_debug_error_capturing_properties=String(k)}let f;if(this.requestRouter.region===O2&&(l.$lib_custom_api_host=this.config.api_host),f=e!=="$pageview"||i?e!=="$pageleave"||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,s),l=en(l,f),e==="$pageview"&&ke&&(l.title=ke.title),!ae(o)){const k=r.getTime()-o;l.$duration=parseFloat((k/1e3).toFixed(3))}Vr&&this.config.opt_out_useragent_filter&&(l.$browser_type=this._is_bot()?"bot":"browser");const h=this.persistence.properties(),m=this.sessionPersistence.properties(),v=l.$groups,w=h.$groups;nt(v)&&!ts(v)&&(l.$groups=$($({},nt(w)?w:{}),v)),Pt(["$referrer","$referring_domain"],k=>{k in h&&delete m[k]});const _={};if(this._h.length>0)for(const k of this._h.slice())try{en(_,k())}catch(C){he.error("Failed to produce browser extension event properties",C)}l=en({},u,h,m,$($({},_),l)),l.$is_identified=this._isIdentified(),ze(this.config.property_denylist)?Pt(this.config.property_denylist,function(k){delete l[k]}):he.error(NR+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);const x=this.config.sanitize_properties;x&&(he.error(D8),l=x(l,e));const b=this.ld();return l.$process_person_profile=b,b&&!i&&this.ud("_calculate_event_properties"),l}rd(e,n=!0,r=!1){var s;if(!this.persistence||!this.ld()||this.mh&&!r)return e;const i=this.persistence.get_initial_props(),o=(s=this.sessionPropsManager)===null||s===void 0?void 0:s.getSetOnceProps();let l=en({},i,o||{},e||{});const u=this.config.sanitize_properties;return u&&(he.error(D8),l=u(l,"$set_once")),n&&(this.mh=!0),ts(l)?void 0:l}register(e,n){var r;(r=this.persistence)===null||r===void 0||r.register(e,n)}register_once(e,n,r){var s;(s=this.persistence)===null||s===void 0||s.register_once(e,n,r)}register_for_session(e){var n,r;(n=this.persistence)===null||n===void 0||n.syncCookieProperties(),this.Dh(),(r=this.sessionPersistence)===null||r===void 0||r.register(e),Object.keys(e).forEach(s=>this.yh.add(s)),this.ad()}unregister(e){var n;(n=this.persistence)===null||n===void 0||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)===null||n===void 0||n.unregister(e),this.yh.delete(e),this.ad()}hd(e,n){this.register({[e]:n})}Rh(){this.yh.forEach(e=>{var n;(n=this.sessionPersistence)===null||n===void 0||n.unregister(e)}),this.yh.clear(),this.ad()}ad(){var e;if(!this.bh)return;if(this.config.persistence==="memory"||!((e=this.sessionPersistence)===null||e===void 0)&&e.hi||!Bt.Et())return void Bt.Pt(this.bh);const n=[];this.yh.forEach(r=>n.push(r)),n.length>0?Bt.At(this.bh,n):Bt.Pt(this.bh)}getFeatureFlag(e,n){var r;return(r=this.featureFlags)===null||r===void 0?void 0:r.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)===null||n===void 0?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var r;return(r=this.featureFlags)===null||r===void 0?void 0:r.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)===null||n===void 0?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var r,s;return(r=(s=this.featureFlags)===null||s===void 0?void 0:s.isFeatureEnabled(e,n))!==null&&r!==void 0?r:n==null?void 0:n.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)===null||e===void 0||e.reloadFeatureFlags()}updateFlags(e,n,r){var s;(s=this.featureFlags)===null||s===void 0||s.updateFlags(e,n,r)}updateEarlyAccessFeatureEnrollment(e,n,r){var s;(s=this.featureFlags)===null||s===void 0||s.updateEarlyAccessFeatureEnrollment(e,n,r)}getEarlyAccessFeatures(e,n=!1,r){var s;return(s=this.featureFlags)===null||s===void 0?void 0:s.getEarlyAccessFeatures(e,n,r)}on(e,n){return this.ur.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:pu}),()=>{})}onSessionId(e){var n,r;return(n=(r=this.sessionManager)===null||r===void 0?void 0:r.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n=!1){this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:pu})}getActiveMatchingSurveys(e,n=!1){this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:pu})}onActiveMatchingSurveysChanged(e){return this.surveys?this.surveys.onActiveMatchingSurveysChanged(e):(e([],{isLoaded:!1,error:pu}),()=>{})}renderSurvey(e,n){var r;(r=this.surveys)===null||r===void 0||r.renderSurvey(e,n)}displaySurvey(e,n=_V){var r;(r=this.surveys)===null||r===void 0||r.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)===null||n===void 0||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,r;return(n=(r=this.surveys)===null||r===void 0?void 0:r.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:pu}}canRenderSurveyAsync(e,n=!1){var r,s;return(r=(s=this.surveys)===null||s===void 0?void 0:s.canRenderSurveyAsync(e,n))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:pu})}dd(e){return!e||Bf(e)?(he.critical("Unique user id has not been set in posthog.identify"),!1):e==="$posthog_cookieless"?(he.critical(`The string "${e}" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.`),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(he.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.`),!1)}identify(e,n,r){if(!this.__loaded||!this.persistence)return he.uninitializedWarning("posthog.identify");if(Cn(e)&&(e=e.toString(),he.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),!this.dd(e)||!this.ud("posthog.identify"))return;this.ah();const s=this.get_distinct_id(),i=this.persistence.syncCookieProperties()&&this.get_distinct_id()!==s,o=this.Dh(!1),l=this.persistence.ku();let u=!1;try{const f=this.get_distinct_id();this.register({$user_id:e}),this.get_property("$device_id")||this.register_once({$had_persisted_distinct_id:!0,$device_id:f},""),e!==f&&e!==this.get_property("__alias")&&(this.unregister(Bm),this.register({distinct_id:e}));const h=(this.persistence.get_property("$user_state")||"anonymous")===Fo,m=e!==f,v=!m&&h;if(m&&h){var d;const w=this.config.reuseAnonymousId?{distinct_id:e}:{distinct_id:e,$anon_distinct_id:f};this.persistence.set_property(Cr,om),this.setPersonPropertiesForFlags({$set:n||{},$set_once:r||{}},!1),this.config.cookieWinsOnConflict&&this.persistence.Su(),this.capture("$identify",w,{$set:n||{},$set_once:r||{}})&&(this.$h=$y(e,n,r)),(d=this.featureFlags)===null||d===void 0||d.setAnonymousDistinctId(this.config.reuseAnonymousId?void 0:f)}else if(v){this.persistence.set_property(Cr,om);const w=n||{},_=r||{};this.setPersonPropertiesForFlags({$set:w,$set_once:_},!1),this.config.cookieWinsOnConflict&&this.persistence.Su(),this.capture("$set",{$set:w,$set_once:_})&&(this.$h=$y(e,n,r))}else(n||r)&&this.setPersonProperties(n,r);m||i||o?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister($o)):v&&(n||r)&&this.reloadFeatureFlags(),u=!0}finally{l&&this.persistence.Cu(u)}}setPersonProperties(e,n){if(!e&&!n||!this.ud("posthog.setPersonProperties"))return;const r=$y(this.get_distinct_id(),e,n);this.$h!==r?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}})&&(this.$h=r)):he.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}unsetPersonProperties(e){var n;const r=(ze(e)?e:[e]).filter(s=>rt(s)&&s.length>0);r.length!==0&&this.ud("posthog.unsetPersonProperties")&&((n=this.featureFlags)===null||n===void 0||n.unsetPersonPropertiesForFlags(r,!0),this.capture("$set",{$unset:r}),this.$h=null)}group(e,n,r){var s;if(!e||!n)return void he.error("posthog.group requires a group type and group key");(s=this.persistence)===null||s===void 0||s.syncCookieProperties(),this.Dh();const i=this.getGroups(),o=i[e]!==n;if(o&&this.resetGroupPropertiesForFlags(e),this.register({$groups:$($({},i),{},{[e]:n})}),(o||r)&&this.ld()){const l={$group_type:e,$group_key:n};r&&(l.$group_set=r),this.capture(t8,l)}r&&this.setGroupPropertiesForFlags({[e]:r}),o&&!r&&this.reloadFeatureFlags()}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n=!0){var r;(r=this.featureFlags)===null||r===void 0||r.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e=!0){var n;(n=this.featureFlags)===null||n===void 0||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n=!0){var r;this.ud("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)===null||r===void 0||r.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)===null||n===void 0||n.resetGroupPropertiesForFlags(e)}reset(e){const n=Hr(e)?e:e==null?void 0:e.resetDeviceID,r=Hr(e)||e==null?void 0:e.bootstrap;this.vd(n,!1,r)}vd(e,n=!1,r){var s,i,o,l,u,d;if(he.info("reset"),!this.__loaded)return he.uninitializedWarning("posthog.reset");const f=r==null?void 0:r.sessionID;this.config.bootstrap=r||((s=this.Th)===null||s===void 0?void 0:s.bootstrap)||{},(i=this.featureFlags)===null||i===void 0||(o=i.updateConfig)===null||o===void 0||o.call(i,this.config,this.Qu());const h=this.get_property(zx),m=this.get_property(by),v=this.get_property(Gf);(l=this.sessionRecording)===null||l===void 0||l.flushBeforeIdentityReset();const w=this.is_capturing();n||this.consent.reset(),n||!w||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after.");const _=(u=this.persistence)===null||u===void 0||(d=u.ku)===null||d===void 0?void 0:d.call(u),x=this.uh;this.uh=x||n;let b=!1;try{var k,C,P,T,M,I,R,L,j,F,N,q,W;if((k=this.persistence)===null||k===void 0||k.clear(),(C=this.sessionPersistence)===null||C===void 0||C.clear(),this.yh.clear(),this.ad(),ae(v)||(F=this.persistence)===null||F===void 0||F.register({$session_recording_remote_config:v}),(P=this.surveys)===null||P===void 0||P.reset(),(T=this.featureFlags)===null||T===void 0||T.reset(),(M=this.conversations)===null||M===void 0||M.reset(),(I=this.logs)===null||I===void 0||I.reset(),(R=this.metrics)===null||R===void 0||R.reset(),(L=this.persistence)===null||L===void 0||L.set_property("$user_state","anonymous"),(j=this.sessionManager)===null||j===void 0||j.resetSessionId(),this.$h=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:Sy,$device_id:null},"");else{const B=this.config.get_device_id(xi());this.register_once({distinct_id:B,$device_id:e?B:h},""),e||ae(m)||this.register({[by]:m})}if(this.register({$last_posthog_reset:new Date().toISOString()},1),r&&(r.distinctID&&!this.nh()&&((W=this.persistence)===null||W===void 0||W.set_property("$user_state",r.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:r.distinctID})),(N=this.featureFlags)===null||N===void 0||N.initialize(),!Xe(f)&&!(!((q=this.sessionManager)===null||q===void 0)&&q.setBootstrapSessionId(f,!0)))){const B=$({},r);delete B.sessionID,this.config.bootstrap=B}delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,b=!0}finally{var Y,H;this.uh=x,_&&((Y=this.persistence)===null||Y===void 0||(H=Y.Cu)===null||H===void 0||H.call(Y,b))}var J;this.cr&&((J=this.conversations)===null||J===void 0||J.onRemoteConfig(this.cr)),this.reloadFeatureFlags()}shutdown(e){var n=this;return Wt(function*(){if(!n.__loaded)return void he.uninitializedWarning("posthog.shutdown");n.gh=!0,clearTimeout(n.Fh),n.Fh=void 0;const r=n.zh;n.zh=void 0;for(const s of[()=>{var i;return(i=n.sessionRecording)===null||i===void 0?void 0:i.dispose()},()=>{var i;return(i=n.logs)===null||i===void 0?void 0:i.flushLogs("sendBeacon")},()=>{var i;return(i=n.metrics)===null||i===void 0?void 0:i.flush("sendBeacon")},()=>{var i;return(i=n.metrics)===null||i===void 0?void 0:i.dispose()},()=>{var i;return(i=n.logs)===null||i===void 0?void 0:i.dispose()},()=>{var i;return(i=n.surveys)===null||i===void 0?void 0:i.dispose()},()=>{var i;return(i=n.autocapture)===null||i===void 0?void 0:i.dispose()},()=>r==null?void 0:r(),()=>{var i;return(i=n.Mh)===null||i===void 0?void 0:i.unload()},()=>{var i;return(i=n.Ph)===null||i===void 0?void 0:i.unload()},()=>{var i;return(i=n.featureFlags)===null||i===void 0?void 0:i.destroy()},()=>{var i;return(i=n.persistence)===null||i===void 0?void 0:i.destroy()},()=>{var i;return(i=n.sessionPersistence)===null||i===void 0?void 0:i.destroy()}])try{const i=s();i&&gn(i.then)&&i.then(void 0,o=>{he.error("Error during shutdown",o)})}catch(i){he.error("Error during shutdown",i)}})()}setIdentity(e,n){var r;delete this.config.identity_claims,this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(r=this.conversations)===null||r===void 0||r.fd()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,(e=this.conversations)===null||e===void 0||e.pd()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)===null||n===void 0?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";const{sessionId:n,sessionStartTimestamp:r}=this.sessionManager.checkAndGetSessionAndWindowId(!0);let s=this.requestRouter.endpointFor("ui",`/project/${this.config.token}/replay/${n}`);if(e!=null&&e.withTimestamp&&r){var i;const o=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!r)return s;s+=`?t=${Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}`}return s}alias(e,n){return e===this.get_property("$people_distinct_id")?(he.critical("Attempting to create alias for existing People user - aborting."),-2):this.ud("posthog.alias")?(ae(n)&&(n=this.get_distinct_id()),e!==n?(this.hd(Bm,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(he.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){const n=$({},this.config);if(nt(e)){var r,s,i,o,l,u,d,f,h,m,v,w,_,x;en(this.config,V8(e));const T=this.fh();if(this.persistence){const I=this.config.persistence==="sessionStorage"||this.config.persistence==="memory";var b,k;if(I&&this.sessionPersistence!==this.persistence&&((b=this.sessionPersistence)===null||b===void 0||b.remove(),(k=this.sessionPersistence)===null||k===void 0||k.destroy()),this.persistence.update_config(this.config,n,T),I)this.sessionPersistence=this.persistence;else if(this.sessionPersistence===this.persistence)this.sessionPersistence=new Iy($($({},this.config),{},{persistence:"sessionStorage"}),T,!1);else{var C;(C=this.sessionPersistence)===null||C===void 0||C.update_config($($({},this.config),{},{persistence:"sessionStorage"}),$($({},n),{},{persistence:"sessionStorage"}),T)}}const M=this.Ch(this.config.debug);var P;Hr(M)&&(this.config.debug=M),Hr(this.config.debug)&&(this.config.debug?(Jr.DEBUG=!0,gt.Et()&>.At("ph_debug",!0),he.info("set_config",{config:e,oldConfig:n,newConfig:$({},this.config)})):(Jr.DEBUG=!1,gt.Et()&>.Pt("ph_debug"))),(r=this.featureFlags)===null||r===void 0||(s=r.updateConfig)===null||s===void 0||s.call(r,this.config,this.Qu()),(i=this.exceptionObserver)===null||i===void 0||i.onConfigChange(),(o=this.exceptions)===null||o===void 0||o.onConfigChange(),(l=this.metrics)===null||l===void 0||l.onConfigChange(),(u=this.webMCP)===null||u===void 0||u.startIfEnabled(),(d=this.sessionRecording)===null||d===void 0||d.startIfEnabledOrStop(),(f=this.tracingHeaders)===null||f===void 0||f.startIfEnabledOrStop(),(h=this.autocapture)===null||h===void 0||h.startIfEnabled(),(m=this.heatmaps)===null||m===void 0||m.startIfEnabled(),("capture_pageview"in e||"disable_capture_url_hashes"in e)&&((P=this.historyAutocapture)===null||P===void 0||P.startIfEnabledOrStop()),(v=this.exceptionObserver)===null||v===void 0||v.startIfEnabledOrStop(),(w=this.deadClicksAutocapture)===null||w===void 0||w.startIfEnabledOrStop(),(_=this.surveys)===null||_===void 0||_.loadIfEnabled(),this.hh(),(x=this.externalIntegrations)===null||x===void 0||x.startIfEnabledOrStop(),!n.segment&&this.config.segment&&this.persistence&&_8(this,eh,!1)}}_overrideSDKInfo(e,n){Jr.LIB_NAME=e,Jr.LIB_VERSION=n}startSessionRecording(e){const n=e===!0,r={sampling:n||!!(e!=null&&e.sampling),linked_flag:n||!!(e!=null&&e.linked_flag),url_trigger:n||!!(e!=null&&e.url_trigger),event_trigger:n||!!(e!=null&&e.event_trigger)};var s,i,o,l,u;Object.values(r).some(Boolean)&&((s=this.sessionManager)===null||s===void 0||s.checkAndGetSessionAndWindowId(),r.sampling&&((i=this.sessionRecording)===null||i===void 0||i.overrideSampling()),r.linked_flag&&((o=this.sessionRecording)===null||o===void 0||o.overrideLinkedFlag()),r.url_trigger&&((l=this.sessionRecording)===null||l===void 0||l.overrideTrigger("url")),r.event_trigger&&((u=this.sessionRecording)===null||u===void 0||u.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===void 0)&&e.started)}captureException(e,n){try{if(!this.exceptions)return;const r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:new Error("PostHog syntheticException")});return this.exceptions.sendExceptionEvent($($({},r),n))}catch{return}}addExceptionStep(e,n){var r;(r=this.exceptions)===null||r===void 0||r.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)===null||n===void 0||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)===null||n===void 0?void 0:n.logger)!==null&&e!==void 0?e:Ea.gd}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,r;return(n=(r=this.toolbar)===null||r===void 0?void 0:r.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)===null||n===void 0?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)===null||n===void 0?void 0:n.props[e]}toString(){var e;let n=(e=this.config.name)!==null&&e!==void 0?e:jf;return n!==jf&&(n="posthog."+n),n}_isIdentified(){var e,n;return((e=this.persistence)===null||e===void 0?void 0:e.get_property("$user_state"))==="identified"||((n=this.sessionPersistence)===null||n===void 0?void 0:n.get_property("$user_state"))==="identified"}ld(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&ts(this.getGroups())&&!(!((e=this.persistence)===null||e===void 0||(e=e.props)===null||e===void 0)&&e.__alias)&&!(!((n=this.persistence)===null||n===void 0||(n=n.props)===null||n===void 0)&&n.$epp))}Qh(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&!!this.config.capture_pageview}createPersonProfile(){this.ld()||this.ud("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.ud("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}ud(e){return this.config.person_profiles==="never"?(he.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.sh(),this.hd(Wx,!0),!0)}fh(){if(this.config.cookieless_mode==="always")return!0;const e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!=="on_reject")}hh(){var e,n;const r=this.fh();var s,i,o;return this.is_capturing()||(s=this.logs)===null||s===void 0||s.md(),((e=this.persistence)===null||e===void 0?void 0:e.hi)!==r&&((i=this.persistence)===null||i===void 0||i.set_disabled(r)),((n=this.sessionPersistence)===null||n===void 0?void 0:n.hi)!==r&&((o=this.sessionPersistence)===null||o===void 0||o.set_disabled(r)),this.ad(),r}opt_in_capturing(e){var n;if(this.config.cookieless_mode!=="always"){if(this.nh()){var r,s,i,o,l,u;(r=this.sessionRecording)===null||r===void 0||r.dispose({discardBufferedEvents:!0}),this.vd(!0,!0),(s=this.sessionManager)===null||s===void 0||s.destroy(),(i=this.pageViewManager)===null||i===void 0||i.destroy(),this.sessionManager=new M8(this),this.pageViewManager=new w8(this),this.persistence&&(this.sessionPropsManager=new R8(this,this.sessionManager,this.persistence));const w=(o=(l=this.config.__extensionClasses)===null||l===void 0?void 0:l.sessionRecording)!==null&&o!==void 0?o:(u=Ea.__defaultExtensionClasses)===null||u===void 0?void 0:u.sessionRecording;var d,f;w&&(this.sessionRecording=this.ih(this.sessionRecording,new w(this)),this.cr&&((d=this.sessionRecording)===null||d===void 0||(f=d.onRemoteConfig)===null||f===void 0||f.call(d,this.cr)))}var h,m,v;this.consent.optInOut(!0),this.hh(),this.Wh(),(n=this.sessionRecording)===null||n===void 0||n.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&((h=this.surveys)===null||h===void 0||h.loadIfEnabled(),(m=this.conversations)===null||m===void 0||m.loadIfEnabled()),(ae(e==null?void 0:e.captureEventName)||e!=null&&e.captureEventName)&&this.capture((v=e==null?void 0:e.captureEventName)!==null&&v!==void 0?v:"$opt_in",e==null?void 0:e.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Vh()}else he.warn(N8)}opt_out_capturing(){this.config.cookieless_mode!=="always"?(this.consent.optInOut(!1),this.hh(),this.config.cookieless_mode==="on_reject"&&this.dh()):he.warn(N8)}dh(){var e,n;const r=this.sessionRecording;r==null||r.dispose({discardBufferedEvents:!0}),this.get_distinct_id()!=="$posthog_cookieless"&&this.vd(!0,!0),this.register({distinct_id:Sy,$device_id:null}),this.th(r),this.sessionRecording=void 0,(e=this.sessionManager)===null||e===void 0||e.destroy(),(n=this.pageViewManager)===null||n===void 0||n.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Vh(),this.Wh()}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){const e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return!this.uh&&(this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing()))}clear_opt_in_out_capturing(){this.consent.reset(),this.hh()}_is_bot(){return gr?ER(gr,this.config.custom_blocked_useragents):void 0}Vh(){ke&&(ke.visibilityState==="visible"?this.kh||(this.kh=!0,this.capture(Gx,{title:ke.title},{send_instantly:!0}),this.Sh&&(ke.removeEventListener(Du,this.Sh),this.Sh=null)):this.Sh||(this.Sh=this.Vh.bind(this),_t(ke,Du,this.Sh)))}debug(e){e===!1?(oe==null||oe.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(oe==null||oe.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}))}Qu(){const e=this.Th||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(he.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):(function(n,r,s,i,o){const l=r in n&&!Xe(n[r]),u=s in n&&!Xe(n[s]);return l?n[r]:!!u&&(o&&o.warn(`Config field '${s}' is deprecated. Please use '${r}' instead. The old field will be removed in a future major version.`),n[s])})(e,"advanced_disable_flags","advanced_disable_decide",0,he)}Os(e){var n;if(Xe(this.config.before_send))return e;const r=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(C7),s=ze(this.config.before_send)?this.config.before_send:[this.config.before_send];let i=e;for(const o of s)try{if(i=o(i),Xe(i)){const l=`Event '${e.event}' was rejected in beforeSend function`;return E7(e.event)?he.warn(`${l}. This can cause unexpected behavior.`):he.info(l),null}i.properties&&!ts(i.properties)||he.warn(`Event '${e.event}' has no properties after beforeSend function, this is likely an error.`)}catch(l){return he.error(`Error in beforeSend function for event '${e.event}':`,l),null}for(const o of r)if(i.properties&&Xe(i.properties[o]))return he.warn(`Event '${e.event}' had its '${o}' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped.`),null;return i}getPageViewId(){var e;return(e=this.pageViewManager.Rl)===null||e===void 0?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(r)})}Ch(e){const n=Hr(e)&&!e,r=gt.Et()&>.Ot("ph_debug")==="true";return!n&&(!!r||e)}};th.__defaultExtensionClasses={},th.gd=(()=>{const t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(let n=0;e.length>n;n++)t.prototype[e[n]]=SF(t.prototype[e[n]])})(th,["identify"]);const jV=["[data-ph-capture-value]"];var $V=class{constructor(t){this._instance=t}refresh(t){var e;const n=this._instance.config,r=nt(n.autocapture)?n.autocapture:void 0;t.enabled=!!n.autocapture,t.rageclick=n.rageclick,t.maskAllElementAttributes=n.mask_all_element_attributes,t.maskAllText=n.mask_all_text,t.disableCaptureUrlHashes=n.disable_capture_url_hashes,t.getCurrentUrl=n.get_current_url,t.remoteRequestsDisabled=this._instance.Qu(),t.url_allowlist=r==null?void 0:r.url_allowlist,t.url_ignorelist=r==null?void 0:r.url_ignorelist,t.dom_event_allowlist=r==null?void 0:r.dom_event_allowlist,t.element_allowlist=r==null?void 0:r.element_allowlist,t.css_selector_allowlist=r==null?void 0:r.css_selector_allowlist,t.css_selector_ignorelist=r==null?void 0:r.css_selector_ignorelist,t.element_attribute_ignorelist=r==null?void 0:r.element_attribute_ignorelist,t.capture_copied_text=r==null?void 0:r.capture_copied_text,t.capture_value_css_selector_allowlist=(e=r==null?void 0:r.capture_value_css_selector_allowlist)!==null&&e!==void 0?e:jV}};const Cf=an("[ExceptionAutocapture]"),H8=()=>{},z8=t=>{var e;if(gn(t))return(e=t.__posthog_layer__)!==null&&e!==void 0?e:t.__rrweb_layer__};function cd(t,e,n){try{if(!(e in t))return H8;const r={next:t[e]},s=n(function(...i){return r.next.apply(this,i)});return gn(s)&&(s.prototype=s.prototype||{},Object.defineProperties(s,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:r}})),t[e]=s,()=>{if(t[e]===s)return void(t[e]=r.next);let i=t[e],o=z8(i);for(;o;){if(o.next===s)return void(o.next=r.next);i=o.next,o=z8(i)}}}catch{return H8}}const FV=an("[TracingHeaders]"),Ml=an("[Web Vitals]"),U8=9e5,B8=["CLS","FCP","INP","LCP"],VV=["INP","LCP"],HV=["interactionTarget","interactionType","inputDelay","processingDuration","presentationDelay","loadState","target","url","timeToFirstByte","resourceLoadDelay","resourceLoadDuration","elementRenderDelay","largestShiftTarget","largestShiftTime","largestShiftValue","firstByteToFCP"],Uy="disabled",W8="lazy_loading",So=an("[SessionRecording]"),zV=[Zx,qx,TT,RT,IT,MT,OT,LT,NT],UV=an("[Heatmaps]");function By(t){return nt(t)&&"clientX"in t&&"clientY"in t&&Cn(t.clientX)&&Cn(t.clientY)}const P0=an("[Product Tours]"),Wy=t=>{var e;return!t.config.disable_product_tours&&!!(!((e=t.persistence)===null||e===void 0)&&e.get_property(Bx))},BV=["$set_once","$set"],Mi=an("[SiteApps]"),Z8="Error while initializing PostHog app with config id ";function mu(t,e,n){if(Xe(t))return!1;switch(n){case"exact":return t===e;case"contains":{const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t)}case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}var WV=class{constructor(t){this.Ai=t,this._o=new Set,this.wo=new Set,this.ko=new Ym,this.So=(e,n)=>this.xo(e,n)&&this.$o(e,n)&&this.Co(e,n)&&this.To(e,n),this.xo=(e,n)=>!(n!=null&&n.event)||(e==null?void 0:e.event)===(n==null?void 0:n.event)}init(){var t,e;ae((t=this.Ai)===null||t===void 0?void 0:t.subscribeCapture)||(this.Io=(e=this.Ai)===null||e===void 0?void 0:e.subscribeCapture((n,r)=>{this.on(n,r)}))}dispose(){var t,e,n;(t=this.Io)===null||t===void 0||t.call(this),this.Io=void 0,(e=this.Ai)===null||e===void 0||(n=e.setElementSelectors)===null||n===void 0||n.call(e,new Set,this),this.ko=new Ym}register(t){var e,n;if(!ae((e=this.Ai)===null||e===void 0?void 0:e.subscribeCapture)&&(t.forEach(r=>{var s;this._o.add(r),(s=r.steps)===null||s===void 0||s.forEach(i=>{this.wo.add((i==null?void 0:i.event)||"")})}),(n=this.Ai)===null||n===void 0?void 0:n.setElementSelectors)){const r=new Set;this._o.forEach(s=>{var i;(i=s.steps)===null||i===void 0||i.forEach(o=>{o!=null&&o.selector&&r.add(o.selector)})}),this.Ai.setElementSelectors(r,this)}}replace(t){this._o.clear(),this.wo.clear(),this.register(t)}on(t,e){e!=null&&t.length!=0&&(this.wo.has(t)||this.wo.has(e.event))&&this._o.forEach(n=>{this.Mo(e,n)&&this.ko.emit("actionCaptured",n.name)})}Eo(t){this.onAction("actionCaptured",e=>t(e))}Mo(t,e){if((e==null?void 0:e.steps)==null)return!1;for(const n of e.steps)if(this.So(t,n))return!0;return!1}onAction(t,e){return this.ko.on(t,e)}$o(t,e){if(e!=null&&e.url){var n;let i=t==null||(n=t.properties)===null||n===void 0?void 0:n.$current_url;if(!(t!=null&&t.properties)||!("$current_url"in t.properties))try{var r,s;i=(r=this.Ai)===null||r===void 0||(s=r.getActionUrl)===null||s===void 0?void 0:s.call(r)}catch{return!1}if(!i||typeof i!="string"||!mu(i,e.url,e.url_matching||"contains"))return!1}return!0}Co(t,e){return!!this.Po(t,e)&&!!this.Ro(t,e)&&!!this.Ao(t,e)}Po(t,e){var n;if(!(e!=null&&e.href))return!0;const r=this.Fo(t);if(r.length>0)return r.some(i=>mu(i.href,e.href,e.href_matching||"exact"));const s=(t==null||(n=t.properties)===null||n===void 0?void 0:n.$elements_chain)||"";return!!s&&mu((function(i){const o=i.match(/(?::|")href="(.*?)"/);return o?o[1]:""})(s),e.href,e.href_matching||"exact")}Ro(t,e){var n;if(!(e!=null&&e.text))return!0;const r=this.Fo(t);if(r.length>0)return r.some(u=>mu(u.text,e.text,e.text_matching||"exact")||mu(u.$el_text,e.text,e.text_matching||"exact"));const s=(t==null||(n=t.properties)===null||n===void 0?void 0:n.$elements_chain)||"";return!!s&&(i=(function(u){const d=[],f=/(?::|")text="(.*?)"/g;let h;for(;!Xe(h=f.exec(u));)d.includes(h[1])||d.push(h[1]);return d})(s),o=e.text,l=e.text_matching||"exact",i.some(u=>mu(u,o,l)));var i,o,l}Ao(t,e){var n,r;if(!(e!=null&&e.selector))return!0;const s=t==null||(n=t.properties)===null||n===void 0?void 0:n.$element_selectors;if(s!=null&&s.includes(e.selector))return!0;const i=(t==null||(r=t.properties)===null||r===void 0?void 0:r.$elements_chain)||"";if(e.selector_regex&&i)try{return new RegExp(e.selector_regex).test(i)}catch{}return!1}Fo(t){var e;return(t==null||(e=t.properties)===null||e===void 0?void 0:e.$elements)==null?[]:t==null?void 0:t.properties.$elements}To(t,e){return!(e!=null&&e.properties)||e.properties.length===0||TR(e.properties.reduce((n,r)=>{const s=ze(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return n[r.key]={values:s,operator:r.operator||"exact"},n},{}),t==null?void 0:t.properties)}},ZV=class{constructor(t,e){this.Oo=e,this.Do=[],this.Ai=t,this.Lo=new Map,this.No=new Map,this.qo=new Map}jo(){var t,e;this.Bo=(t=(e=this.Ai).subscribeSession)===null||t===void 0?void 0:t.call(e,n=>this.zo(n))}Ho(t){return!1}Uo(){return null}Wo(t){}Vo(){}Go(t,e){return!!t&&TR(t.propertyFilters,e==null?void 0:e.properties)}Qo(t,e){const n=new Map;return t.forEach(r=>{var s;(s=r.conditions)===null||s===void 0||(s=s[e])===null||s===void 0||(s=s.values)===null||s===void 0||s.forEach(i=>{if(i!=null&&i.name){const o=n.get(i.name)||[];o.push(r.id),n.set(i.name,o)}})}),n}Zo(t,e,n){const r=(n===bf.Activation?this.Lo:this.No).get(t);let s=[];return this.Jo(i=>{s=i.filter(o=>r==null?void 0:r.includes(o.id))}),s.filter(i=>{var o;const l=(o=i.conditions)===null||o===void 0||(o=o[n])===null||o===void 0||(o=o.values)===null||o===void 0?void 0:o.find(u=>u.name===t);return this.Go(l,e)})}register(t){this.Ko(t,!1)}replace(t){this.Ko(t,!0)}Ko(t,e){ae(this.Ai.subscribeCapture)||(this.Xo(t,e),this.Yo(t,e))}Yo(t,e){const n=t.filter(i=>{var o;return(o=i.conditions)===null||o===void 0||(o=o.actions)===null||o===void 0||(o=o.values)===null||o===void 0?void 0:o.length});var r;if(e&&this.qo.clear(),n.length===0)return void(e&&((r=this.ta)===null||r===void 0||r.replace([])));this.ta||(this.ta=new WV(this.Ai),this.ta.init(),this.ta.Eo(i=>this.onAction(i)));const s=[];n.forEach(i=>{var o;(o=i.conditions)===null||o===void 0||(o=o.actions)===null||o===void 0||o.values.forEach(l=>{if(s.push(l),l.name){var u;const d=(u=this.qo.get(l.name))!==null&&u!==void 0?u:[];d.includes(i.id)||d.push(i.id),this.qo.set(l.name,d)}})}),e?this.ta.replace(s):this.ta.register(s)}ea(t,e){e.forEach((n,r)=>{var s;const i=(s=t.get(r))!==null&&s!==void 0?s:[];n.forEach(o=>{i.includes(o)||i.push(o)}),t.set(r,i)})}Xo(t,e){var n,r,s;const i=t.filter(d=>{var f,h;return((f=d.conditions)===null||f===void 0?void 0:f.events)&&((h=d.conditions)===null||h===void 0||(h=h.events)===null||h===void 0||(h=h.values)===null||h===void 0?void 0:h.length)>0}),o=t.filter(d=>{var f,h;return((f=d.conditions)===null||f===void 0?void 0:f.cancelEvents)&&((h=d.conditions)===null||h===void 0||(h=h.cancelEvents)===null||h===void 0||(h=h.values)===null||h===void 0?void 0:h.length)>0}),l=this.Qo(t,bf.Activation),u=this.Qo(t,bf.Cancellation);e?(this.Lo=l,this.No=u):(this.ea(this.Lo,l),this.ea(this.No,u)),(i.length!==0||o.length!==0||t.some(d=>{var f;return(f=d.conditions)===null||f===void 0||(f=f.actions)===null||f===void 0||(f=f.values)===null||f===void 0?void 0:f.length}))&&((n=this.Io)!==null&&n!==void 0||(this.Io=(r=(s=this.Ai).subscribeCapture)===null||r===void 0?void 0:r.call(s,(d,f)=>{this.onEvent(d,f)})))}onEvent(t,e){var n,r;const s=this.ia(),i=(e==null||(n=e.properties)===null||n===void 0?void 0:n.$survey_id)||(e==null||(r=e.properties)===null||r===void 0?void 0:r.$product_tour_id);if(i&&this.getActivatedIds().includes(i)){const l=this.na(t,i,e);if(l==="consume")return s.info("event consumed activated item, removing it",{event:t,itemId:i}),void this.sa([i]);if(l==="persist")return s.info("shown item promoted to persisted activation",{event:t,itemId:i}),this.ra(i),void this.oa([i])}if(this.No.has(t)){const l=this.Zo(t,e,bf.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:t,itemsToCancel:l.map(u=>u.id)}),this.sa(l.map(u=>u.id)),l.forEach(u=>this.aa(u.id)))}if(!this.Lo.has(t))return;s.info("event name matched",{event:t,eventPayload:e,items:this.Lo.get(t)});const o=this.Zo(t,e,bf.Activation);this.la(o.map(l=>l.id))}onAction(t){this.qo.has(t)&&this.la(this.qo.get(t)||[])}la(t){if(t.length===0)return;const e=!!this.Ai.getSessionId(),n=[];for(const r of t)e&&this.Ho(r)?this.ra(r)&&this.ua(r):n.push(r);n.length>0&&(this.Do=[...new Set([...this.Do,...n])]),this.ia().info("updating activated items",{activatedItems:this.getActivatedIds()}),this.ca()}ra(t){this.Do=this.Do.filter(n=>n!==t);const e=this.ha();return!e.includes(t)&&(this.da([...e,t]),this.va(),!0)}sa(t){const e=new Set(t);this.Do=this.Do.filter(s=>!e.has(s));const n=this.fa(),r=n.filter(s=>!e.has(s));r.length!==n.length&&(this.da(r),r.length===0&&this.pa()),this.oa(t),this.ca()}ca(){try{var t;(t=this.Oo)===null||t===void 0||t.call(this)}catch(e){this.ia().error("Error while handling activated items change",e)}}ga(){const t=this.Uo();if(!t)return{};const e=this.Ai.getProperty(t);return e&&typeof e=="object"?e:{}}ua(t){if(!this.Uo())return;const e=this.ga();this.Wo($($({},e),{},{[t]:Date.now()}))}oa(t){if(!this.Uo())return;const e=this.ga(),n={};let r=!1;for(const[s,i]of Object.entries(e))t.includes(s)?r=!0:n[s]=i;r&&(ts(n)?this.Vo():this.Wo(n))}ma(){this.Uo()&&this.Vo()}getActivationTimestamp(t){if(!this.ha().includes(t))return;const e=this.ga()[t];return Cn(e)?e:void 0}fa(){const t=this.ya();return this.Ai.getProperty(t)||[]}ha(){const t=this.fa();if(t.length===0)return[];const e=this.Ai.getProperty(this.ba()),n=this.Ai.getSessionId();return n&&e===n?t:[]}va(){const t=this.Ai.getSessionId();t&&this._a(t)}pa(){this.wa()}zo(t){const e=this.Ai.getProperty(this.ba());if(e&&e!==t){const n=this.fa(),r=this.ga();n.length>0&&(this.da([]),n.filter(s=>Cn(r[s])).forEach(s=>this.aa(s))),this.pa(),this.ma(),n.length>0&&this.ca()}}getActivatedIds(){return[...new Set([...this.ha(),...this.Do])].filter(t=>!this.ka(t))}dispose(){var t,e,n;(t=this.Bo)===null||t===void 0||t.call(this),this.Bo=void 0,(e=this.Io)===null||e===void 0||e.call(this),this.Io=void 0,(n=this.ta)===null||n===void 0||n.dispose(),this.ta=void 0}reset(){this.Do=[],this.fa().length>0&&this.da([]),this.pa(),this.ma(),this.ca()}getEventToItemsMap(){return this.Lo}Sa(){return this.ta}},qV=class extends ZV{constructor(t,e,n,r){var s;super({subscribeCapture(i){const o=t.onEvent(l=>i(l.event,l));return()=>o.dispose()},subscribeSession(i){const o=t.onSession(i);return()=>o.dispose()},getSessionId(){var i;return(i=t.session)===null||i===void 0?void 0:i.sessionId},getProperty:i=>t.kv.get(i),getActionUrl:n==null?void 0:n.getActionUrl,setElementSelectors:(s=n==null?void 0:n.setElementSelectors)!==null&&s!==void 0?s:(i,o)=>{var l;return(l=t.getExtension("autocapture"))===null||l===void 0?void 0:l.setElementSelectors(i,o)}},r),this.xa=t,this.$a=e,this.jo()}ya(){return g2}ba(){return sm}Uo(){return im}Wo(t){this.xa.kv.set({[im]:t})}Vo(){this.xa.kv.remove(im)}Ho(t){var e;let n;this.Jo(s=>{n=s.find(i=>i.id===t)});const r=n==null||(e=n.appearance)===null||e===void 0?void 0:e.surveyPopupDelaySeconds;return Cn(r)&&r>0}Ca(){return bs.SHOWN}Jo(t){this.$a.getSurveys(t)}aa(t){this.$a.cancelPendingSurvey(t)}ia(){return Ct}da(t){this.xa.kv.set({[g2]:t})}_a(t){this.xa.kv.set({[sm]:t})}wa(){this.xa.kv.remove(sm)}ka(){return!1}na(t,e,n){var r;if(t===bs.SENT&&(n==null||(r=n.properties)===null||r===void 0?void 0:r.$survey_completed)===!1)return"ignore";let s;return this.Jo(i=>{s=i.find(o=>o.id===e)}),!s||(function(i){var o;return PR(i)&&!!(!((o=i.conditions)===null||o===void 0||(o=o.events)===null||o===void 0)&&o.repeatedActivation)||i.schedule==="always"})(s)?t===bs.SHOWN?"consume":"ignore":t===bs.SHOWN?"persist":t===bs.DISMISSED||t===bs.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}};const nb=(t,e)=>t!=null&&t.then?t.then(e):e(t),gu="SDK is not enabled or survey functionality is not yet loaded",q8="Disabled. Not loading surveys.";var GV=class{constructor(t){this.Ta=t,this.name="surveys",this._surveyEventReceiver=null,this._surveyManager=null,this.Ia=!1,this.Ma=!1,this.Ea=[],this.Pa=[],this.Ra=null,this.Aa=null,this.Ci=!1,this.Fa=new Set,this.onRemoteConfig=e=>{if(this.Ci||this.Ar.disableSurveys)return;if(!e.ok)return this.Ma=!0,this.Oa({isLoaded:!1,error:"Remote config unavailable. Not loading surveys."}),Ct.warn("Remote config unavailable. Not loading surveys.");const n=e.config.surveys;if(Xe(n))return Ct.warn("Flags not loaded yet. Not loading surveys.");this.Da=Hr(n)?n:n.length>0,Ct.info(`flags response received, isSurveysEnabled: ${this.Da}`),this.loadIfEnabled()},this.Oa=e=>{this.Pa.slice().forEach(n=>this.La(n,e))}}setup(t){if(!this.Ci)return this.Na=t,nb(t.kv.initialize(),()=>{if(this.Na!==t||this.Ci)return;this.Na=void 0,this.xa=t;const e=t.onRemoteConfig(this.onRemoteConfig);this.Ci?e.dispose():(this.qa=e,this.loadIfEnabled())})}dispose(){var t,e,n,r,s;this.Ci||(this.Ci=!0,this.Na=void 0,this.xa=void 0,(t=this.qa)===null||t===void 0||t.dispose(),this.qa=void 0,(e=this._surveyEventReceiver)===null||e===void 0||e.dispose(),this._surveyEventReceiver=null,(n=this._surveyManager)===null||n===void 0||(r=n.dispose)===null||r===void 0||r.call(n),this._surveyManager=null,this.Ea=[],this.Pa.forEach(i=>{i.active=!1}),this.Pa=[],(s=this.ja)===null||s===void 0||s.call(this),this.ja=void 0,this.Ra=null,this.Fa.forEach(i=>clearTimeout(i)),this.Fa.clear())}get Ar(){return this.Ta.get()}getRenderContext(){if(!this.xa)return;const t=this;return{client:this.xa,get config(){return t.Ar},surveys:t}}initialize(){this.loadIfEnabled()}reset(){var t,e;(t=this._surveyManager)===null||t===void 0||(e=t.clearInMemoryInProgressSurveyState)===null||e===void 0||e.call(t);try{var n;(n=this._surveyEventReceiver)===null||n===void 0||n.reset(),localStorage.removeItem("lastSeenSurveyDate");const r=[];for(let s=0;s<localStorage.length;s++){const i=localStorage.key(s);(i!=null&&i.startsWith("seenSurvey_")||i!=null&&i.startsWith("inProgressSurvey_"))&&r.push(i)}r.forEach(s=>localStorage.removeItem(s))}catch{}this.Oa()}loadIfEnabled(){if(this.Ci||!this.xa)return;const t=this.Ar;if(this._surveyManager)return;if(this.Ia)return void Ct.info("Already initializing surveys, skipping...");if(t.disableSurveys)return void Ct.info(q8);if(t.cookielessMode&&this.xa.isOptedOut)return void Ct.info("Not loading surveys in cookieless mode without consent.");const e=this.Ta.getExtensions();if(!e)return void this.Ba("PostHog Extensions not found.");if(ae(this.Da)&&!t.advancedEnableSurveys)return;const n=this.Da||t.advancedEnableSurveys;this.Ia=!0,this.Ma=!1;try{const r=e.generateSurveys;if(r)return this.za(r,n),void(this.Ia=!1);const s=e.loadExternalDependency;if(!s)return this.Ba(Hx),void(this.Ia=!1);s(i=>{try{if(this.Ci)return;const o=this.Ta.getExtensions();i||!(o!=null&&o.generateSurveys)?this.Ba("Could not load surveys script",i):this.za(o.generateSurveys,n)}finally{this.Ia=!1}})}catch(r){throw this.Ia=!1,this.Ba("Error initializing surveys",r),r}}za(t,e){var n;if(this.Ci)return;this._surveyManager=t(e),this._surveyEventReceiver=this.Ha(this.xa,this.Oa);const r=(n=this.xa)===null||n===void 0?void 0:n.kv.get(Nf);r&&this.Ua(r),Ct.info("Surveys loaded successfully"),this.Wa(),this.Oa(),this.Va({isLoaded:!0})}Ha(t,e){return new qV(t,this,void 0,e)}Ba(t,e){this.Ma=!0,Ct.error(t,e),this.Oa({isLoaded:!1,error:t}),this.Va({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Ea.push(t),this._surveyManager&&this.Va({isLoaded:!0}),()=>{this.Ea=this.Ea.filter(e=>e!==t)}}getSurveys(t,e=!1){if(this.Ci)return;const n=this.xa;if(!n)return t([],{isLoaded:!1,error:gu});if(this.Ar.disableSurveys)return Ct.info(q8),t([]);const r=n.kv.get(Nf);if(r&&!e)return t(r,{isLoaded:!0}),void(this.Ga()&&this.getSurveys(()=>{},!0));if(this.Ra)return void this.Ra.then(({surveys:o,context:l})=>{this.Ci||t(o,l)}).catch(o=>Ct.error("Error in survey callback",o));const s=n.sendRequest("/api/surveys/",{method:"GET",query:{token:n.projectToken},sentAt:"query",timeoutMs:this.Ar.requestTimeoutMs}).then(o=>{try{return this.Qa(n,o)}catch(l){return Ct.error("Error processing surveys response",l),this.Qa(n,{statusCode:0,error:l})}},o=>this.Qa(n,{statusCode:0,error:o}));this.Ra=s;const i=()=>{this.Ra===s&&(this.Ra=null)};s.then(o=>{i(),this.Ci||(this.Oa(o.context),t(o.surveys,o.context))},i).catch(o=>Ct.error("Error in survey callback",o))}Qa(t,e){if(this.Ci)return{surveys:[],context:{isLoaded:!1,error:gu}};const n=e.statusCode;if(n!==200||!e.json){const s=`Surveys API could not be loaded, status: ${n}`;return n!==0?Ct.error(s):e.error||Ct.warn(s),this.Aa=Date.now(),{surveys:[],context:{isLoaded:!1,error:s}}}this.Aa=null;const r=e.json.surveys||[];return t.kv.set({[Nf]:r,[Um]:Date.now()}),this.Ua(r),{surveys:r,context:{isLoaded:!0}}}Ua(t){const e=t.filter(n=>(function(r){return!(!r.start_date||r.end_date)})(n)&&(PR(n)||(function(r){var s;return!!(!((s=r.conditions)===null||s===void 0||(s=s.actions)===null||s===void 0||(s=s.values)===null||s===void 0)&&s.length)})(n)));this.Za(e)}Za(t){var e;(e=this._surveyEventReceiver)===null||e===void 0||e.replace(t)}Ga(){return this.Ja()&&!this.Ra&&!this.Ka()}Ja(){var t;const e=(t=this.xa)===null||t===void 0?void 0:t.kv.get(Um);return Cn(e)&&Date.now()-e>3e5}Ka(){return Cn(this.Aa)&&3e5>Date.now()-this.Aa}markSurveyAsSeen(t,e){var n;const r={id:t,current_iteration:(n=e==null?void 0:e.iteration)!==null&&n!==void 0?n:null};RR(r);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}this.Oa()}Va(t){for(const e of this.Ea){if(this.Ci)return;try{t.isLoaded?this.getSurveys(e):e([],t)}catch(n){Ct.error("Error in survey callback",n)}}}getActiveMatchingSurveys(t,e=!1){if(!Xe(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Ct.warn("init was not called")}onActiveMatchingSurveysChanged(t){var e;if(this.Ci)return()=>{};const n={callback:t,active:!0,revision:0};this.Pa.push(n),this.Wa();const r=(e=this.xa)===null||e===void 0?void 0:e.kv.get(Nf);return this.Ar.disableSurveys||!this._surveyManager&&this.Ma&&!this.Ia||!r&&!Xe(this.Aa)&&!this.Ra?this.La(n,{isLoaded:!1}):this._surveyManager&&this.La(n),()=>{var s;n.active=!1,this.Pa=this.Pa.filter(i=>i!==n),this.Pa.length===0&&((s=this.ja)===null||s===void 0||s.call(this),this.ja=void 0)}}Wa(){var t,e,n;this._surveyManager&&this.Pa.length>0&&((t=this.ja)!==null&&t!==void 0||(this.ja=(e=(n=this.Ta).onMatchingConditionsChanged)===null||e===void 0?void 0:e.call(n,this.Oa)))}La(t,e){if(this.Ci||!t.active)return;const n=++t.revision,r=s=>{if(!this.Ci&&t.active&&n===t.revision)try{const i=e??{isLoaded:!0},o=JSON.stringify([s,i]);if(o===t.lastResult)return;t.lastResult=o,t.callback(s,i)}catch(i){Ct.error("Error in active matching surveys callback",i)}};try{e&&!e.isLoaded?r([]):this.getActiveMatchingSurveys(r)}catch(s){Ct.error("Error in active matching surveys callback",s)}}Xa(t){let e=null;return this.getSurveys(n=>{var r;e=(r=n.find(s=>s.id===t))!==null&&r!==void 0?r:null}),e}Ya(t){if(Xe(this._surveyManager))return{eligible:!1,reason:gu};const e=typeof t=="string"?this.Xa(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}tl(t){var e;if(!(!((e=this.xa)===null||e===void 0)&&e.canCapture))return{eligible:!1,reason:"PostHog is not capturing, so a survey response cannot be recorded"};if(Xe(this._surveyManager))return{eligible:!1,reason:gu};const n=typeof t=="string"?this.Xa(t):t;return n?this._surveyManager.checkSurveyRenderability(n):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(Xe(this._surveyManager))return Ct.warn("init was not called"),{visible:!1,disabledReason:gu};const e=this.tl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return Xe(this._surveyManager)?(Ct.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:gu})):new Promise(n=>{this.getSurveys(r=>{var s;const i=(s=r.find(o=>o.id===t))!==null&&s!==void 0?s:null;if(i){const o=this.tl(i);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})},e)})}renderSurvey(t,e,n){var r,s,i;if(!(!((r=this.xa)===null||r===void 0)&&r.canCapture))return;if(Xe(this._surveyManager))return void Ct.warn("init was not called");const o=typeof t=="string"?this.Xa(t):t;if(!(o!=null&&o.id))return void Ct.warn("Survey not found");if(!yV.includes(o.type))return void Ct.warn(`Surveys of type ${o.type} cannot be rendered in the app`);const l=(s=typeof document>"u"?void 0:document)===null||s===void 0?void 0:s.querySelector(e);if(l){if(!((i=o.appearance)===null||i===void 0)&&i.surveyPopupDelaySeconds){Ct.info(`Rendering survey ${o.id} with delay of ${o.appearance.surveyPopupDelaySeconds} seconds`);const u=setTimeout(()=>{var d,f,h;this.Fa.delete(u),!this.Ci&&(!((d=this.xa)===null||d===void 0)&&d.canCapture)&&(Ct.info(`Rendering survey ${o.id} with delay of ${(f=o.appearance)===null||f===void 0?void 0:f.surveyPopupDelaySeconds} seconds`),(h=this._surveyManager)===null||h===void 0||h.renderSurvey(o,l,n),Ct.info(`Survey ${o.id} rendered`))},1e3*o.appearance.surveyPopupDelaySeconds);return void this.Fa.add(u)}this._surveyManager.renderSurvey(o,l,n)}else Ct.warn("Survey element not found")}displaySurvey(t,e){var n,r;if(!(!((n=this.xa)===null||n===void 0)&&n.canCapture))return;if(Xe(this._surveyManager))return void Ct.warn("init was not called");const s=this.Xa(t);if(!s)return void Ct.warn("Survey not found");let i=s;if(!((r=s.appearance)===null||r===void 0)&&r.surveyPopupDelaySeconds&&e.ignoreDelay&&(i=$($({},s),{},{appearance:$($({},s.appearance),{},{surveyPopupDelaySeconds:0})})),e.displayType!==A2.Popover&&e.initialResponses&&Ct.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){const o=this.Ya(s);if(!o.eligible)return void Ct.warn("Survey is not eligible to be displayed: ",o.reason)}e.displayType!==A2.Inline?this._surveyManager.handlePopoverSurvey(i,e):this.renderSurvey(i,e.selector,e.properties)}cancelPendingSurvey(t){Xe(this._surveyManager)?Ct.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t,e;(t=this._surveyManager)===null||t===void 0||(e=t.handlePageUnload)===null||e===void 0||e.call(t)}},KV=class{constructor(t){this._instance=t}get(){var t,e,n,r;const s=(t=this._instance)===null||t===void 0?void 0:t.config;return{disableSurveys:!!(s!=null&&s.disable_surveys),cookielessMode:!!(s!=null&&s.cookieless_mode),advancedEnableSurveys:!!(s!=null&&s.advanced_enable_surveys),requestTimeoutMs:(e=s==null?void 0:s.surveys_request_timeout_ms)!==null&&e!==void 0?e:1e4,prefillFromUrl:!!(!(s==null||(n=s.surveys)===null||n===void 0)&&n.prefillFromUrl),automaticDisplay:!(s!=null&&s.disable_surveys_automatic_display),featureFlagEvaluation:!(s!=null&&s.advanced_disable_feature_flags),overrideLanguage:s==null?void 0:s.override_display_language,prepareStylesheet:s==null?void 0:s.prepare_external_dependency_stylesheet,get_current_url:s==null?void 0:s.get_current_url,uiHost:(r=this._instance)===null||r===void 0||(r=r.requestRouter)===null||r===void 0?void 0:r.endpointFor("ui","")}}getExtensions(){const t=qe==null?void 0:qe.__PosthogExtensions__;if(!t||!this._instance)return;const e=this._instance,{generateSurveys:n,loadExternalDependency:r}=t;return{generateSurveys:n?s=>n(e,s):void 0,loadExternalDependency:r?s=>r(e,"surveys",s):void 0}}onMatchingConditionsChanged(t){var e,n;const r=(e=this._instance)===null||e===void 0?void 0:e._addCaptureHook(l=>{l!=="$pageview"&&l!==bs.SHOWN&&l!==bs.DISMISSED&&l!==bs.SENT||t()}),s=()=>t();_t(oe,"PHSurveyShown",s);let i=!1;const o=(n=this._instance)===null||n===void 0?void 0:n.onFeatureFlags(()=>{i&&t()});return i=!0,()=>{i=!1,r==null||r(),o==null||o(),oe==null||oe.removeEventListener("PHSurveyShown",s)}}};const YV=oe!=null&&oe.location?qm(oe.location.hash,"__posthog")||qm(location.hash,"state"):null,G8="_postHogToolbarParams",K8=an("[Toolbar]"),Y8=an("[FeatureFlags]"),Ol=an("[FeatureFlags]",{debugEnabled:!0}),Zy=`" failed. Feature flags didn't load in time.`,XV=[502,504],X8=["click","keydown","wheel","touchstart","pointerdown"],Q8="connection_error",J8=t=>{const e={};for(let n=0;t.length>n;n++)e[t[n]]=!0;return e},eE=t=>{const e={};for(const[n,r]of am(t||{}))r&&(e[n]=r);return e};var QV=class{constructor(t){this.name="featureFlags",this.yd=!1,this.featureFlagEventHandlers=[],this.$=Y8,this.bd={},this._d={},this.wd=[],this.kd=new Set,this.Sd=new Set,this.xd=!1,this.$d=!1,this.Cd=0,this.Td=!1,this.Id=!1,this.Md=!1,this.Ed=!1,this.Pd=!1,this.Rd=0,this.Ad=!1,this.rn=()=>{const e=this.Fd();this.Rd=0,e&&this.reloadFeatureFlags()},this.Od=()=>{var e,n;const r=this.Dd,s=(e=this.Ld)!==null&&e!==void 0?e:r;ae(r)||ae(s)||this.Ar.remoteRequestsDisabled||!this.Nd||this.Nd.visibilityState==="hidden"||Date.now()-((n=this.qd)!==null&&n!==void 0?n:0)<s||(this.Ld=this.Ad||!this.Ar.idleRefreshBackoff?r:Math.min(2*s,36e5),this.Ad=!1,this.reloadFeatureFlags(),this.jd())},this.Bd=()=>{this.Ad&&this.Ld===this.Dd||this.zd()},this.sn=()=>{var e;((e=this.Nd)===null||e===void 0?void 0:e.visibilityState)==="visible"&&this.zd()},this.Ta=t}get Hd(){}Ud(){this.xa&&this.Wd()}setup(t){try{this.Vd=typeof window>"u"?void 0:window,this.Nd=typeof document>"u"?void 0:document}catch{this.Vd=void 0,this.Nd=void 0}return this.Na=t,this.$=t.logger.createLogger("[FeatureFlags]"),nb(t.kv.initialize(),()=>{this.Na===t&&(this.Na=void 0,this.xa=t,this.Gd(t))})}Gd(t){var e;if(this.xa===t)return this.Vd&&_t(this.Vd,"online",this.rn),this.Wd(),this.Qd=t.registerDynamicEventProperties(()=>this.Zd()?this.bd:this._d),this.Jd=(e=this.Hd)===null||e===void 0?void 0:e.onCrossTabFeatureFlagChange(()=>{this.Kd(),this.Xd(),this.Yd()}),this.Xd(),this.initialize()}zd(){this.Ad=!0,this.Ld=this.Dd,this.Od()}Wd(){var t;const e=this.Ar.refreshIntervalMs,n=!this.Ar.remoteRequestsDisabled&&this.Nd&&!ae(e)&&e>0?e:void 0;this.Ar.idleRefreshBackoff||(this.Ld=n),n!==this.Dd&&(this.tv(),ae(n)||(this.Dd=n,this.Ld=n,this.jd(),!((t=this.Nd)===null||t===void 0)&&t.addEventListener&&(_t(this.Nd,Du,this.sn),Au(X8,r=>{_t(this.Nd,r,this.Bd,{capture:!0})}))))}jd(){ae(this.Dd)||(ae(this.ev)||clearInterval(this.ev),this.qd=Date.now(),this.ev=setInterval(this.Od,this.Dd))}tv(){var t,e;ae(this.ev)||(clearInterval(this.ev),this.ev=void 0,(t=this.Nd)===null||t===void 0||(e=t.removeEventListener)===null||e===void 0||e.call(t,"visibilitychange",this.sn),Au(X8,n=>{var r,s;(r=this.Nd)===null||r===void 0||(s=r.removeEventListener)===null||s===void 0||s.call(r,n,this.Bd,{capture:!0})})),this.Dd=void 0,this.Ld=void 0,this.Ad=!1,this.qd=void 0}destroy(){this.iv()}dispose(){this.iv()}iv(){var t,e,n;this.tv(),this.Cd++,this.Id=!1,this.Na=void 0,this.nv(this.kd,"cancelled"),this.nv(this.Sd,"cancelled"),this.xa&&(this.sv(),(t=this.Qd)===null||t===void 0||t.dispose(),this.Qd=void 0,(e=this.Jd)===null||e===void 0||e.call(this),this.Jd=void 0,this.wd=[],(n=this.Vd)===null||n===void 0||n.removeEventListener("online",this.rn),this.xa=void 0)}get Ar(){return this.Ta.get()}rv(t){var e;return this.ov&&t in this.ov?this.ov[t]:(e=this.xa)===null||e===void 0?void 0:e.kv.get(t)}Kd(){return!!this.ov&&(this.ov=void 0,!0)}av(){var t;return!ae((t=this.xa)===null||t===void 0?void 0:t.kv.get("$enabled_feature_flags"))&&this.Kd()}At(t){this.lv(()=>{var e;return(e=this.xa)===null||e===void 0?void 0:e.kv.set(t)})}uv(t,e,n){if(!this.Hd||!t.$enabled_feature_flags)return;const r=this.rv("$enabled_feature_flags")||{},s=t.$enabled_feature_flags||{},i=e.flags||e.featureFlags,o=e.flags?Object.entries(e.flags).filter(([,x])=>!(x!=null&&x.failed)).map(([x])=>x):[],l=!!e.errorsWhileComputingFlags&&!!e.flags,u=l?o:n&&!ze(i)?Object.keys(i||{}):Array.from(new Set([...Object.keys(r),...Object.keys(s)])),d=this.rv("$feature_flag_payloads")||{},f=t.$feature_flag_payloads||{},h=l||n?u:Array.from(new Set([...Object.keys(d),...Object.keys(f)])),m=!l&&!n,v=!!m||u,w=!!m||h,_={[jo]:v,[wi]:v,[Fa]:w};t.$feature_flag_details&&(_[lc]=v);for(const x of[cc,Ba,Zf])ae(t[x])||(_[x]=!0);this.Hd.markCrossTabFeatureFlagChanges(_)}Pt(t){this.lv(()=>{var e;return(e=this.xa)===null||e===void 0?void 0:e.kv.remove(t)})}lv(t){try{t()}catch(e){this.$.error("Failed to update feature flag persistence",e)}}Xd(){const t={};for(const r of[jo,Fa,cc,Di]){const s=this.rv(r);ae(s)||(t[r]=s)}this.bd=t;const e=$({},t),n=this.rv(wi);if(n)for(const[r,s]of Object.entries(n))e[`$feature/${r}`]=s;this._d=e}Zd(){const t=this.Ar.cacheTtlMs;if(!t||0>=t)return!1;const e=this.rv(Ba);return typeof e!="number"||Date.now()-e>t}hv(){return!!this.Zd()&&(this.Pd||this.$d||(this.Pd=!0,this.$.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}dv(){const t=this.Ar.evaluationContexts;return t!=null&&t.length?t.filter(e=>{const n=e&&typeof e=="string"&&e.trim().length>0;return n||this.$.error("Invalid evaluation context found:",e,"Expected non-empty string"),n}):[]}vv(){const t=this.Ar.flagKeys;if(!ae(t))return t.filter(e=>{const n=e&&typeof e=="string"&&e.trim().length>0;return n||this.$.error("Invalid flag key found:",e,"Expected non-empty string"),n})}initialize(){var t,e;const n=this.Ar,r=(t=(e=n.bootstrap)===null||e===void 0?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(r).length){var s,i;const o=(s=(i=n.bootstrap)===null||i===void 0?void 0:i.featureFlagPayloads)!==null&&s!==void 0?s:{},l=Object.keys(r).filter(d=>!ae(r[d])).reduce((d,f)=>(d[f]=r[f],d),{}),u=Object.keys(o).filter(d=>l[d]).reduce((d,f)=>(d[f]=o[f],d),{});return this.fv({featureFlags:l,featureFlagPayloads:u},void 0,{persist:!1})}}updateFlags(t,e,n){var r,s;const i=n!=null&&n.merge&&(r=this.rv("$enabled_feature_flags"))!==null&&r!==void 0?r:{},o=n!=null&&n.merge&&(s=this.rv("$feature_flag_payloads"))!==null&&s!==void 0?s:{},l=$($({},i),t),u=$($({},o),e),d={};for(const[f,h]of Object.entries(l))d[f]={key:f,enabled:Hk(h),variant:zk(h),reason:void 0,metadata:ae(u==null?void 0:u[f])?void 0:{id:0,version:void 0,description:void 0,payload:u[f]}};this.fv({flags:d})}get hasLoadedFlags(){return this.xd}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){const t=this.rv(lc),e=this.rv(Di),n=this.rv(Wl);if(!n&&!e)return t||{};const r=en({},t||{}),s=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(const l of s){var i,o;const u=r[l],d=e==null?void 0:e[l],f=ae(d)?(i=u==null?void 0:u.enabled)!==null&&i!==void 0&&i:!!d,h=ae(d)?u==null?void 0:u.variant:typeof d=="string"?d:void 0,m=n==null?void 0:n[l],v=$($({},u),{},{enabled:f,variant:f?h??(u==null?void 0:u.variant):void 0});f!==(u==null?void 0:u.enabled)&&(v.original_enabled=u==null?void 0:u.enabled),h!==(u==null?void 0:u.variant)&&(v.original_variant=u==null?void 0:u.variant),m&&(v.metadata=$($({},u==null?void 0:u.metadata),{},{payload:m,original_payload:u==null||(o=u.metadata)===null||o===void 0?void 0:o.payload})),r[l]=v}return this.yd||(this.$.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:r}),this.yd=!0),r}getAllFeatureFlags(){const t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map(n=>{const r=t[n];return{key:n,enabled:Hk(r),variant:zk(r),payload:Vk(e[n])}})}getFlagVariants(){const t=this.rv(wi),e=this.rv(Di);if(!e)return t||{};const n=en({},t||{}),r=Object.keys(e);for(let s=0;r.length>s;s++)n[r[s]]=e[r[s]];return this.yd||(this.$.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.yd=!0),n}getFlagPayloads(){const t=this.rv(Fa),e=this.rv(Wl);if(!e)return t||{};const n=en({},t||{}),r=Object.keys(e);for(let s=0;r.length>s;s++)n[r[s]]=e[r[s]];return this.yd||(this.$.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.yd=!0),n}reloadFeatureFlags(){this.Td||this.Ar.featureFlagsDisabled||this.Fd()||(this.Md&&this.$.warn("reloadFeatureFlags() was called inside an onFeatureFlags callback. This callback also runs when flags change in other tabs, so this can cause a request loop."),this.$d&&(this.Id=!0),this.pv||(this.wd.slice().forEach(t=>{try{t()}catch(e){this.$.error("Error while running feature flags reloading callback",e)}}),this.pv=setTimeout(()=>{this.gv()},5)))}reloadFeatureFlagsAsync(){return!this.xa||this.Td||this.Ar.featureFlagsDisabled||this.Ar.remoteRequestsDisabled||this.Fd()?Promise.resolve({status:"skipped"}):new Promise(t=>{this.kd.add(t),this.reloadFeatureFlags()})}nv(t,e){t.forEach(n=>n({status:e})),t.clear()}sv(){clearTimeout(this.pv),this.pv=void 0}onReloading(t){return this.wd.push(t),()=>{this.wd=this.wd.filter(e=>e!==t)}}ensureFlagsLoaded(){this.xd||this.$d||this.pv||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this.Td=t}resetFlagCallReported(){this.Pt($o)}gv(t){var e;this.sv();const n=this.xa;if(!n||this.Ar.remoteRequestsDisabled||this.Fd())return void this.nv(this.kd,"skipped");if(this.$d)return void(this.Id=!0);const r={token:n.projectToken,distinct_id:n.distinctId,groups:n.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:$($($({},n.initialPersonProperties),this.rv("$stored_person_properties")||{}),{},{$lib:n.library.name,$lib_version:n.library.version}),group_properties:this.rv(ja),timezone:YT()};ae(n.deviceId)||(r.$device_id=n.deviceId),(t!=null&&t.disableFlags||this.Ar.featureFlagsDisabled)&&(r.disable_flags=!0);const s=this.dv();s.length&&(r.evaluation_contexts=s);const i=this.vv();ae(i)||(r.flag_keys=i);const o=this.Ar.onlyEvaluateSurveyFeatureFlags,l="/flags/?v=2"+(o?"&only_evaluate_survey_feature_flags=true":""),u=this.Cd,d=this.kd;this.kd=new Set,this.Sd=d,this.$d=!0;const f=()=>{this.Id&&(this.Id=!1,this.gv())},h=x=>{var b,k;const C=(b=x.json)!==null&&b!==void 0?b:{},P=x.statusCode!==200;if(this.$d=!1,u!==this.Cd)return void f();if(this.mv(x.statusCode),P||this.Id||(this.$anon_distinct_id=void 0),r.disable_flags&&!this.Id)return void this.nv(d,"skipped");this.Ed=!P;const T=[];x.error?T.push(x.error instanceof Error&&x.error.name==="AbortError"?"timeout":x.error instanceof Error?Q8:"unknown_error"):x.statusCode!==200&&T.push(`api_error_${x.statusCode}`),C.errorsWhileComputingFlags&&T.push("errors_while_computing_flags");const M=!!(!((k=C.quotaLimited)===null||k===void 0)&&k.includes("feature_flags"));M&&T.push("quota_limited"),this.At({[mh]:T}),M?this.$.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."):r.disable_flags||this.fv(C,P,{partialResponse:o}),this.nv(d,r.disable_flags?"skipped":T.length||!C.flags&&!C.featureFlags?"error":"loaded"),f()},m=x=>{this.$d=!1,u===this.Cd&&(this.At({[mh]:[Q8]}),this.$.error("Feature flag request failed",x),this.av()&&this.Yd(!0),this.nv(d,"error")),f()};let v=(e=this.Ar.requestMaxRetries)!==null&&e!==void 0?e:1;const w=()=>v>0&&u===this.Cd,_=()=>{if(u!==this.Cd||!this.xa||this.Ar.remoteRequestsDisabled)return this.$d=!1,this.nv(d,"skipped"),void f();try{n.sendRequest(l,{target:"flags",method:"POST",body:r,compression:this.Ar.compression,sentAt:"body",timeoutMs:this.Ar.requestTimeoutMs}).then(x=>{if((b=>XV.includes(b.statusCode)||(k=>k.statusCode===0&&k.error instanceof Error&&k.error.name==="AbortError")(b))(x)&&w())return v--,void setTimeout(_,500);h(x)}).catch(m)}catch(x){m(x)}};_()}Fd(){return QT(this.Rd,3)}mv(t){this.Rd=JT(t,this.Rd,3,()=>this.$.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes."))}getFeatureFlag(t,e={}){var n;if(e.fresh&&!this.Ed)return;if(!(this.xd||this.getFlags()&&this.getFlags().length>0))return void this.$.warn('getFeatureFlag for key "'+t+Zy);if(this.hv())return;const r=this.getFeatureFlagResult(t,e);return(n=r==null?void 0:r.variant)!==null&&n!==void 0?n:r==null?void 0:r.enabled}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){const e=this.getFeatureFlagResult(t,{send_event:!1});return e==null?void 0:e.payload}getFeatureFlagResult(t,e={}){if(e.fresh&&!this.Ed)return;if(!(this.xd||this.getFlags()&&this.getFlags().length>0))return void this.$.warn('getFeatureFlagResult for key "'+t+Zy);if(this.hv())return;const n=this.getFlagVariants(),r=t in n,s=n[t],i=this.getFlagPayloads()[t],o=String(s),l=this.rv("$feature_flag_request_id")||void 0,u=this.rv("$feature_flag_evaluated_at")||void 0;let d,f=this.rv("$flag_call_reported")||{};if(this.Ar.deduplicateCallsPerSession){var h;const F=(h=this.xa)===null||h===void 0||(h=h.session)===null||h===void 0?void 0:h.sessionId,N=this.rv(Lf);F&&F!==N&&(f={},d=F)}if(!e.send_event&&"send_event"in e)d&&this.At({[$o]:f,[Lf]:d});else{var m,v;const F=(m=this.xa)===null||m===void 0?void 0:m.canCapture;if(!F&&Object.keys(f).length>0&&(f={},this.At({[$o]:f})),F&&!(!((v=f[t])===null||v===void 0)&&v.includes(o))){var w,_,x,b,k,C,P,T,M,I,R,L,j;ze(f[t])?f[t].push(o):f[t]=[o],this.At($({[$o]:f},d?{[Lf]:d}:{}));const N=this.getFeatureFlagDetails(t),q=[...(w=this.rv("$feature_flag_errors"))!==null&&w!==void 0?w:[]];ae(s)&&q.push("flag_missing");const W={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:i??null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:(_=(x=this.Ar.bootstrap)===null||x===void 0||(x=x.featureFlags)===null||x===void 0?void 0:x[t])!==null&&_!==void 0?_:null,$feature_flag_bootstrapped_payload:(b=(k=this.Ar.bootstrap)===null||k===void 0||(k=k.featureFlagPayloads)===null||k===void 0?void 0:k[t])!==null&&b!==void 0?b:null,$used_bootstrap_value:!this.Ed};ae(N==null||(C=N.metadata)===null||C===void 0?void 0:C.has_experiment)||(W.$feature_flag_has_experiment=N.metadata.has_experiment),ae(N==null||(P=N.metadata)===null||P===void 0?void 0:P.version)||(W.$feature_flag_version=N.metadata.version);const Y=(T=N==null||(M=N.reason)===null||M===void 0?void 0:M.description)!==null&&T!==void 0?T:N==null||(I=N.reason)===null||I===void 0?void 0:I.code;Y&&(W.$feature_flag_reason=Y),!(N==null||(R=N.metadata)===null||R===void 0)&&R.id&&(W.$feature_flag_id=N.metadata.id),ae(N==null?void 0:N.original_variant)&&ae(N==null?void 0:N.original_enabled)||(W.$feature_flag_original_response=ae(N.original_variant)?N.original_enabled:N.original_variant),!(N==null||(L=N.metadata)===null||L===void 0)&&L.original_payload&&(W.$feature_flag_original_payload=N==null||(j=N.metadata)===null||j===void 0?void 0:j.original_payload),q.length&&(W.$feature_flag_error=q.join(",")),this.yv(W)}else d&&this.At({[$o]:f,[Lf]:d})}return r?{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:Vk(i)}:void 0}yv(t){try{var e;(e=this.xa)===null||e===void 0||e.capture("$feature_flag_called",t)}catch(n){this.$.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.bv(t,e)}bv(t,e){var n=this;return Wt(function*(){const r=n.xa;if(!r)return;const s={distinct_id:r.distinctId,token:r.projectToken,person_properties:{$lib:r.library.name,$lib_version:r.library.version}},i=n.dv();i.length&&(s.evaluation_contexts=i);const o=n.vv();let l;ae(o)||(s.flag_keys=o);try{var u;const d=(u=(yield r.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:s,compression:n.Ar.compression,sentAt:"body",timeoutMs:n.Ar.requestTimeoutMs})).json)===null||u===void 0?void 0:u.featureFlagPayloads;l=(d==null?void 0:d[t])||void 0}catch(d){return void n.$.error("Remote config feature flag request failed",d)}try{e(l)}catch(d){n.$.error("Remote config feature flag callback failed",d)}})()}isFeatureEnabled(t,e={}){if(e.fresh&&!this.Ed)return e.defaultValue;if(!(this.xd||this.getFlags()&&this.getFlags().length>0))return this.$.warn('isFeatureEnabled for key "'+t+Zy),e.defaultValue;const n=this.getFeatureFlag(t,e);return ae(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(e=>e!==t)}receivedFeatureFlags(t,e,n){this.fv(t,e,n)}fv(t,e,n){if(!this.xa)return;this.xd=!0;const r=((s,i={},o={},l={},u,d=Y8)=>{const f=((C,P)=>{const T=C.flags;if(T){const M=Object.fromEntries(Object.keys(T).map(R=>{var L;return[R,(L=T[R].variant)!==null&&L!==void 0?L:T[R].enabled]})),I=Object.fromEntries(Object.keys(T).filter(R=>T[R].enabled).filter(R=>{var L;return!ae((L=T[R].metadata)===null||L===void 0?void 0:L.payload)}).map(R=>{var L;return[R,(L=T[R].metadata)===null||L===void 0?void 0:L.payload]}));return $($({},C),{},{featureFlags:M,featureFlagPayloads:I})}return C.featureFlags&&P.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),C})(s,d),h=f.flags,m=f.featureFlags,v=f.featureFlagPayloads;if(!m)return;const w=s.requestId,_=s.evaluatedAt;if(ze(m)){d.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");const C={};if(m)for(let P=0;m.length>P;P++)C[m[P]]=!0;return{[jo]:m,[wi]:C,[Zf]:!1}}let x=m,b=v,k=h;if(u!=null&&u.partialResponse){const C=Object.keys(x),P=b||{};x=$($({},i),x),b=$($({},o),P),C.forEach(T=>{T in P||b==null||delete b[T]}),k=$($({},l),k)}else if(s.errorsWhileComputingFlags)if(h){const C=new Set(Object.keys(h).filter(T=>{var M;return!(!((M=h[T])===null||M===void 0)&&M.failed)}));x=$($({},i),Object.fromEntries(Object.entries(x).filter(([T])=>C.has(T))));const P=Object.fromEntries(Object.entries(b||{}).filter(([T])=>C.has(T)));b=$($({},o),P),C.forEach(T=>{T in P||b==null||delete b[T]}),k=$($({},l),Object.fromEntries(Object.entries(k||{}).filter(([T])=>C.has(T))))}else x=$($({},i),x),b=$($({},o),b),k=$($({},l),k);return $($({[jo]:Object.keys(eE(x)),[wi]:x||{},[Fa]:b||{},[lc]:k||{},[Zf]:s.minimalFlagCalledEvents===!0},w?{[cc]:w}:{}),_?{[Ba]:_}:{})})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.$);if(r)if((n==null?void 0:n.persist)===!1){const s=!ae(this.xa.kv.get(wi));this.ov=r,s||this.At(r)}else this.Kd(),this.uv(r,t,!!(n!=null&&n.partialResponse)),this.At(r);else e&&this.av();e||(this.Pd=!1),this.Yd(e)}override(t,e=!1){this.$.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this._v(t)}_v(t){if(this.xa){if(t===!1)return this.Pt([Di,Wl]),this.Yd(),void Ol.info("All overrides cleared");if(ze(t))return this.At({[Di]:J8(t)}),this.Yd(),void Ol.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e;const n=t;this.yd=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);const r={},s=n.flags,i=n.payloads;return s&&(r[Di]=ze(s)?J8(s):s),i&&(r[Wl]=i),Object.keys(r).length&&this.At(r),s===!1&&i===!1?this.Pt([Di,Wl]):s===!1?this.Pt(Di):i===!1&&this.Pt(Wl),this.Yd(),s===!1?Ol.info("Flag overrides cleared"):s&&Ol.info("Flag overrides set",{flags:s}),void(i===!1?Ol.info("Payload overrides cleared"):i&&Ol.info("Payload overrides set",{payloads:i}))}if(t&&typeof t=="object")return this.At({[Di]:t}),this.Yd(),void Ol.info("Flag overrides set",{flags:t});this.$.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.$.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.xd){const{flags:e,flagVariants:n}=this.wv();try{t(e,n)}catch(r){this.$.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var r;const s=(this.rv("$early_access_features")||[]).find(d=>d.flagKey===t),i={[`$feature_enrollment/${t}`]:e},o={$feature_flag:t,$feature_enrollment:e,$set:i};s&&(o.$early_access_feature_name=s.name),n&&(o.$feature_enrollment_stage=n);const l=$($({},this.getFlagVariants()),{},{[t]:e});(r=this.Hd)===null||r===void 0||r.markCrossTabFeatureFlagChanges({$active_feature_flags:[t],$enabled_feature_flags:[t],$stored_person_properties:Object.keys(i)}),this.At({[jo]:Object.keys(eE(l)),[wi]:l,[$a]:$($({},this.rv("$stored_person_properties")||{}),i)}),this.Yd();try{var u;(u=this.xa)===null||u===void 0||u.capture("$feature_enrollment_update",o)}catch(d){this.$.error("Failed to capture early access feature enrollment",d)}}getEarlyAccessFeatures(t,e=!1,n){const r=this.rv(m2);!r||e?this.Sv(t,n):t(r)}Sv(t,e){var n=this;return Wt(function*(){const r=n.xa;if(!r)return;const s=e?`&${e.map(o=>`stage=${o}`).join("&")}`:"";let i;try{const o=yield r.sendRequest(`/api/early_access_features/?token=${r.projectToken}${s}`,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;i=o.json.earlyAccessFeatures,n.At({[m2]:i})}catch(o){return void n.$.error("Early access feature request failed",o)}try{t(i)}catch(o){n.$.error("Early access feature callback failed",o)}})()}wv(){const t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter(n=>e[n]),flagVariants:Object.keys(e).filter(n=>e[n]).reduce((n,r)=>(n[r]=e[r],n),{})}}Yd(t){this.Xd();const{flags:e,flagVariants:n}=this.wv(),r=this.Md;this.Md=!0,this.featureFlagEventHandlers.forEach(s=>{try{s(e,n,{errorsLoading:t})}catch(i){this.$.error("Error while running feature flags callback",i)}}),this.Md=r}setPersonPropertiesForFlags(t,e=!0){this.xv(t,e)}xv(t,e=!0){const n=this.rv("$stored_person_properties")||{},r=(t==null?void 0:t.$set)||(t!=null&&t.$set_once?{}:t),s=t==null?void 0:t.$set_once,i={};if(s)for(const o in s)({}).hasOwnProperty.call(s,o)&&(o in n||(i[o]=s[o]));this.At({[$a]:$($($({},n),i),r)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e=!0){const n=$({},this.rv("$stored_person_properties")||{});t.forEach(r=>{delete n[r]}),this.At({[$a]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t=!0){this.Pt($a),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e=!0){const n=this.rv("$stored_group_properties")||{},r=$({},n);for(const s of Object.keys(t))r[s]=$($({},n[s]),t[s]);this.At({[ja]:r}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){const e=this.rv("$stored_group_properties")||{};this.At({[ja]:$($({},e),{},{[t]:{}})})}else this.Pt(ja)}reset(){this.Cd++,this.nv(this.kd,"cancelled"),this.nv(this.Sd,"cancelled"),this.Id=!1,this.bd={},this._d={},this.ov=void 0,this.xd=!1,this.Td=!1,this.Ed=!1,this.$anon_distinct_id=void 0,this.sv(),this.yd=!1,this.Rd=0}};const tE=an("[FeatureFlags]");var JV=class{constructor(t,e=!1){this.$v=!1,this.update(t,e)}update(t,e){this.Cv=((n,r)=>{var s,i,o,l,u,d,f,h;return{bootstrap:{featureFlags:(s=(i=n.bootstrap)===null||i===void 0?void 0:i.featureFlags)!==null&&s!==void 0?s:void 0,featureFlagPayloads:(o=(l=n.bootstrap)===null||l===void 0?void 0:l.featureFlagPayloads)!==null&&o!==void 0?o:void 0},remoteRequestsDisabled:r,featureFlagsDisabled:!!n.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!n.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!n.advanced_feature_flags_dedup_per_session,cacheTtlMs:n.feature_flag_cache_ttl_ms,refreshIntervalMs:(u=n.remote_config_refresh_interval_ms)!==null&&u!==void 0?u:3e5,idleRefreshBackoff:ae(n.remote_config_refresh_interval_ms),requestTimeoutMs:n.feature_flag_request_timeout_ms,requestMaxRetries:Math.max(0,(d=n.feature_flag_request_max_retries)!==null&&d!==void 0?d:1),compression:n.disable_compression?void 0:"best-available",evaluationContexts:(f=(h=n.evaluation_contexts)!==null&&h!==void 0?h:n.evaluation_environments)!==null&&f!==void 0?f:[],flagKeys:ze(n.flag_keys)?n.flag_keys:void 0}})(t,e),!t.evaluation_environments||t.evaluation_contexts||this.$v||(tE.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.$v=!0),ae(t.flag_keys)||ze(t.flag_keys)||tE.error("Invalid flag_keys found:",t.flag_keys,"Expected array of non-empty strings")}get(){return this.Cv}};const nE=t=>Ed(t)&&(t.name==="RangeError"&&t.message.indexOf("Maximum call stack size exceeded")===0||t.name==="InternalError"&&t.message==="too much recursion"),fi=an("[Error tracking]"),N2="webkit-masked-url:",eH=[{value:"isolatedAPI.contexts.topHostname",exact:!1},{value:"No response from target",exact:!0}],tH=["chrome-extension://","moz-extension://","safari-extension:","safari-web-extension:",N2],nH=["__firefox__","__gCrWeb"],rE="Refusing to render web experiment since the viewer is a likely bot",rH={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>Xm(e,t),not_regex:(t,e)=>!Xm(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t},Zs=an("[Conversations]"),Ll="Conversations not available yet.";function sE(t,e){var n,r,s,i,o,l,u;const d=(n=t==null?void 0:t.flushIntervalMs)!==null&&n!==void 0?n:3e3,f=(r=t==null?void 0:t.maxBufferSize)!==null&&r!==void 0?r:100,h=e!=null&&e.consoleCapture?void 0:(s=t==null?void 0:t.maxLogsPerInterval)!==null&&s!==void 0?s:1e3,m=ae(h)?Math.max(f,2048):Math.max(f,h),v=$($({},(function(){let w="",_="";try{var x;const b="u">typeof globalThis?globalThis:"u">typeof window?window:void 0,k=b==null||(x=b.navigator)===null||x===void 0?void 0:x.userAgent;k&&([w,_]=B5(k))}catch{}return(function(b,k){const C=(function(P){if(P)return{}.hasOwnProperty.call(Gk,P)?Gk[P]:P})(b);return $($({},C?{"os.name":C}:{}),k?{"os.version":k}:{})})(w,_)})()),t==null?void 0:t.resourceAttributes);return{serviceName:(i=(o=v==null?void 0:v["service.name"])!==null&&o!==void 0?o:t==null?void 0:t.serviceName)!==null&&i!==void 0?i:e==null?void 0:e.serviceNameDefault,serviceVersion:(l=v==null?void 0:v["service.version"])!==null&&l!==void 0?l:t==null?void 0:t.serviceVersion,environment:(u=v==null?void 0:v["deployment.environment"])!==null&&u!==void 0?u:t==null?void 0:t.environment,resourceAttributes:v,beforeSend:t==null?void 0:t.beforeSend,flushIntervalMs:d,maxBufferSize:f,maxQueueSize:m,maxBatchRecordsPerPost:100,rateCapWindowMs:d,maxLogsPerInterval:h,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}}const sH=["debug","log","warn","error","info"],iH=t=>{for(;t!=null&&t.__rrweb_original__;)t=t.__rrweb_original__;return t},iE="console",DR="__posthogHandledLogsRequestError",qy=(t,e)=>{const n=t instanceof Error?t:new Error(e);return n[DR]=!0,n},oE=t=>!!t&&typeof t=="object"&&t[DR]===!0;var oH=class{get Tv(){return $($({},this.$),{},{error:(...t)=>{t.some(oE)||this.$.error(...t)}})}constructor(t,e){var n;this.Ta=t,this.Iv=e,this.name="logs",this.Mv=!1,this.Ev=!1,this.Pv=!1,this.$=an("[logs]"),this.Ju=[],this.Rv=[],this.Rd=0,this.Av=!1,this.Ci=!1,this.Fv=[],this.Ov=[],this.Dv=!1,this.Lv=!1,this.Nv=!1,this.qv=()=>{var r,s;this.Ci||(this.Rd=0,(r=this.jv)===null||r===void 0||r.onReconnect(),(s=this.Bv)===null||s===void 0||s.onReconnect())},this.Mv=!!(!((n=t.get())===null||n===void 0)&&n.captureConsoleLogs)}get zv(){return!0}Hv(){}Uv(){if(!this.Nv){try{this.Vd=typeof window>"u"?void 0:window}catch{this.Vd=void 0}this.Vd&&(_t(this.Vd,"online",this.qv),this.Nv=!0)}}Wv(t,e,n,r){this.Uv();const s=sE(this.Ta.get(),n);return[new K$(this.Vv(t,e),s,this.Tv,()=>this.Iv(),i=>i(),void 0,r),s]}Gv(){const t=this.Ta.get();var e;return this.jv&&this.Qv===t||((e=this.jv)===null||e===void 0||e.reset(),this.Qv=t,[this.jv,this.Zv]=this.Wv(()=>this.Ju,n=>{this.Ju=n})),this.jv}Jv(){const t=this.Ta.get();var e;return this.Bv&&this.Kv===t||((e=this.Bv)===null||e===void 0||e.reset(),this.Kv=t,[this.Bv,this.Xv]=this.Wv(()=>this.Rv,n=>{this.Rv=n},{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},iE)),this.Bv}setup(t){if(!this.Ci&&!this.Av)return this.Av=!0,this.xa=t,this.$=t.logger.createLogger("[logs]"),nb(t.kv.initialize(),()=>{this.Ci||this.Gd(t)})}Gd(t){var e;this.Uv(),!((e=this.Ta.get())===null||e===void 0)&&e.captureConsoleLogs&&(this.Mv=!0),(this.Mv||this.Ta.remoteConfigWillArrive&&t.kv.get(this.Ta.captureHintKey))&&this.Yv();let n=!1;const r=t.onRemoteConfig(s=>{var i;n=s.ok&&((i=s.config.logs)===null||i===void 0?void 0:i.captureConsoleLogs)===!0,this.onRemoteConfig(s)});this.Ci?r.dispose():(this.qa=r,n||this.loadIfEnabled())}dispose(){var t,e,n,r,s,i,o;this.Ci||(this.Ci=!0,this.tf(),(t=this.qa)===null||t===void 0||t.dispose(),this.qa=void 0,this.xa=void 0,this.Pv=!1,(e=this.Vd)===null||e===void 0||e.removeEventListener("online",this.qv),(n=this.ef)===null||n===void 0||n.call(this),this.ef=void 0,(r=this.jv)===null||r===void 0||r.clearQueue(),(s=this.Bv)===null||s===void 0||s.clearQueue(),(i=this.jv)===null||i===void 0||i.reset(),(o=this.Bv)===null||o===void 0||o.reset())}onRemoteConfig(t){var e,n;if(this.Ci)return;const r=t.ok?(e=t.config.logs)===null||e===void 0?void 0:e.captureConsoleLogs:void 0;Xe(r)?this.if():((n=this.xa)===null||n===void 0||n.kv.set(this.Ta.captureHintKey,!!r),r?(this.Mv=!0,this.Ev||this.Yv(),this.loadIfEnabled()):this.if())}reset(){var t,e,n,r;this.tf(),(t=this.jv)===null||t===void 0||t.clearQueue(),this.Ju=[],(e=this.jv)===null||e===void 0||e.reset(),(n=this.Bv)===null||n===void 0||n.clearQueue(),this.Rv=[],(r=this.Bv)===null||r===void 0||r.reset(),this.Rd=0}captureLog(t){!this.Ci&&this.xa&&this.Gv().captureLog(t)}captureConsoleLog(t){!this.Ci&&this.xa&&this.Jv().captureLog(t)}captureBufferedConsoleLog(t,e,n){!this.Ci&&this.xa&&this.Jv().captureLog(t,{context:e,occurredAtMs:n})}md(){var t;this.tf(),(t=this.Bv)===null||t===void 0||t.clearQueue(),this.Rv=[]}if(){this.Mv||this.tf()}Yv(){var t;if(this.Dv||!(!((t=this.Vd)===null||t===void 0)&&t.console))return;const e=sE(this.Ta.get()).maxBufferSize;let n=!0;this.Ov.push(()=>{n=!1});for(const r of sH){let s;try{s=iH(this.Vd.console[r])}catch{continue}s&&this.Ov.push(cd(this.Vd.console,r,i=>{const o=(...l)=>{try{n&&this.nf(r,l,e)}catch{}return i.apply(this.Vd.console,l)};return o.__rrweb_original__=s,o}))}this.Dv=!0,this.sf=setTimeout(()=>{this.tf()},3e4)}nf(t,e,n){var r;if(this.Dv&&!this.Lv&&e.length!==0)if(!((r=this.xa)===null||r===void 0)&&r.canCapture){if(n>this.Fv.length){this.Lv=!0;try{this.Fv.push({level:t,args:e,occurredAtMs:Date.now(),context:this.Iv()})}finally{this.Lv=!1}}}else this.tf()}tf(){if(this.Fv=[],this.Dv){this.Dv=!1,this.sf&&(clearTimeout(this.sf),this.sf=void 0);for(const t of this.Ov)t();this.Ov=[]}}rf(){const t=this.Fv;return this.tf(),t}get logger(){return this.af||(this.af={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.af}flushLogs(t){this.xa&&(t?this.lf(t):(this.jv&&this.jv.flush().catch(e=>this.uf(e)),this.Bv&&this.Bv.flush().catch(e=>this.uf(e))))}flush(){var t=this;return Wt(function*(){var e,n;const r=(e=t.jv)===null||e===void 0?void 0:e.flush().catch(i=>t.uf(i)),s=(n=t.Bv)===null||n===void 0?void 0:n.flush().catch(i=>t.uf(i));yield r,yield s})()}uf(t){oE(t)||this.$.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.Ci||!this.Mv||this.Ev||this.Pv)return;const t=this.Hv();if(t){this.Pv=!0;try{t((e,n)=>{if(this.Pv=!1,!this.Ci&&this.Mv)if(e||!n)this.$.error("Could not load logs script",e),this.tf();else{const r=this.rf();this.ef=n.initialize(this.xa),this.Ev=!0,r.length>0&&n.replay(this.xa,r)}})}catch(e){throw this.Pv=!1,e}}else this.tf()}Vv(t,e){const n=this.xa;return{get isDisabled(){return!1},get optedOut(){return!n.canCapture},getPersistedProperty:r=>r===ji.LogsQueue?t():void 0,setPersistedProperty(r,s){r===ji.LogsQueue&&e(s??[])},js:r=>this.js(r),getLibraryId:()=>n.library.name,getLibraryVersion:()=>n.library.version}}js(t){return new Promise(e=>{if(QT(this.Rd,3))return void e({kind:"fatal",error:qy(void 0,"logs endpoint is unreachable, dropping batch")});let n=!1;const r=o=>{n||(n=!0,clearTimeout(s),e(o))},s=setTimeout(()=>{this.$.warn("Logs request timed out before receiving a response"),r({kind:"retry-later",error:qy(void 0,"logs request timed out")})},9e4),i=this.zv;this.xa.sendRequest("/i/v1/logs",{method:"POST",query:{token:this.xa.projectToken},body:t,compression:"best-available",timeoutMs:6e4}).then(o=>{var l;const u=o.statusCode;this.cf(u,i),u>=200&&300>u?r({kind:"ok"}):u===413?r({kind:"too-large"}):u!==0&&u!==408&&u!==429&&500>u?r({kind:"fatal",error:new Error(`logs request failed with status ${u}`)}):u===0?(o.error||this.$.warn("Logs request failed before receiving an HTTP response"),r({kind:"retry-later",error:qy(o.error,"logs request failed before receiving an HTTP response")})):r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error(`logs request failed with status ${u}`)})},o=>{r({kind:"retry-later",error:o})})})}cf(t,e){(t!==0||e)&&(this.Rd=JT(t,this.Rd,3,()=>this.$.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes.")))}lf(t){this.Ju.length>0&&this.hf(t,this.Ju,this.Zv,this.xa.library.name,e=>{this.Ju=e}),this.Rv.length>0&&this.hf(t,this.Rv,this.Xv,iE,e=>{this.Rv=e})}hf(t,e,n,r,s){if(e.length===0)return;const i=e.map(l=>l.record);s([]);const o=hT(i,fT(n,this.xa.library.name,this.xa.library.version),r,this.xa.library.version);this.xa.sendRequest("/i/v1/logs",{method:"POST",query:{token:this.xa.projectToken},body:o,compression:"best-available",transport:t,timeoutMs:6e4}).catch(l=>this.uf(l))}};const Qm=an("[NetworkMetrics]"),rb=()=>{var t;return!(oe==null||(t=oe.performance)===null||t===void 0)&&t.now?oe.performance.now():Date.now()},aH={"http:":80,"https:":443},lH=new Set(["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"]),jR=(t,e)=>{var n;const r=String(e);return{method:String(t).toUpperCase(),url:((n=qo(r))===null||n===void 0?void 0:n.href)||r}},D2=(t,e,n,r,s,i,o=!1)=>{try{var l,u;const d=s();if(!d)return;const f=n||void 0,h=rb()-r,m=qo(e.url);if(m&&m.protocol!=="http:"&&m.protocol!=="https:")return;const v={url:(m==null?void 0:m.href)||e.url,method:e.method},w=gn(d.name)?d.name(v):rt(d.name)?d.name:"http.client.request.duration";if(!w)return;const _=o&&!f?void 0:((b,k)=>b?400>b?void 0:String(b):(k==null?void 0:k.name)||"_OTHER")(f,i),x=$($($($($({},(b=>{const k=lH.has(b)?b:"_OTHER";return $({"http.request.method":k},k==="_OTHER"&&b!==k?{"http.request.method_original":b}:{})})(v.method)),m?(b=>{return{"server.address":b.hostname.startsWith("[")&&b.hostname.endsWith("]")?b.hostname.slice(1,-1):b.hostname,"server.port":Number(b.port)||aH[b.protocol],"url.scheme":b.protocol.slice(0,-1),"url.template":(k=b.pathname,k.split("/").map(C=>(P=>/^\d+$/.test(P)||P.length>=8&&/^[0-9a-f-]*\d[0-9a-f-]*$/i.test(P))(C)?":id":C).join("/"))};var k})(m):{}),f?{"http.response.status_code":f}:{}),_?{"error.type":_}:{}),(l=d.attributes)===null||l===void 0?void 0:l.call(d,v,{status:f,durationMs:h}));(u=t.metrics)===null||u===void 0||u.histogram(w,h,{unit:"ms",attributes:x})}catch(d){Qm.error("Failed to record network metric",d)}},$R=()=>{},cH=(t,e)=>gn(oe==null?void 0:oe.fetch)?cd(oe,"fetch",n=>function(...r){const s=rb(),i=n.apply(this,r);if(!e())return i;try{var o,l,u;const[d,f]=r,h=jR((o=(l=f==null?void 0:f.method)!==null&&l!==void 0?l:d==null?void 0:d.method)!==null&&o!==void 0?o:"GET",(u=d==null?void 0:d.url)!==null&&u!==void 0?u:d);return i.then(m=>(D2(t,h,m==null?void 0:m.status,s,e,void 0,!0),m),m=>{throw D2(t,h,void 0,s,e,m),m})}catch(d){return Qm.error("Failed to observe fetch",d),i}}):$R,uH=(t,e)=>{var n;const r=oe==null||(n=oe.XMLHttpRequest)===null||n===void 0?void 0:n.prototype;if(!r)return $R;const s=new WeakMap,i=cd(r,"open",l=>function(...u){try{pR.has(this)||s.set(this,jR(u[0],u[1]))}catch(d){Qm.error("Failed to observe XHR open",d)}return l.apply(this,u)}),o=cd(r,"send",l=>function(...u){let d;try{const f=s.get(this);if(f&&e()){const h=rb();d=()=>{this.removeEventListener("loadend",d),D2(t,f,this.status,h,e)},_t(this,"loadend",d)}}catch(f){Qm.error("Failed to observe XHR send",f)}try{return l.apply(this,u)}catch(f){throw d&&this.removeEventListener("loadend",d),f}});return()=>{i(),o()}},aE=new WeakMap,dH=new Set(["$comment","$defs","$id","$schema","additionalProperties","default","definitions","deprecated","description","examples","minProperties","properties","readOnly","required","title","type","writeOnly"]),fH={maxStringLength:2048,truncationSuffix:"..."},hH={maxStringLength:2048,truncationSuffix:"..."};function lE(t){if(t)return t===!0?{intent:!0,model:!0}:{intent:t.intent!==!1,model:t.model!==!1}}function Gy(t,e){return{}.hasOwnProperty.call(t,e)}function Ky(t,e){const n=Object.create(t);return e&&Object.defineProperty(n,"inputSchema",{configurable:!0,enumerable:!0,writable:!0,value:e}),n}function cE(t,e,n=!1){if(!rt(t))return;const r=t.trim();return r?(n?aT(r,fH):r).slice(0,e):void 0}function uE(t){try{return nt(t)&&t.isError===!0}catch{return!1}}function FR(t){return aT(t||"Unknown error",hH).slice(0,2048)}function pH(t,e){try{return FR(e?(function(n){try{return!nt(n)||!ze(n.content)?void 0:n.content.filter(r=>nt(r)&&r.type==="text"&&rt(r.text)).map(r=>r.text).join(" ").trim()||void 0}catch{return}})(t):nt(t)&&rt(t.message)?t.message:rt(t)?t:String(t))}catch{return"Unknown error"}}function mH(t,e,n){return e.errorResult?[{type:"Error",value:n,mechanism:{type:"generic",handled:!0,synthetic:!0,exception_id:0}}]:t.buildProperties(e.error,{handled:!0}).$exception_list.map(r=>$($({},r),{},{value:FR(r.value)}))}function gH(t,e){if(e)return"Error";try{if(!nt(t))return"Error";let n=rt(t.name)?t.name.trim():"";const r=t.constructor;return n&&n!=="Error"||!gn(r)||r.name==="Error"||(n=r.name),(n||"Error").slice(0,256)}catch{return"Error"}}function vH(t,e){return{message:pH(t,e),type:gH(t,e)}}const qg={featureFlags:class extends QV{constructor(t){const e=new JV(t.config,t.Qu());super(e),this.name=OR,this._instance=t,this.df=e}get Hd(){return this._instance.persistence}updateConfig(t,e){this.df.update(t,e),this.Ud()}}},yH={sessionRecording:class{get Ar(){return this._instance.config}get _c(){return this._instance.persistence}get started(){var t;return!!(!((t=this.vf)===null||t===void 0)&&t.isStarted)}get status(){var t,e;return this.ff==="awaiting_config"||this.ff==="missing_config"?this.ff:(t=(e=this.vf)===null||e===void 0?void 0:e.status)!==null&&t!==void 0?t:this.ff}constructor(t){if(this._instance=t,this._forceAllowLocalhostNetworkCapture=!1,this.ff=Uy,this.pf=void 0,this.gf=!1,this.Je=(()=>{var e,n;if(!(ke!=null&&ke.visibilityState)||ke.visibilityState==="visible")return!0;const r=oe==null||(e=oe.performance)===null||e===void 0||(n=e.getEntriesByType)===null||n===void 0?void 0:n.call(e,"visibility-state");return!(r!=null&&r.length)||r.some(s=>s.name==="visible")})(),this.sn=()=>{var e,n;(ke==null?void 0:ke.visibilityState)==="visible"&&(this.Je=!0,(e=this.vf)===null||e===void 0||(n=e.setDocumentWasEverVisible)===null||n===void 0||n.call(e,!0))},!this._instance.sessionManager)throw So.error("started without valid sessionManager"),new Error("[SessionRecording] started without valid sessionManager. This is a bug.");if(this.Ar.cookieless_mode==="always")throw new Error('[SessionRecording] cannot be used with cookieless_mode="always"');ke!=null&&ke.addEventListener&&_t(ke,"visibilitychange",this.sn)}initialize(){this.startIfEnabledOrStop()}dispose({discardBufferedEvents:t=!1}={}){var e;this.gf=!0,ke==null||(e=ke.removeEventListener)===null||e===void 0||e.call(ke,"visibilitychange",this.sn),t?this.mf(!0):this.stopRecording()}get yf(){var t;const e=!!(!((t=this._instance.get_property("$session_recording_remote_config"))===null||t===void 0)&&t.enabled),n=!this.Ar.disable_session_recording,r=this.Ar.disable_session_recording||this._instance.consent.isOptedOut();return oe&&e&&n&&!r}startIfEnabledOrStop(t){var e;if(this.gf||this.yf&&(!((e=this.vf)===null||e===void 0)&&e.isStarted))return;const n=!ae(Object.assign)&&!ae(Array.from);this.yf&&n?(this.bf(t),So.info("starting")):(this.ff=Uy,this.stopRecording())}bf(t){var e,n;if(this.yf)if(this.ff!=="awaiting_config"&&this.ff!=="missing_config"&&(this.ff=W8),(qe==null||(e=qe.__PosthogExtensions__)===null||e===void 0||(e=e.rrweb)===null||e===void 0?void 0:e.record)&&((n=qe.__PosthogExtensions__)===null||n===void 0?void 0:n.initSessionRecording))this._f(t);else{var r,s;const i=this._instance.sessionManager;(r=qe.__PosthogExtensions__)===null||r===void 0||(s=r.loadExternalDependency)===null||s===void 0||s.call(r,this._instance,this.wf,o=>{if(!this.gf&&this.yf&&this._instance.sessionManager===i)return o?(this._instance.register_for_session({$sdk_debug_recording_script_not_loaded:!0}),So.error("could not load recorder",o)):void this._f(t);this.ff="disabled"})}}stopRecording(){var t,e;(t=this.pf)===null||t===void 0||t.call(this),this.pf=void 0,(e=this.vf)===null||e===void 0||e.stop()}mf(t=!1){var e,n;(e=this.pf)===null||e===void 0||e.call(this),this.pf=void 0,(n=this.vf)===null||n===void 0||n.discard({discardProducerEvents:t})}kf(){var t,e;(t=this._c)===null||t===void 0||t.unregister("$session_is_sampled"),(e=this._c)===null||e===void 0||e.unregister("$replay_sample_rate")}Sf(t,e){if(Xe(t))return null;const n=Cn(t)?t:parseFloat(t);return typeof(r=n)!="number"||!Number.isFinite(r)||0>r||r>1?(So.warn(`${e} must be between 0 and 1. Ignoring invalid value:`,t),null):n;var r}xf(t){if(this._c){var e,n;const r=this._c,s=()=>{var i;const o=t.sessionRecording===!1?void 0:t.sessionRecording,l=this.Sf((i=this.Ar.session_recording)===null||i===void 0?void 0:i.sampleRate,"session_recording.sampleRate"),u=this.Sf(o==null?void 0:o.sampleRate,"remote config sampleRate"),d=l??u;Xe(d)&&this.kf();const f=o==null?void 0:o.minimumDurationMilliseconds;r.register({[Gf]:$($({cache_timestamp:Date.now(),enabled:!!o},o),{},{networkPayloadCapture:$({capturePerformance:t.capturePerformance},o==null?void 0:o.networkPayloadCapture),canvasRecording:{enabled:o==null?void 0:o.recordCanvas,fps:o==null?void 0:o.canvasFps,quality:o==null?void 0:o.canvasQuality},sampleRate:d,minimumDurationMilliseconds:ae(f)?null:f,endpoint:o==null?void 0:o.endpoint,triggerMatchType:o==null?void 0:o.triggerMatchType,masking:o==null?void 0:o.masking,urlTriggers:o==null?void 0:o.urlTriggers,version:o==null?void 0:o.version,triggerGroups:o==null?void 0:o.triggerGroups})})};s(),(e=this.pf)===null||e===void 0||e.call(this),this.pf=(n=this._instance.sessionManager)===null||n===void 0?void 0:n.onSessionId(s)}}onRemoteConfig(t){const e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.xf(e),void this.mf()):(this.xf(e),void this.startIfEnabledOrStop()):(this.ff==="awaiting_config"&&(this.ff="missing_config",this._instance.register_for_session({[qx]:!0}),So.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e="log"){var n;!((n=this.vf)===null||n===void 0)&&n.log?this.vf.log(t,e):So.warn("log called before recorder was ready")}get wf(){var t,e;const n=(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0?void 0:t.get_property(Gf);return(n==null||(e=n.scriptConfig)===null||e===void 0?void 0:e.script)||"lazy-recorder"}$f(){const t=this._instance.get_property(Gf);if(!t)return!1;let e;try{e=typeof t=="object"?t:JSON.parse(t)}catch(n){return So.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!Xe(e.cache_timestamp)&&36e5>=Date.now()-e.cache_timestamp}_f(t){var e,n,r;if(!this.gf&&this.yf&&this._instance.sessionManager){if(!(!((e=qe.__PosthogExtensions__)===null||e===void 0)&&e.initSessionRecording))return So.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Zx]:!0});var s;if(this.vf||(this.vf=(s=qe.__PosthogExtensions__)===null||s===void 0?void 0:s.initSessionRecording(this._instance,this.Je),this.vf._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.$f())return this.ff==="missing_config"||this.ff==="awaiting_config"?void 0:(this.ff="awaiting_config",So.info("persisted remote config is stale, requesting fresh config before starting"),void new lR(this._instance).load());this.ff=W8,(n=(r=this.vf).setDocumentWasEverVisible)===null||n===void 0||n.call(r,this.Je),this.vf.start(t)}else this.ff=Uy}onRRwebEmit(t){var e,n;(e=this.vf)===null||e===void 0||(n=e.onRRwebEmit)===null||n===void 0||n.call(e,t)}overrideLinkedFlag(){var t,e;this.vf||(e=this._c)===null||e===void 0||e.register({$replay_override_linked_flag:!0}),(t=this.vf)===null||t===void 0||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.vf||(e=this._c)===null||e===void 0||e.register({$replay_override_sampling:!0}),(t=this.vf)===null||t===void 0||t.overrideSampling()}overrideTrigger(t){var e,n;this.vf||(n=this._c)===null||n===void 0||n.register({[t==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(e=this.vf)===null||e===void 0||e.overrideTrigger(t)}get sdkDebugProperties(){var t;const e={};for(const r of zV){var n;const s=(n=this._instance.sessionPersistence)===null||n===void 0?void 0:n.get_property(r);ae(s)||(e[r]=s)}return $($({},e),((t=this.vf)===null||t===void 0?void 0:t.sdkDebugProperties)||{$recording_status:this.status})}tryAddCustomEvent(t,e){var n;return!!(!((n=this.vf)===null||n===void 0)&&n.tryAddCustomEvent(t,e))}flushBeforeIdentityReset(){var t,e;(t=this.vf)===null||t===void 0||(e=t.flushBeforeIdentityReset)===null||e===void 0||e.call(t)}}},_H={autocapture:class extends CV{constructor(t){super(new $V(t)),this.instance=t}},historyAutocapture:class{constructor(t){this.Cf=!1,this._instance=t,this.Tf=this.If()}initialize(){this.startIfEnabled()}get isEnabled(){const t=this.Mf();return!!(t.path||t.search||this.Ef(t))}startIfEnabled(){this.isEnabled&&(he.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}startIfEnabledOrStop(){this.stop(),this.Tf=this.If(),this.startIfEnabled()}stop(){this.Pf&&this.Pf(),this.Pf=void 0,this.Rf&&this.Rf(),this.Rf=void 0,he.info("History API monitoring stopped")}monitorHistoryChanges(){oe&&oe.history&&(this.Af("pushState"),this.Af("replaceState"),this.Ff(),this.Ef()&&this.Of())}Af(t){var e;if(!oe||!((e=oe.history[t])===null||e===void 0)&&e.__posthog_wrapped__)return;const n=this;cd(oe.history,t,r=>function(s,i,o){var l;n.Df(o)&&n.Lf(),r.call(this,s,i,o),n.Nf(t,!n.Cf&&(oe==null||(l=oe.event)===null||l===void 0?void 0:l.type)!=="popstate")})}If(){const t=oe==null?void 0:oe.location;if(t!=null&&t.pathname)return{pathname:t.pathname,search:t.search,hash:t.hash}}Mf(){const t=this._instance.config.capture_pageview;return t==="history_change"?{path:!0}:nt(t)?t:{}}Ef(t=this.Mf()){return!!t.hash&&!this._instance.config.disable_capture_url_hashes}qf(t){const e=this.Mf(),n=this.Tf;return!(!n||!(e.path&&t.pathname!==n.pathname||e.search&&t.search!==n.search||this.Ef(e)&&t.hash!==n.hash))}Nf(t,e=!1){try{e||this.Lf();const n=this.If();if(!n)return;if(this.qf(n)){const r=()=>this._instance.capture(Gx,{navigation_type:t});e?(this.jf=r,Promise.resolve().then(()=>this.Lf())):r()}this.Tf=n}catch(n){he.error(`Error capturing ${t} pageview`,n)}}Df(t){var e,n;return!(Xe(t)||!oe)&&((e=qo(String(t)))===null||e===void 0?void 0:e.href)!==((n=oe.location)===null||n===void 0?void 0:n.href)}Lf(){const t=this.jf;if(t){this.jf=void 0,this.Cf=!0;try{t()}catch(e){he.error("Error capturing deferred pageview",e)}finally{this.Cf=!1}this.Tf=this.If()}}Ff(){if(this.Pf)return;const t=()=>{this.Nf("popstate")};_t(oe,"popstate",t),this.Pf=()=>{oe&&oe.removeEventListener("popstate",t)}}Of(){if(this.Rf)return;const t=()=>{this.Nf("hashchange")};_t(oe,"hashchange",t),this.Rf=()=>{oe&&oe.removeEventListener("hashchange",t)}}},heatmaps:class{get Ar(){return this.instance.config}constructor(t){var e;this.Bf=!1,this.ll=!1,this.zf=null,this.instance=t,this.Bf=!!(!((e=this.instance.persistence)===null||e===void 0)&&e.props[y2]),this.rageclicks=new IR(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){let t=5e3;return nt(this.Ar.capture_heatmaps)&&this.Ar.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ar.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return Xe(this.Ar.capture_heatmaps)?Xe(this.Ar.enable_heatmaps)?this.Bf:this.Ar.enable_heatmaps:this.Ar.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.ll)return;UV.info("starting..."),this.Hf(),this.sn()}else{var t;clearInterval((t=this.zf)!==null&&t!==void 0?t:void 0),this.Uf(),this.getAndClearBuffer()}}onRemoteConfig(t){if(!t.ok)return;const e=t.config;if(!("heatmaps"in e))return;const n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[y2]:n}),this.Bf=n,this.startIfEnabled()}getAndClearBuffer(){const t=this.Rt;return this.Rt=void 0,t}Wf(t){By(t.originalEvent)&&this.Er(t.originalEvent,"deadclick")}sn(){this.zf&&clearInterval(this.zf),this.zf=(ke==null?void 0:ke.visibilityState)==="visible"?setInterval(this.rc.bind(this),this.flushIntervalMilliseconds):null}Hf(){oe&&ke&&(this.Vf=this.rc.bind(this),_t(oe,Wm,this.Vf),this.Gf=t=>this.Er(t||(oe==null?void 0:oe.event)),_t(ke,"click",this.Gf,{capture:!0}),this.Qf=t=>this.Zf(t||(oe==null?void 0:oe.event)),_t(ke,"mousemove",this.Qf,{capture:!0}),this.Jf=new y8(this.instance,HF,this.Wf.bind(this)),this.Jf.startIfEnabledOrStop(),this.Kf=this.sn.bind(this),_t(ke,Du,this.Kf),this.ll=!0)}Uf(){var t;oe&&ke&&(this.Vf&&oe.removeEventListener(Wm,this.Vf),this.Gf&&ke.removeEventListener("click",this.Gf,{capture:!0}),this.Qf&&ke.removeEventListener("mousemove",this.Qf,{capture:!0}),this.Kf&&ke.removeEventListener(Du,this.Kf),clearTimeout(this.Xf),(t=this.Jf)===null||t===void 0||t.stop(),this.ll=!1)}Yf(t,e){const n=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),s=this.instance.scrollManager.scrollElement(),i=(function(o,l,u){let d=o;for(;d&&ei(d)&&!Nn(d,"body");){if(d===u)return!1;let v;try{var f,h,m;v=(f=(h=(m=d.ownerDocument)===null||m===void 0?void 0:m.defaultView)!==null&&h!==void 0?h:oe)===null||f===void 0?void 0:f.getComputedStyle(d).position}catch{return!1}if(je(l,v))return!0;d=UT(d)}return!1})(Xf(t),["fixed","sticky"],s);return{x:t.clientX+(i?0:r),y:t.clientY+(i?0:n),target_fixed:i,type:e}}Er(t,e="click"){var n;if(a8(t.target)||!By(t))return;const r=this.Yf(t,e);!((n=this.rageclicks)===null||n===void 0)&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&WT(Xf(t),this.instance.config.rageclick)&&this.Qs($($({},r),{},{type:"rageclick"})),this.Qs(r)}Zf(t){!a8(t.target)&&By(t)&&(clearTimeout(this.Xf),this.Xf=setTimeout(()=>{this.Qs(this.Yf(t,"mousemove"))},500))}Qs(t){if(!oe)return;const e=this.Ar.disable_capture_url_hashes?Ya(oe.location.href):oe.location.href,n=this.Ar.custom_personal_data_properties,r=this.Ar.mask_personal_data_properties?[...ad,...n||[]]:[],s=vh(e,r,yh);this.Rt=this.Rt||{},this.Rt[s]||(this.Rt[s]=[]),this.Rt[s].push(t)}rc(){this.Rt&&!ts(this.Rt)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:y8,webVitalsAutocapture:class{constructor(t){var e;this._instance=t,this.Bf=!1,this.ll=!1,this.Rt={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.tp=(n=!1)=>{clearTimeout(this.ep),this.ep=void 0,this.Rt.metrics.length!==0&&(this._instance.capture("$web_vitals",$({$current_url:this.Rt.url},this.Rt.metrics.reduce((r,s)=>$($({},r),{},{[`$web_vitals_${s.name}_event`]:$({},s),[`$web_vitals_${s.name}_value`]:s.value}),{})),n?{transport:"sendBeacon",send_instantly:!0}:void 0),this.Rt={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.np=n=>{var r;if(this.Rt=this.Rt||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},Xe(n==null?void 0:n.name)||Xe(n==null?void 0:n.value))return void Ml.error("Invalid metric received",n);const s=typeof n.navigationURL=="string"?n.navigationURL:void 0,i=this.sp(s);if(ae(i))return;const o=Cn(n.navigationId)||typeof n.navigationId=="string"?`navigation:${n.navigationId}`:`url:${i}`;if(this.rp&&n.value>=this.rp)return void Ml.error("Ignoring metric with value >= "+this.rp,n);this.Rt.navigationKey!==o&&(this.tp(),this.ep=setTimeout(this.tp,this.flushToCaptureTimeoutMs)),ae(this.Rt.navigationKey)&&(this.Rt.navigationKey=o,this.Rt.url=i),this.Rt.firstMetricTimestamp=ae(this.Rt.firstMetricTimestamp)?Date.now():this.Rt.firstMetricTimestamp;const l=(r=this._instance.sessionManager)===null||r===void 0?void 0:r.checkAndGetSessionAndWindowId(!0),u=$($($({},n),s?{navigationURL:i}:{}),{},{$current_url:i,timestamp:Date.now()});if(delete u.entries,nt(n.attribution)&&this.attributionMetrics.indexOf(n.name)>-1){const d={};for(const f of HV){const h=f==="url"&&typeof n.attribution[f]=="string"?this.sp(n.attribution[f]):n.attribution[f];ae(h)||(d[f]=h)}u.attribution=d}else delete u.attribution;ae(l)||(u.$session_id=l.sessionId,u.$window_id=l.windowId),this.Rt.metrics.push(u),this.Rt.metrics.length===this.allowedMetrics.length&&this.tp()},this.op=()=>{if(this.ll)return;let n,r,s,i,o=!1;const l=qe.__PosthogExtensions__,u=l==null?void 0:l.postHogWebVitalsCallbacksByFlavor,d=(u==null?void 0:u[this.ap])||(this.ap==="web-vitals"&&ae(u)?l==null?void 0:l.postHogWebVitalsCallbacks:void 0);if(!ae(d)){const v=d.withoutAttribution,w=this.attributionMetrics;o=!ae(v),n=w.indexOf("LCP")>-1?d.onLCP:(v==null?void 0:v.onLCP)||d.onLCP,r=w.indexOf("CLS")>-1?d.onCLS:(v==null?void 0:v.onCLS)||d.onCLS,s=w.indexOf("FCP")>-1?d.onFCP:(v==null?void 0:v.onFCP)||d.onFCP,i=w.indexOf("INP")>-1?d.onINP:(v==null?void 0:v.onINP)||d.onINP}if(!(n&&r&&s&&i))return void Ml.error("web vitals callbacks not loaded - not starting");const f={reportSoftNavs:this.useSoftNavs},h=o&&this.attributionMetrics.indexOf("INP")>-1?$($({},f),{},{includeProcessedEventEntries:!1}):f;this.allowedMetrics.indexOf("LCP")>-1&&n(this.np.bind(this),f),this.allowedMetrics.indexOf("CLS")>-1&&r(this.np.bind(this),f),this.allowedMetrics.indexOf("FCP")>-1&&s(this.np.bind(this),f),this.allowedMetrics.indexOf("INP")>-1&&i(this.np.bind(this),h);const m=oe==null?void 0:oe.document;_t(m,Du,()=>{(m==null?void 0:m.visibilityState)==="hidden"&&this.tp(!0)}),_t(oe,"pagehide",()=>this.tp(!0)),this.ll=!0},this.Bf=!!(!((e=this._instance.persistence)===null||e===void 0)&&e.props[x2]),this.startIfEnabled()}get lp(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e;const n=nt(this.lp)?(t=this.lp)===null||t===void 0?void 0:t.web_vitals_allowed_metrics:void 0;return Xe(n)?((e=this._instance.persistence)===null||e===void 0?void 0:e.props.$web_vitals_allowed_metrics)||B8:n}get flushToCaptureTimeoutMs(){return(nt(this.lp)?this.lp.web_vitals_delayed_flush_ms:void 0)||5e3}get attributionMetrics(){const t=nt(this.lp)?this.lp.web_vitals_attribution:void 0;return Hr(t)?t?B8:[]:ze(t)?t:VV}get useAttribution(){return this.attributionMetrics.length>0}get useSoftNavs(){const t=nt(this.lp)?this.lp.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get rp(){const t=nt(this.lp)&&Cn(this.lp.__web_vitals_max_value)?this.lp.__web_vitals_max_value:U8;return t>0&&6e4>=t?U8:t}get isEnabled(){const t=Ut==null?void 0:Ut.protocol;if(t!=="http:"&&t!=="https:")return Ml.info("Web Vitals are disabled on non-http/https protocols"),!1;const e=nt(this.lp)?this.lp.web_vitals:Hr(this.lp)?this.lp:void 0;return Hr(e)?e:this.Bf}startIfEnabled(){this.isEnabled&&!this.ll&&(Ml.info("enabled, starting..."),this.Ml(this.op))}onRemoteConfig(t){if(!t.ok)return;const e=t.config;if(!("capturePerformance"in e))return;const n=nt(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=nt(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[x2]:n}),this._instance.persistence.register({[xT]:r})),this.Bf=n,this.startIfEnabled()}get ap(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}Ml(t){var e;const n=qe.__PosthogExtensions__,r=this.ap,s=n==null?void 0:n.postHogWebVitalsCallbacksByFlavor;s!=null&&s[r]||r==="web-vitals"&&ae(s)&&(n!=null&&n.postHogWebVitalsCallbacks)?t():n==null||(e=n.loadExternalDependency)===null||e===void 0||e.call(n,this._instance,r,i=>{i?Ml.error("failed to load script",i):t()})}sp(t){const e=t||(oe==null?void 0:oe.location.href);if(!e)return void Ml.error("Could not determine current URL");const n=this._instance.config.disable_capture_url_hashes?Ya(e):e,r=this._instance.config.custom_personal_data_properties,s=this._instance.config.mask_personal_data_properties?[...ad,...r||[]]:[];return vh(n,s,yh)}}},wH={exceptionObserver:class{constructor(t){var e;this.op=()=>{var n;if(!oe||!this.isEnabled||!(!((n=qe.__PosthogExtensions__)===null||n===void 0)&&n.errorWrappingFunctions))return;const r=qe.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,s=qe.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,i=qe.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.up&&this.Ar.capture_unhandled_errors&&(this.up=r(this.captureException.bind(this))),!this.cp&&this.Ar.capture_unhandled_rejections&&(this.cp=s(this.captureException.bind(this))),!this.hp&&this.Ar.capture_console_errors&&(this.hp=i(this.captureException.bind(this)))}catch(o){Cf.error("failed to start",o),this.dp()}},this._instance=t,this.vp=!!(!((e=this._instance.persistence)===null||e===void 0)&&e.props[_2]),this.wt=new R7($($({},(function(n={}){var r,s,i,o;return{refillRate:(r=(s=n.exceptionRateLimiterRefillRate)!==null&&s!==void 0?s:n.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(i=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&i!==void 0?i:10}})(this._instance.config.error_tracking)),{},{refillInterval:1e4,$:Cf})),this.Ar=this.fp(),this.startIfEnabledOrStop()}fp(){const t=this._instance.config.capture_exceptions;let e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return nt(t)?e=$($({},e),t):(ae(t)?this.vp:t)&&(e=$($({},e),{},{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ar.capture_console_errors||this.Ar.capture_unhandled_errors||this.Ar.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Cf.info("enabled"),this.dp(),this.Ml(this.op)):this.dp()}Ml(t){var e,n,r;!((e=qe.__PosthogExtensions__)===null||e===void 0)&&e.errorWrappingFunctions?t():(n=qe.__PosthogExtensions__)===null||n===void 0||(r=n.loadExternalDependency)===null||r===void 0||r.call(n,this._instance,"exception-autocapture",s=>{if(s)return Cf.error("failed to load script",s);t()})}dp(){var t,e,n;(t=this.up)===null||t===void 0||t.call(this),this.up=void 0,(e=this.cp)===null||e===void 0||e.call(this),this.cp=void 0,(n=this.hp)===null||n===void 0||n.call(this),this.hp=void 0}onRemoteConfig(t){if(!t.ok)return;const e=t.config;"autocaptureExceptions"in e&&(this.vp=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[_2]:this.vp}),this.Ar=this.fp(),this.startIfEnabledOrStop())}onConfigChange(){this.Ar=this.fp()}captureException(t){try{var e,n,r;const s=(e=t==null||(n=t.$exception_list)===null||n===void 0||(n=n[0])===null||n===void 0?void 0:n.type)!==null&&e!==void 0?e:"Exception";if(this.wt.consumeRateLimit(s))return void Cf.info("Skipping exception capture because of client rate limiting.",{exception:s});(r=this._instance.exceptions)===null||r===void 0||r.sendExceptionEvent(t)}catch{}}},exceptions:class{constructor(t){var e,n;this.pp=[],this.gp=new z7([new r$,new f$,new i$,new s$,new u$,new c$,new a$,new d$],(function(r,...s){return(i,o=0)=>{const l=[],u=i.split(`
|
|
19
|
-
`),d=Math.min(u.length,o+1e3),f=[];for(let v=o;d>v;v++){const w=u[v];if(w.length>1024)continue;const _=Fk.test(w)?w.replace(Fk,"$1"):w;if(!_.match(/\S*Error: /)){for(const x of s){const b=x(_,r);if(b){l.push(b);const k=J7(l);if(k){for(let C=f.length-1;C>=0;C--){const P=f[C];if(k.start>=P.start+P.length)break;f.pop()}f.push(k)}break}}if(t$(l,f)>=50)break}}const h=[...f].sort((v,w)=>w.start-v.start),m=h[h.length-1];if(m){const v=Q5(l,m);l.splice(m.start-v,v);for(const w of h)w.start-=v}for(const v of h)e$(l,v);return f.some(v=>v.start===0&&l.length===v.length)&&(function(v){const w=v.map(x=>`${x.function}|${x.filename}|${x.lineno}|${x.colno}|${x.module}`);let _=0;for(let x=1;w.length>x;x++)n$(w,x,_)&&(_=x);v.push(...v.splice(0,_))})(l),(function(v){if(!v.length)return[];const w=Array.from(v);return w.reverse(),w.slice(0,50).map(_=>{return $($({},_),{},{filename:_.filename||(x=w,x[x.length-1]||{}).filename,function:_.function||"?"});var x})})(l)}})("web:javascript",K7,Q7)),this._instance=t,this.pp=(e=(n=this._instance.persistence)===null||n===void 0?void 0:n.get_property("$error_tracking_suppression_rules"))!==null&&e!==void 0?e:[],this.mp=Fm(this.yp()),this.bp=new p$(this.mp)}onConfigChange(){this.mp=Fm(this.yp()),this.bp.setConfig(this.mp)}onRemoteConfig(t){var e,n,r;if(!t.ok)return;const s=t.config;if(!("errorTracking"in s))return;const i=(e=(n=s.errorTracking)===null||n===void 0?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(r=s.errorTracking)===null||r===void 0?void 0:r.captureExtensionExceptions;this.pp=i,this._instance.persistence&&this._instance.persistence.register({[_T]:this.pp,[w2]:o})}get _p(){var t;const e=!!this._instance.get_property(w2),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.gp.buildFromUnknown(t,{syntheticException:e==null?void 0:e.syntheticException,mechanism:{handled:e==null?void 0:e.handled}})}addExceptionStep(t,e){if(this.mp.enabled)try{if(!rt(t)||t.trim().length===0)return void fi.warn("Ignoring exception step because message must be a non-empty string");const{sanitizedProperties:n,droppedKeys:r}=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};const i=[];return{sanitizedProperties:Object.keys(s).reduce((o,l)=>h$.has(l)?(i.push(l),o):(o[l]=s[l],o),{}),droppedKeys:i}})(this.wp(e));r.length>0&&fi.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.bp.add($({[jm]:t,[$m]:new Date().toISOString()},n))}catch(n){fi.error("Failed to add exception step. Ignoring breadcrumb.",n)}}sendExceptionEvent(t){try{const e=t.$exception_list;if(this.kp(e)){if(this.Sp(e))return this.xp("Exception dropped: matched a suppression rule"),void fi.info("Skipping exception capture because a suppression rule matched");if(!this._p&&this.$p(e))return this.xp("Exception dropped: thrown by a browser extension"),void fi.info("Skipping exception capture because it was thrown by an extension");if(!this._p&&this.Cp(e))return this.xp("Exception dropped: thrown by an injected browser script"),void fi.info("Skipping exception capture because it was thrown by an injected browser script");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.Tp(e))return this.xp("Exception dropped: thrown by the PostHog SDK"),void fi.info("Skipping exception capture because it was thrown by the PostHog SDK")}const n=this.mp.enabled&&Xe(t.$exception_steps)?this.Ip(t):t,r=(function(){if("u">typeof process){var s;const o=(s=w7.POSTHOG_RELEASE_ID)===null||s===void 0?void 0:s.trim();if(o)return o}const i=globalThis._posthogReleaseId;return typeof i=="string"&&i.length>0?i:void 0})();r&&(n.$release_id=r);try{const s=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",sd:!0});return s&&this.bp.clear(),s}catch(s){return nE(s)||fi.error("Failed to capture exception event. Dropping this exception.",s),void this.bp.clear()}}catch(e){return void(nE(e)||fi.error("Failed to process exception event. Ignoring this exception.",e))}}Ip(t){try{const e=this.bp.getAttachable();return e.length===0?t:$($({},t),{},{$exception_steps:e})}catch(e){return fi.error("Failed to read buffered exception steps. Capturing exception without steps.",e),t}}xp(t){this.mp.enabled&&this.bp.add({[jm]:t,[$m]:new Date().toISOString()})}wp(t){return nt(t)?$({},t):{}}yp(){var t,e;return(t=(e=this._instance.config.error_tracking)===null||e===void 0?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}Sp(t){if(t.length===0)return!1;try{const e=t.reduce((n,{type:r,value:s})=>(rt(r)&&r.length>0&&n.$exception_types.push(r),rt(s)&&s.length>0&&n.$exception_values.push(s),n),{$exception_types:[],$exception_values:[]});return this.pp.some(n=>{const r=n.values.map(s=>{const i=AR[s.operator],o=e[s.key];if(!i||!o)return!1;const l=ze(s.value)?s.value:[s.value];return l.length>0&&i(l,o)});return n.type==="OR"?r.some(Boolean):r.every(Boolean)})}catch(e){return fi.warn("Failed to evaluate suppression rules. Capturing the exception.",e),!1}}$p(t){const e=t.flatMap(r=>{var s,i;return(s=(i=r.stacktrace)===null||i===void 0?void 0:i.frames)!==null&&s!==void 0?s:[]}),n=e.filter(({filename:r})=>!!r&&tH.some(s=>r.startsWith(s)));return n.length!==0&&(!n.every(({filename:r})=>!!r&&r.startsWith(N2))||t.some(({type:r,value:s})=>r==="NoResponse"||rt(s)&&eH.some(({value:i,exact:o})=>o?s===i:s.includes(i)))&&!e.some(({in_app:r,filename:s})=>r&&!(s!=null&&s.startsWith(N2))))}Cp(t){return t.some(({value:e})=>rt(e)&&nH.some(n=>e.includes(n)))}Tp(t){if(t.length>0){var e,n,r,s;const i=(e=(n=t[0].stacktrace)===null||n===void 0?void 0:n.frames)!==null&&e!==void 0?e:[],o=i[i.length-1];return(r=o==null||(s=o.filename)===null||s===void 0?void 0:s.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}kp(t){return!Xe(t)&&ze(t)}}},xH=$({productTours:class{get _c(){return this._instance.persistence}constructor(t){this.Mp=null,this.Ep=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!t.ok)return;const e=t.config;if("productTours"in e){var n,r;if(this._c&&this._c.register({[Bx]:!!e.productTours}),!Wy(this._instance))return!this.Mp&&Xe((n=this._c)===null||n===void 0?void 0:n.props.ph_product_tours)||P0.info("product tours disabled; stopping and clearing cached tours"),(r=this.Mp)===null||r===void 0||r.stop(),this.Mp=null,void this.clearCache();this.loadIfEnabled()}}loadIfEnabled(){!this.Mp&&Wy(this._instance)&&this.Ml(()=>this.Pp())}Ml(t){var e,n,r;!((e=qe.__PosthogExtensions__)===null||e===void 0)&&e.generateProductTours?t():(n=qe.__PosthogExtensions__)===null||n===void 0||(r=n.loadExternalDependency)===null||r===void 0||r.call(n,this._instance,"product-tours",s=>{s?P0.error("Could not load product tours script",s):t()})}Pp(){var t;!this.Mp&&(!((t=qe.__PosthogExtensions__)===null||t===void 0)&&t.generateProductTours)&&(this.Mp=qe.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e=!1){if(ze(this.Ep)&&!e)return void t(this.Ep,{isLoaded:!0});const n=this._c;if(n){const r=n.props[b2];if(ze(r)&&!e)return this.Ep=r,void t(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/product_tours/?token=${this._instance.config.token}`),method:"GET",timestampMode:"query",callback:r=>{if(!Wy(this._instance))return void t([],{isLoaded:!0});const s=r.statusCode;if(s!==200||!r.json){const o=`Product Tours API could not be loaded, status: ${s}`;return s===0?r.error||P0.warn(o):P0.error(o),void t([],{isLoaded:!1,error:o})}const i=ze(r.json.product_tours)?r.json.product_tours:[];this.Ep=i,n&&n.register({[b2]:i}),t(i,{isLoaded:!0})}})}getActiveProductTours(t){Xe(this.Mp)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.Mp.getActiveProductTours(t)}showProductTour(t){var e;(e=this.Mp)===null||e===void 0||e.showTourById(t)}previewTour(t){this.Mp?this.Mp.previewTour(t):this.Ml(()=>{var e;this.Pp(),(e=this.Mp)===null||e===void 0||e.previewTour(t)})}dismissProductTour(){var t;(t=this.Mp)===null||t===void 0||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.Mp)===null||t===void 0||t.nextStep()}previousStep(){var t;(t=this.Mp)===null||t===void 0||t.previousStep()}clearCache(){var t;this.Ep=null,(t=this._c)===null||t===void 0||t.unregister("ph_product_tours")}resetTour(t){var e;(e=this.Mp)===null||e===void 0||e.resetTour(t)}resetAllTours(){var t;(t=this.Mp)===null||t===void 0||t.resetAllTours()}cancelPendingTour(t){var e;(e=this.Mp)===null||e===void 0||e.cancelPendingTour(t)}}},qg),bH={siteApps:class{constructor(t){this._instance=t,this.Rp=0,this.Ap=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Fp(t,e){if(!e)return;const n=this.globalsForEvent(e);this.Ap.push(n),this.Ap.length>1e3&&(this.Ap=this.Ap.slice(10))}get siteAppLoaders(){var t;return(t=qe._POSTHOG_REMOTE_CONFIG)===null||t===void 0||(t=t[this._instance.config.token])===null||t===void 0?void 0:t.siteApps}initialize(){if(this.isEnabled){const t=this._instance._addCaptureHook(this.Fp.bind(this));this.Op=()=>{t(),this.Ap=[],this.Op=void 0}}}globalsForEvent(t){var e,n,r,s,i,o,l;if(!t)throw new Error("Event payload is required");const u={},d=this._instance.get_property("$groups")||[],f=this._instance.get_property("$stored_group_properties")||{};for(const[v,w]of Object.entries(f))u[v]={id:d[v],type:v,properties:w};const{$set_once:h,$set:m}=t;return{event:$($({},nT(t,BV)),{},{properties:$($($({},t.properties),m?{$set:$($({},(e=(n=t.properties)===null||n===void 0?void 0:n.$set)!==null&&e!==void 0?e:{}),m)}:{}),h?{$set_once:$($({},(r=(s=t.properties)===null||s===void 0?void 0:s.$set_once)!==null&&r!==void 0?r:{}),h)}:{}),elements_chain:(i=(o=t.properties)===null||o===void 0?void 0:o.$elements_chain)!==null&&i!==void 0?i:"",distinct_id:(l=t.properties)===null||l===void 0?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:u}}Dp(t){var e;const n=(e=t.tagName)===null||e===void 0?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Mi.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Mi.error("prepare_external_dependency_script returned null"),null):t}Lp(){var t,e,n,r,s,i,o,l;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};const u=ke==null?void 0:ke.defaultView,d=u==null||(t=u.Node)===null||t===void 0?void 0:t.prototype;if(!u||!d)return()=>{};if(this.Rp++,this.Np)return this.qp();const f=[],h=this,m=new WeakSet,v=(x,b,k)=>{if(!(x!=null&&x[b]))return;const C=x[b];x[b]=k(C),f.push(()=>{x[b]=C})},w=x=>{if(m.has(x))return x;const b=h.Dp(x);return b&&m.add(b),b},_=x=>x.map(b=>typeof b=="string"?b:w(b)).filter(b=>!dn(b));return v(d,"appendChild",x=>function(b){const k=w(b);return k?x.call(this,k):b}),v(d,"insertBefore",x=>function(b,k){const C=w(b);return C?x.call(this,C,k):b}),v(d,"replaceChild",x=>function(b,k){const C=w(b);return C?x.call(this,C,k):k}),[(e=u.Element)===null||e===void 0?void 0:e.prototype,(n=u.Document)===null||n===void 0?void 0:n.prototype,(r=u.DocumentFragment)===null||r===void 0?void 0:r.prototype].forEach(x=>{v(x,"append",b=>function(...k){return b.apply(this,_(k))}),v(x,"prepend",b=>function(...k){return b.apply(this,_(k))})}),[(s=u.Element)===null||s===void 0?void 0:s.prototype,(i=u.CharacterData)===null||i===void 0?void 0:i.prototype,(o=u.DocumentType)===null||o===void 0?void 0:o.prototype].forEach(x=>{v(x,"before",b=>function(...k){return b.apply(this,_(k))}),v(x,"after",b=>function(...k){return b.apply(this,_(k))}),v(x,"replaceWith",b=>function(...k){const C=_(k);return k.length&&!C.length?void 0:b.apply(this,C)})}),v((l=u.Element)===null||l===void 0?void 0:l.prototype,"insertAdjacentElement",x=>function(b,k){const C=w(k);return C?x.call(this,b,C):null}),this.Np=()=>{f.forEach(x=>x()),this.Np=void 0},this.qp()}qp(){let t=!1;return()=>{var e;t||(t=!0,this.Rp--,this.Rp===0&&((e=this.Np)===null||e===void 0||e.call(this)))}}jp(t,e=!0){const n=this.Lp();try{const r=t(n);return e&&n(),r}catch(r){throw n(),r}}setupSiteApp(t){const e=this.apps[t.id],n=()=>{var i;!e.errored&&this.Ap.length&&(Mi.info(`Processing ${this.Ap.length} events for site app with id ${t.id}`),this.Ap.forEach(o=>this.jp(()=>{var l;return(l=e.processEvent)===null||l===void 0?void 0:l.call(e,o)})),e.processedBuffer=!0),Object.values(this.apps).every(o=>o.processedBuffer||o.errored)&&((i=this.Op)===null||i===void 0||i.call(this))};let r=!1;const s=i=>{e.errored=!i,e.loaded=!0,Mi.info(`Site app with id ${t.id} ${i?"loaded":"errored"}`),r&&n()};try{const{processEvent:i}=this.jp(o=>t.init({posthog:this._instance,callback(l){o(),s(l)}}),!1);i&&(e.processEvent=i),r=!0}catch(i){Mi.error(Z8+t.id,i),s(!1)}if(r&&e.loaded)try{n()}catch(i){Mi.error(`Error while processing buffered events PostHog app with config id ${t.id}`,i),e.errored=!0}}Bp(){const t=this.siteAppLoaders||[];for(const e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(const e of t)this.setupSiteApp(e)}zp(t){if(Object.keys(this.apps).length===0)return;const e=this.globalsForEvent(t);for(const n of Object.values(this.apps))try{this.jp(()=>{var r;return(r=n.processEvent)===null||r===void 0?void 0:r.call(n,e)})}catch(r){Mi.error(`Error while processing event ${t.event} for site app ${n.id}`,r)}}onRemoteConfig(t){var e,n,r;if(!((e=this.siteAppLoaders)===null||e===void 0)&&e.length)return this.isEnabled?(this.Bp(),void this._instance.on("eventCaptured",l=>this.zp(l))):void Mi.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.Op)===null||n===void 0||n.call(this),!t.ok)return;const s=t.config;if(!((r=s.siteApps)===null||r===void 0)&&r.length)if(this.isEnabled)for(const{id:l,url:u}of s.siteApps){var i,o;qe[`__$$ph_site_app_${l}`]=this._instance,(i=qe.__PosthogExtensions__)===null||i===void 0||(o=i.loadSiteApp)===null||o===void 0||o.call(i,this._instance,u,d=>{if(d)return Mi.error(Z8+l,d)})}else Mi.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},SH={tracingHeaders:class{constructor(t){this._instance=t,this.Hp=void 0,this.Up=void 0,this.Wp=void 0,this.op=()=>{const e=this.Vp();var n,r;e?(ae(this.Hp)&&(this.Hp=(n=qe.__PosthogExtensions__)===null||n===void 0||(n=n.tracingHeadersPatchFns)===null||n===void 0?void 0:n._patchXHR(e,()=>this._instance.get_distinct_id(),this._instance.sessionManager)),ae(this.Up)&&(this.Up=(r=qe.__PosthogExtensions__)===null||r===void 0||(r=r.tracingHeadersPatchFns)===null||r===void 0?void 0:r._patchFetch(e,()=>this._instance.get_distinct_id(),this._instance.sessionManager))):this.dp()}}initialize(){this.startIfEnabledOrStop()}Ml(t){var e,n,r;!((e=qe.__PosthogExtensions__)===null||e===void 0)&&e.tracingHeadersPatchFns?t():(n=qe.__PosthogExtensions__)===null||n===void 0||(r=n.loadExternalDependency)===null||r===void 0||r.call(n,this._instance,"tracing-headers",s=>{if(s)return FV.error("failed to load script",s);t()})}Gp(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Vp(){const t=this.Gp();return ze(t)?(ze(this.Wp)?this.Wp.splice(0,this.Wp.length,...t):this.Wp=[...t],t.length>0?this.Wp:void 0):(ze(this.Wp)&&this.Wp.splice(0),this.Wp=t||void 0,this.Wp)}dp(){var t,e;(t=this.Hp)===null||t===void 0||t.call(this),(e=this.Up)===null||e===void 0||e.call(this),this.Hp=void 0,this.Up=void 0}startIfEnabledOrStop(){this.Vp()?this.Ml(this.op):this.dp()}}},kH=$({surveys:class extends GV{constructor(t){super(new KV(t))}}},qg),EH={toolbar:class{constructor(t){this.instance=t}Qp(t){qe.ph_toolbar_state=t}Zp(){var t;return(t=qe.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t=void 0,e=void 0,n=void 0){var r,s;if(k2(this.instance.config)||!oe||!ke)return!1;t=(r=t)!==null&&r!==void 0?r:oe.location,n=(s=n)!==null&&s!==void 0?s:oe.history;try{if(!e){try{oe.localStorage.setItem("test","test"),oe.localStorage.removeItem("test")}catch{return!1}e=oe==null?void 0:oe.localStorage}const i=YV||qm(t.hash,"__posthog")||qm(t.hash,"state");let o;const l=i?Ok(()=>JSON.parse(atob(decodeURIComponent(i))))||Ok(()=>JSON.parse(decodeURIComponent(i))):null;return l&&l.action==="ph_authorize"?(o=l,o.source="url",o&&Object.keys(o).length>0&&(l.desiredHash?t.hash=l.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):(o=JSON.parse(e.getItem(G8)||"{}"),o.source="localstorage",delete o.userIntent),!(!o.token||this.instance.config.token!==o.token||(this.loadToolbar(o),0))}catch{return!1}}Jp(t){const e=qe.ph_load_toolbar||qe.ph_load_editor;!Xe(e)&&gn(e)?e(t,this.instance):K8.warn("No toolbar load function found")}loadToolbar(t){const e=!!(ke!=null&&ke.getElementById("__POSTHOG_TOOLBAR__"));if(!oe||e)return!1;const n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=$($({token:this.instance.config.token},t),{},{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(oe.localStorage.setItem(G8,JSON.stringify($($({},r),{},{source:void 0}))),this.Zp()===2)this.Jp(r);else if(this.Zp()===0){var s,i;this.Qp(1),(s=qe.__PosthogExtensions__)===null||s===void 0||(i=s.loadExternalDependency)===null||i===void 0||i.call(s,this.instance,"toolbar",o=>{if(o)return K8.error("[Toolbar] Failed to load",o),void this.Qp(0);this.Qp(2),this.Jp(r)}),_t(oe,"turbolinks:load",()=>{this.Qp(0),this.loadToolbar(r)})}return!0}Kp(t){return this.loadToolbar(t)}maybeLoadEditor(t=void 0,e=void 0,n=void 0){return this.maybeLoadToolbar(t,e,n)}}},CH=$({experiments:class jr{get Ar(){return this._instance.config}constructor(e){this._instance=e,this.getWebExperimentsAndEvaluateDisplayLogic=(n=!1)=>{this.getWebExperiments(r=>{jr.Xp("retrieved web experiments from the server"),this.Yp=new Map,r.forEach(s=>{if(s.feature_flag_key){var i;this.Yp&&(jr.Xp("setting flag key ",s.feature_flag_key," to web experiment ",s),(i=this.Yp)===null||i===void 0||i.set(s.feature_flag_key,s));const o=this._instance.getFeatureFlag(s.feature_flag_key);rt(o)&&s.variants[o]&&this.tg(s.name,o,s.variants[o].transforms)}else if(s.variants)for(const o in s.variants){const l=s.variants[o];jr.eg(l,this._instance)&&this.tg(s.name,o,l.transforms)}})},n)},this._instance.onFeatureFlags(n=>{this.onFeatureFlags(n)})}initialize(){}onFeatureFlags(e){if(this._is_bot())jr.Xp(rE);else if(!this.Ar.disable_web_experiments){if(Xe(this.Yp))return this.Yp=new Map,this.loadIfEnabled(),void this.previewWebExperiment();jr.Xp("applying feature flags",e),e.forEach(n=>{var r;if(this.Yp&&(!((r=this.Yp)===null||r===void 0)&&r.has(n))){var s;const i=this._instance.getFeatureFlag(n),o=(s=this.Yp)===null||s===void 0?void 0:s.get(n);i&&(o!=null&&o.variants[i])&&this.tg(o.name,i,o.variants[i].transforms)}})}}previewWebExperiment(){const e=jr.getWindowLocation();if(e!=null&&e.search){const n=od(e==null?void 0:e.search,"__experiment_id"),r=od(e==null?void 0:e.search,"__experiment_variant");n&&r&&(jr.Xp(`previewing web experiments ${n} && ${r}`),this.getWebExperiments(s=>{this.ig(parseInt(n),r,s)},!1,!0))}}loadIfEnabled(){this.Ar.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,r){if(this.Ar.disable_web_experiments&&!r)return e([]);const s=this._instance.get_property("$web_experiments");if(s&&!n)return e(s);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/web_experiments/?token=${this.Ar.token}`),method:"GET",timestampMode:"query",callback:i=>e(i.statusCode===200&&i.json&&i.json.experiments||[])})}ig(e,n,r){const s=r.filter(i=>i.id===e);s&&s.length>0&&(jr.Xp(`Previewing web experiment [${s[0].name}] with variant [${n}]`),this.tg(s[0].name,n,s[0].variants[n].transforms))}static eg(e,n){return!Xe(e.conditions)&&jr.ng(e,n)&&jr.sg(e)}static ng(e,n){var r;if(Xe(e.conditions)||Xe((r=e.conditions)===null||r===void 0?void 0:r.url))return!0;const s=jr.getWindowLocation();if(s){var i,o,l;const u=VT(n,s.href);return!(!((i=e.conditions)===null||i===void 0)&&i.url)||rH[(o=(l=e.conditions)===null||l===void 0?void 0:l.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,u)}return!1}static getWindowLocation(){return oe==null?void 0:oe.location}static sg(e){var n;if(Xe(e.conditions)||Xe((n=e.conditions)===null||n===void 0?void 0:n.utm))return!0;const r=eR();if(r.utm_source){var s,i,o,l,u,d,f,h;const m=!(!((s=e.conditions)===null||s===void 0||(s=s.utm)===null||s===void 0)&&s.utm_campaign)||((i=e.conditions)===null||i===void 0||(i=i.utm)===null||i===void 0?void 0:i.utm_campaign)==r.utm_campaign,v=!(!((o=e.conditions)===null||o===void 0||(o=o.utm)===null||o===void 0)&&o.utm_source)||((l=e.conditions)===null||l===void 0||(l=l.utm)===null||l===void 0?void 0:l.utm_source)==r.utm_source,w=!(!((u=e.conditions)===null||u===void 0||(u=u.utm)===null||u===void 0)&&u.utm_medium)||((d=e.conditions)===null||d===void 0||(d=d.utm)===null||d===void 0?void 0:d.utm_medium)==r.utm_medium,_=!(!((f=e.conditions)===null||f===void 0||(f=f.utm)===null||f===void 0)&&f.utm_term)||((h=e.conditions)===null||h===void 0||(h=h.utm)===null||h===void 0?void 0:h.utm_term)==r.utm_term;return m&&w&&_&&v}return!1}static Xp(e,...n){he.info(`[WebExperiments] ${e}`,n)}tg(e,n,r){this._is_bot()?jr.Xp(rE):n!=="control"?r.forEach(s=>{if(s.selector){var i;jr.Xp(`applying transform of variant ${n} for experiment ${e} `,s);const o=(i=document)===null||i===void 0?void 0:i.querySelectorAll(s.selector);o==null||o.forEach(l=>{const u=l;s.html&&(u.innerHTML=s.html),s.css&&u.setAttribute("style",s.css)})}}):jr.Xp("Control variants leave the page unmodified.")}_is_bot(){return gr&&this._instance?ER(gr,this.Ar.custom_blocked_useragents):void 0}}},qg),PH={conversations:class{constructor(t){this._instance=t,this.rg=void 0,this._conversationsManager=null,this.og=!1,this.ne=null,this.ag=!1,this.lg=0,this.ug=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(this._instance.config.disable_conversations)return void(this.ug=null);if(this.cg=t.ok,!t.ok)return;const e=t.config.conversations;Xe(e)?this.ug=null:(Hr(e)?this.rg=e:(this.rg=e.enabled,this.ne=e),this.rg||(this.ug=null),this.loadIfEnabled())}reset(){var t;(t=this._conversationsManager)===null||t===void 0||t.reset(),this._conversationsManager=null,this.lg++,this.rg=void 0,this.ne=null,this.cg=void 0,this.ag=!1,this.ug=null}loadIfEnabled(){if(this._conversationsManager||this.og||this._instance.config.disable_conversations||k2(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())return;const t=qe==null?void 0:qe.__PosthogExtensions__;if(t&&!ae(this.rg)&&this.rg)if(this.ne&&this.ne.token){this.og=!0;try{const e=t.initConversations;if(e)return this.hg(e),void(this.og=!1);const n=t.loadExternalDependency;if(!n)return void this.dg(Hx);const r=this.lg;n(this._instance,"conversations",s=>{if(r!==this.lg)return this.og=!1,void this.loadIfEnabled();s||!t.initConversations?this.dg("Could not load conversations script",s):this.hg(t.initConversations),this.og=!1})}catch(e){this.dg("Error initializing conversations",e),this.og=!1}}else Zs.error("Conversations enabled but missing token in remote config.")}hg(t){if(this.ne){try{this._conversationsManager=t(this.ne,this._instance),this.ag=!1,Zs.info("Conversations loaded successfully")}catch(e){return void this.dg("Error completing conversations initialization",e)}this.vg()}else Zs.error("Cannot complete initialization: remote config is null")}vg(){const t=this.ug;this.ug=null,this._conversationsManager&&t&&(t==="open"?this._conversationsManager.open():this._conversationsManager.close())}dg(t,e){Zs.error(t,e),this._conversationsManager=null,this.og=!1,this.ag=!0}show(){this._conversationsManager?this._conversationsManager.show():Zs.warn("Conversations not loaded yet.")}hide(){this.ug==="open"&&(this.ug=null),this._conversationsManager&&this._conversationsManager.hide()}open(){this._conversationsManager?(this.ug=null,this._conversationsManager.open()):this.ug="open"}close(){this._conversationsManager?(this.ug=null,this._conversationsManager.close()):this.ug="close"}isAvailable(){return this.rg===!0&&!dn(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":k2(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.cg===!1?"remote_config_failed":ae(this.rg)?this.cg?"disabled_in_project":"remote_config_pending":this.rg?Xe(this.ne)||!this.ne.token?"missing_token":qe!=null&&qe.__PosthogExtensions__?this.og?"initializing":this.ag?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)===null||e===void 0?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var r=this;return Wt(function*(){return r._conversationsManager?r._conversationsManager.sendMessage(t,e,n):(Zs.warn(Ll),null)})()}getMessages(t,e){var n=this;return Wt(function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(Zs.warn(Ll),null)})()}markAsRead(t){var e=this;return Wt(function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Zs.warn(Ll),null)})()}getTickets(t){var e=this;return Wt(function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Zs.warn(Ll),null)})()}requestRestoreLink(t){var e=this;return Wt(function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Zs.warn(Ll),null)})()}restoreFromToken(t){var e=this;return Wt(function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Zs.warn(Ll),null)})()}restoreFromUrlToken(){var t=this;return Wt(function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Zs.warn(Ll),null)})()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)===null||e===void 0?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)===null||e===void 0?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}fd(){var t;(t=this._conversationsManager)===null||t===void 0||t.setIdentity()}pd(){var t;(t=this._conversationsManager)===null||t===void 0||t.clearIdentity()}}},AH={logs:class extends oH{constructor(t){super({get(){var e;return t==null||(e=t.config)===null||e===void 0?void 0:e.logs},captureHintKey:wT,get remoteConfigWillArrive(){var e,n;return!(!((e=t.Qu)===null||e===void 0)&&e.call(t))||!!(!((n=qe._POSTHOG_REMOTE_CONFIG)===null||n===void 0||(n=n[t.config.token])===null||n===void 0)&&n.config)}},()=>(function(e){var n;const r={};if(r.distinctId=e.get_distinct_id(),e.sessionManager){const{sessionId:s,windowId:i,sessionStartTimestamp:o,lastActivityTimestamp:l}=e.sessionManager.checkAndGetSessionAndWindowId(!0);r.sessionId=s,r.windowId=i,Xe(o)||(r.sessionStartTimestamp=o),Xe(l)||(r.lastActivityTimestamp=l)}if(!(qe==null||(n=qe.location)===null||n===void 0)&&n.href&&(r.currentUrl=e.config.disable_capture_url_hashes?Ya(qe.location.href):qe.location.href),e.featureFlags){const s=e.featureFlags.getFlags();s&&s.length>0&&(r.activeFeatureFlags=s)}return r})(t)),this._instance=t,this.name=LR,this.Uv()}get zv(){return this._instance.__loaded}Hv(){const t=an("[logs]"),e=qe==null?void 0:qe.__PosthogExtensions__;if(!e)return void t.error("PostHog Extensions not found.");const n=e.loadExternalDependency;if(n)return r=>{n(this._instance,"logs",s=>{const i=e.logs;r(s,i!=null&&i.initializeLogs?{initialize:o=>i.initializeLogs(o),replay(o,l){var u;return(u=i.replayConsoleBuffer)===null||u===void 0?void 0:u.call(i,o,l)}}:void 0)})};t.error(Hx)}}},TH={metrics:class{constructor(t){this._instance=t,this.$=an("[metrics]"),this.Ci=!1}initialize(){this.onConfigChange()}onConfigChange(){var t;if(this.Ci)return;const e=!!(!((t=this._instance.config.metrics)===null||t===void 0)&&t.network);e&&!this.fg?this.fg=(n=>{let r=!0;const s=()=>r?(l=>{var u;const d=(u=l.config.metrics)===null||u===void 0?void 0:u.network;return d===!0?{}:d||void 0})(n):void 0,i=cH(n,s),o=uH(n,s);return()=>{r=!1,i(),o()}})(this._instance):!e&&this.fg&&(this.fg(),this.fg=void 0)}Gv(){var t;const e=(t=this._instance)===null||t===void 0||(t=t.config)===null||t===void 0?void 0:t.metrics;var n;return this.jv&&this.Qv===e||((n=this.jv)===null||n===void 0||n.reset(),this.Qv=e,this.jv=new J$(this.Vv(),(function(r){var s,i,o,l,u;const d=r==null?void 0:r.resourceAttributes;return{serviceName:(s=d==null?void 0:d["service.name"])!==null&&s!==void 0?s:r==null?void 0:r.serviceName,serviceVersion:(i=d==null?void 0:d["service.version"])!==null&&i!==void 0?i:r==null?void 0:r.serviceVersion,environment:(o=d==null?void 0:d["deployment.environment"])!==null&&o!==void 0?o:r==null?void 0:r.environment,resourceAttributes:d,beforeSend:r==null?void 0:r.beforeSend,flushIntervalMs:(l=r==null?void 0:r.flushIntervalMs)!==null&&l!==void 0?l:1e4,maxSeriesPerFlush:(u=r==null?void 0:r.maxSeriesPerFlush)!==null&&u!==void 0?u:1e3}})(e),this.$)),this.jv}count(t,e=1,n){this.Gv().count(t,e,n)}gauge(t,e,n){this.Gv().gauge(t,e,n)}histogram(t,e,n){this.Gv().histogram(t,e,n)}flush(t){if(!this.jv)return Promise.resolve();if(t){const e=this.jv.drainWindow();return e&&this.po(e,t),Promise.resolve()}return this.jv.flush().catch(e=>this.$.error("PostHog metrics flush failed:",e))}reset(){var t;(t=this.jv)===null||t===void 0||t.reset()}dispose(){var t,e;this.Ci=!0,(t=this.fg)===null||t===void 0||t.call(this),this.fg=void 0,(e=this.jv)===null||e===void 0||e.reset()}Vv(){const t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},po:n=>e.po(n),getLibraryId:()=>Jr.LIB_NAME,getLibraryVersion:()=>Jr.LIB_VERSION}}po(t,e){return new Promise(n=>{let r=!1;const s=o=>{r||(r=!0,clearTimeout(i),n(o))},i=setTimeout(()=>s({kind:"retry-later",error:new Error("metrics request timed out")}),9e4);this._instance._send_request($($({method:"POST",url:this.pg(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e}),{},{fireCallbackOnDrop:!0,callback(o){const l=o.statusCode;if(l>=200&&300>l)s({kind:"ok"});else if(l===413)s({kind:"too-large"});else if(l!==0&&l!==408&&l!==429&&500>l)s({kind:"fatal",error:new Error(`metrics request failed with status ${l}`)});else{var u;s({kind:"retry-later",error:(u=o.error)!==null&&u!==void 0?u:new Error(`metrics request failed with status ${l}`)})}}}))})}pg(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},RH={webMCP:class{constructor(t){this._instance=t,this.gg=!1}initialize(){this.startIfEnabled()}startIfEnabled(){if(!this._instance.config.capture_webmcp||this.gg)return;const t=ke==null?void 0:ke.modelContext;if(!t||!gn(t.registerTool))return;const e=aE.get(t);if(e)return e.instances.add(this._instance),void(this.gg=!0);const n={instances:new Set([this._instance])},r=t.registerTool,s=this;cd(t,"registerTool",i=>{const o=i;return function(l,...u){let d=l;try{d=s.mg(l,n)}catch{return o.call(this,l,...u)}return o.call(this,d,...u)}}),t.registerTool!==r&&(aE.set(t,n),this.gg=!0)}mg(t,e){if(!t||!gn(t.execute))return t;const n=t.execute,r=this,{tool:s,injected:i}=(function(o,l){const u={intent:!1,model:!1},d=o.inputSchema;if(!(function(w){return!!ae(w)||nt(w)&&Object.keys(w).every(_=>dH.has(_)||_.startsWith("x-"))&&w.additionalProperties!==!0&&!nt(w.additionalProperties)&&(!w.type||w.type==="object")&&(!w.properties||nt(w.properties))&&(!w.required||ze(w.required))})(d))return{tool:Ky(o),injected:u};const f=(d==null?void 0:d.properties)||{},h=w=>Gy(f,w)||ze(d==null?void 0:d.required)&&d.required.includes(w);if(u.intent=l.intent&&!h("context"),u.model=l.model&&!h("llm_model"),!u.intent&&!u.model)return{tool:Ky(o),injected:u};const m=$({},f),v=ze(d==null?void 0:d.required)?[...d.required]:[];return u.intent&&(m.context={type:"string",description:`Explain why this tool is called and how it supports the user's goal. Describe the abstract purpose only. Do not include personal or identifying information. Generalize specific entities as roles such as "a customer".`},v.includes("context")||v.push("context")),u.model&&(m.llm_model={type:"string",description:'The exact model identifier you are running as, taken from your system prompt or environment. Pass "unknown" if you do not know it. Never guess.'},v.includes("llm_model")||v.push("llm_model")),{tool:Ky(o,$($({},d),{},{type:(d==null?void 0:d.type)||"object",properties:m,required:v})),injected:u}})(t,(function(o){const l={intent:!1,model:!1};for(const u of o.instances){const d=lE(u.config.capture_webmcp);l.intent||(l.intent=(d==null?void 0:d.intent)===!0),l.model||(l.model=(d==null?void 0:d.model)===!0)}return l})(e));return Object.defineProperty(s,"execute",{configurable:!0,enumerable:!0,writable:!0,value(...o){const l=new Date,u=(function(v,w){if(!nt(v))return{};try{const _=w.intent?cE(v.context,2048,!0):void 0,x=w.model?cE(v.llm_model,256):void 0;return $($({},_&&_!=="{}"?{intent:_}:{}),x&&x.toLowerCase()!=="unknown"?{model:x}:{})}catch{return{}}})(o[0],i),d=(function(v,w){const _=v[0];if(!nt(_))return v;try{const x=w.intent&&Gy(_,"context"),b=w.model&&Gy(_,"llm_model");if(!x&&!b)return v;const k=$({},_);return x&&delete k.context,b&&delete k.llm_model,[k,...v.slice(1)]}catch{return v}})(o,i);let f;try{f=n.apply(this===s?t:this,d)}catch(v){throw r.yg(e,s,l,{error:v,errorResult:!1},u),v}if((h=f)&&typeof h.then=="function")return Promise.resolve(f).then(v=>{const w=uE(v)?{error:v,errorResult:!0}:void 0;return r.yg(e,s,l,w,u),v},v=>{throw r.yg(e,s,l,{error:v,errorResult:!1},u),v});var h;const m=uE(f)?{error:f,errorResult:!0}:void 0;return r.yg(e,s,l,m,u),f}}),s}yg(t,e,n,r,s){const i=Date.now()-n.getTime();let o;for(const u of t.instances){var l;const d=lE(u.config.capture_webmcp);if(d){r&&!o&&(o=vH(r.error,r.errorResult));try{u.capture("$mcp_tool_call",$($($({$mcp_source:"posthog_mcp_analytics",$mcp_interface:"webmcp",$mcp_tool_name:e.name,$mcp_resource_name:e.name,$mcp_tool_description:e.description,$mcp_server_name:Ut==null?void 0:Ut.hostname,$mcp_duration_ms:i,$mcp_is_error:!!r},o?{$mcp_error_type:o.type,$mcp_error_message:o.message}:{}),d.intent&&s.intent?{$mcp_intent:s.intent,$mcp_intent_source:"context_parameter"}:{}),d.model&&s.model?{$mcp_llm_model:s.model,$mcp_llm_model_source:"self_reported"}:{}),{timestamp:n})}catch{continue}if(r&&o&&u.exceptions&&(!((l=u.exceptionObserver)===null||l===void 0)&&l.isEnabled))try{const f={$exception_list:mH(u.exceptions,r,o.message),$exception_level:"error",$exception_source:"mcp.tool_call",$mcp_interface:"webmcp",$mcp_tool_name:e.name,$mcp_resource_name:e.name,$mcp_tool_description:e.description,$mcp_server_name:Ut==null?void 0:Ut.hostname};u.exceptionObserver.captureException(f)}catch{}}}}}};th.__defaultExtensionClasses=$({},$($($($($($($($($($($($($($({},qg),yH),_H),wH),xH),bH),kH),SH),EH),CH),PH),AH),TH),RH));const IH=(function(){Jr.SDK_DIST_CHANNEL="npm";const t=Jf[jf]=new th;return(function(){function e(){e.done||(e.done=!0,SR=!1,Pt(Jf,function(n){n._dom_loaded()}))}ke!=null&&ke.addEventListener?ke.readyState==="complete"?e():_t(ke,"DOMContentLoaded",e,{capture:!1}):oe&&he.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();var $e=IH,Mt;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{const i={};for(const o of s)i[o]=o;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(const l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},t.find=(s,i)=>{for(const o of s)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Mt||(Mt={}));var dE;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(dE||(dE={}));const Ne=Mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Aa=t=>{switch(typeof t){case"undefined":return Ne.undefined;case"string":return Ne.string;case"number":return Number.isNaN(t)?Ne.nan:Ne.number;case"boolean":return Ne.boolean;case"function":return Ne.function;case"bigint":return Ne.bigint;case"symbol":return Ne.symbol;case"object":return Array.isArray(t)?Ne.array:t===null?Ne.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Ne.promise:typeof Map<"u"&&t instanceof Map?Ne.map:typeof Set<"u"&&t instanceof Set?Ne.set:typeof Date<"u"&&t instanceof Date?Ne.date:Ne.object;default:return Ne.unknown}},we=Mt.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Go extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let l=r,u=0;for(;u<o.path.length;){const d=o.path[u];u===o.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(n(o))):l[d]=l[d]||{_errors:[]},l=l[d],u++}}};return s(this),r}static assert(e){if(!(e instanceof Go))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Mt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},r=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Go.create=t=>new Go(t);const j2=(t,e)=>{let n;switch(t.code){case we.invalid_type:t.received===Ne.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case we.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Mt.jsonStringifyReplacer)}`;break;case we.unrecognized_keys:n=`Unrecognized key(s) in object: ${Mt.joinValues(t.keys,", ")}`;break;case we.invalid_union:n="Invalid input";break;case we.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Mt.joinValues(t.options)}`;break;case we.invalid_enum_value:n=`Invalid enum value. Expected ${Mt.joinValues(t.options)}, received '${t.received}'`;break;case we.invalid_arguments:n="Invalid function arguments";break;case we.invalid_return_type:n="Invalid function return type";break;case we.invalid_date:n="Invalid date";break;case we.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Mt.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case we.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case we.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case we.custom:n="Invalid input";break;case we.invalid_intersection_types:n="Intersection results could not be merged";break;case we.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case we.not_finite:n="Number must be finite";break;default:n=e.defaultError,Mt.assertNever(t)}return{message:n}};let MH=j2;function OH(){return MH}const LH=t=>{const{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}};function Pe(t,e){const n=OH(),r=LH({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===j2?void 0:j2].filter(s=>!!s)});t.common.issues.push(r)}class Br{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const s of n){if(s.status==="aborted")return ot;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const s of n){const i=await s.key,o=await s.value;r.push({key:i,value:o})}return Br.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const s of n){const{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return ot;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}}const ot=Object.freeze({status:"aborted"}),$f=t=>({status:"dirty",value:t}),ri=t=>({status:"valid",value:t}),fE=t=>t.status==="aborted",hE=t=>t.status==="dirty",ud=t=>t.status==="valid",Jm=t=>typeof Promise<"u"&&t instanceof Promise;var Ze;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(Ze||(Ze={}));class Ji{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const pE=(t,e)=>{if(ud(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Go(t.common.issues);return this._error=n,this._error}}};function ht(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{const{message:u}=t;return o.code==="invalid_enum_value"?{message:u??l.defaultError}:typeof l.data>"u"?{message:u??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:u??n??l.defaultError}},description:s}}class St{get description(){return this._def.description}_getType(e){return Aa(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Aa(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Br,ctx:{common:e.parent.common,data:e.data,parsedType:Aa(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(Jm(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){const r={common:{issues:[],async:(n==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Aa(e)},s=this._parseSync({data:e,path:r.path,parent:r});return pE(r,s)}"~validate"(e){var r,s;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Aa(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:n});return ud(i)?{value:i.value}:{issues:n.common.issues}}catch(i){(s=(r=i==null?void 0:i.message)==null?void 0:r.toLowerCase())!=null&&s.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(i=>ud(i)?{value:i.value}:{issues:n.common.issues})}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Aa(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Jm(s)?s:Promise.resolve(s));return pE(r,i)}refine(e,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const o=e(s),l=()=>i.addIssue({code:we.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Sc({schema:this,typeName:lt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Uo.create(this,this._def)}nullable(){return kc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ki.create(this)}promise(){return ig.create(this,this._def)}or(e){return tg.create([this,e],this._def)}and(e){return ng.create(this,e,this._def)}transform(e){return new Sc({...ht(this._def),schema:this,typeName:lt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new og({...ht(this._def),innerType:this,defaultValue:n,typeName:lt.ZodDefault})}brand(){return new UR({typeName:lt.ZodBranded,type:this,...ht(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new ag({...ht(this._def),innerType:this,catchValue:n,typeName:lt.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ib.create(this,e)}readonly(){return lg.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const NH=/^c[^\s-]{8,}$/i,DH=/^[0-9a-z]+$/,jH=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$H=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,FH=/^[a-z0-9_-]{21}$/i,VH=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,HH=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,zH=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,UH="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Yy;const BH=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,WH=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ZH=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,qH=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,GH=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,KH=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,VR="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",YH=new RegExp(`^${VR}$`);function HR(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function XH(t){return new RegExp(`^${HR(t)}$`)}function QH(t){let e=`${VR}T${HR(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function JH(t,e){return!!((e==="v4"||!e)&&BH.test(t)||(e==="v6"||!e)&&ZH.test(t))}function ez(t,e){if(!VH.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&(s==null?void 0:s.typ)!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function tz(t,e){return!!((e==="v4"||!e)&&WH.test(t)||(e==="v6"||!e)&&qH.test(t))}class zo extends St{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Ne.string){const i=this._getOrReturnCtx(e);return Pe(i,{code:we.invalid_type,expected:Ne.string,received:i.parsedType}),ot}const r=new Br;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?Pe(s,{code:we.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&Pe(s,{code:we.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")zH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"email",code:we.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Yy||(Yy=new RegExp(UH,"u")),Yy.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"emoji",code:we.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")$H.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"uuid",code:we.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")FH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"nanoid",code:we.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")NH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"cuid",code:we.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")DH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"cuid2",code:we.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")jH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"ulid",code:we.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),Pe(s,{validation:"url",code:we.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"regex",code:we.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?QH(i).test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?YH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?XH(i).test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?HH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"duration",code:we.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?JH(e.data,i.version)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"ip",code:we.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?ez(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"jwt",code:we.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?tz(e.data,i.version)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"cidr",code:we.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?GH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"base64",code:we.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?KH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"base64url",code:we.invalid_string,message:i.message}),r.dirty()):Mt.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:we.invalid_string,...Ze.errToObj(r)})}_addCheck(e){return new zo({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Ze.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Ze.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Ze.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Ze.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Ze.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Ze.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Ze.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Ze.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Ze.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Ze.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Ze.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Ze.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Ze.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...Ze.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...Ze.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...Ze.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...Ze.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n==null?void 0:n.position,...Ze.errToObj(n==null?void 0:n.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...Ze.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...Ze.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...Ze.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...Ze.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...Ze.errToObj(n)})}nonempty(e){return this.min(1,Ze.errToObj(e))}trim(){return new zo({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new zo({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new zo({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}zo.create=t=>new zo({checks:[],typeName:lt.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...ht(t)});function nz(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}class dd extends St{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Ne.number){const i=this._getOrReturnCtx(e);return Pe(i,{code:we.invalid_type,expected:Ne.number,received:i.parsedType}),ot}let r;const s=new Br;for(const i of this._def.checks)i.kind==="int"?Mt.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?nz(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.not_finite,message:i.message}),s.dirty()):Mt.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Ze.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Ze.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Ze.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Ze.toString(n))}setLimit(e,n,r,s){return new dd({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Ze.toString(s)}]})}_addCheck(e){return new dd({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Ze.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ze.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ze.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ze.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ze.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Ze.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:Ze.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ze.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ze.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Mt.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}}dd.create=t=>new dd({checks:[],typeName:lt.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...ht(t)});class _h extends St{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Ne.bigint)return this._getInvalidInput(e);let r;const s=new Br;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):Mt.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return Pe(n,{code:we.invalid_type,expected:Ne.bigint,received:n.parsedType}),ot}gte(e,n){return this.setLimit("min",e,!0,Ze.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Ze.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Ze.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Ze.toString(n))}setLimit(e,n,r,s){return new _h({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Ze.toString(s)}]})}_addCheck(e){return new _h({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ze.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ze.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ze.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ze.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Ze.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}_h.create=t=>new _h({checks:[],typeName:lt.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...ht(t)});class $2 extends St{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Ne.boolean){const r=this._getOrReturnCtx(e);return Pe(r,{code:we.invalid_type,expected:Ne.boolean,received:r.parsedType}),ot}return ri(e.data)}}$2.create=t=>new $2({typeName:lt.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...ht(t)});class eg extends St{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Ne.date){const i=this._getOrReturnCtx(e);return Pe(i,{code:we.invalid_type,expected:Ne.date,received:i.parsedType}),ot}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return Pe(i,{code:we.invalid_date}),ot}const r=new Br;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):Mt.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new eg({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:Ze.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:Ze.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}eg.create=t=>new eg({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:lt.ZodDate,...ht(t)});class mE extends St{_parse(e){if(this._getType(e)!==Ne.symbol){const r=this._getOrReturnCtx(e);return Pe(r,{code:we.invalid_type,expected:Ne.symbol,received:r.parsedType}),ot}return ri(e.data)}}mE.create=t=>new mE({typeName:lt.ZodSymbol,...ht(t)});class F2 extends St{_parse(e){if(this._getType(e)!==Ne.undefined){const r=this._getOrReturnCtx(e);return Pe(r,{code:we.invalid_type,expected:Ne.undefined,received:r.parsedType}),ot}return ri(e.data)}}F2.create=t=>new F2({typeName:lt.ZodUndefined,...ht(t)});class V2 extends St{_parse(e){if(this._getType(e)!==Ne.null){const r=this._getOrReturnCtx(e);return Pe(r,{code:we.invalid_type,expected:Ne.null,received:r.parsedType}),ot}return ri(e.data)}}V2.create=t=>new V2({typeName:lt.ZodNull,...ht(t)});class gE extends St{constructor(){super(...arguments),this._any=!0}_parse(e){return ri(e.data)}}gE.create=t=>new gE({typeName:lt.ZodAny,...ht(t)});class H2 extends St{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ri(e.data)}}H2.create=t=>new H2({typeName:lt.ZodUnknown,...ht(t)});class Xa extends St{_parse(e){const n=this._getOrReturnCtx(e);return Pe(n,{code:we.invalid_type,expected:Ne.never,received:n.parsedType}),ot}}Xa.create=t=>new Xa({typeName:lt.ZodNever,...ht(t)});class vE extends St{_parse(e){if(this._getType(e)!==Ne.undefined){const r=this._getOrReturnCtx(e);return Pe(r,{code:we.invalid_type,expected:Ne.void,received:r.parsedType}),ot}return ri(e.data)}}vE.create=t=>new vE({typeName:lt.ZodVoid,...ht(t)});class Ki extends St{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==Ne.array)return Pe(n,{code:we.invalid_type,expected:Ne.array,received:n.parsedType}),ot;if(s.exactLength!==null){const o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&(Pe(n,{code:o?we.too_big:we.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(Pe(n,{code:we.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(Pe(n,{code:we.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>s.type._parseAsync(new Ji(n,o,n.path,l)))).then(o=>Br.mergeArray(r,o));const i=[...n.data].map((o,l)=>s.type._parseSync(new Ji(n,o,n.path,l)));return Br.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new Ki({...this._def,minLength:{value:e,message:Ze.toString(n)}})}max(e,n){return new Ki({...this._def,maxLength:{value:e,message:Ze.toString(n)}})}length(e,n){return new Ki({...this._def,exactLength:{value:e,message:Ze.toString(n)}})}nonempty(e){return this.min(1,e)}}Ki.create=(t,e)=>new Ki({type:t,minLength:null,maxLength:null,exactLength:null,typeName:lt.ZodArray,...ht(e)});function Su(t){if(t instanceof Hn){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=Uo.create(Su(r))}return new Hn({...t._def,shape:()=>e})}else return t instanceof Ki?new Ki({...t._def,type:Su(t.element)}):t instanceof Uo?Uo.create(Su(t.unwrap())):t instanceof kc?kc.create(Su(t.unwrap())):t instanceof xc?xc.create(t.items.map(e=>Su(e))):t}class Hn extends St{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=Mt.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==Ne.object){const d=this._getOrReturnCtx(e);return Pe(d,{code:we.invalid_type,expected:Ne.object,received:d.parsedType}),ot}const{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof Xa&&this._def.unknownKeys==="strip"))for(const d in s.data)o.includes(d)||l.push(d);const u=[];for(const d of o){const f=i[d],h=s.data[d];u.push({key:{status:"valid",value:d},value:f._parse(new Ji(s,h,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof Xa){const d=this._def.unknownKeys;if(d==="passthrough")for(const f of l)u.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(d==="strict")l.length>0&&(Pe(s,{code:we.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const f of l){const h=s.data[f];u.push({key:{status:"valid",value:f},value:d._parse(new Ji(s,h,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const f of u){const h=await f.key,m=await f.value;d.push({key:h,value:m,alwaysSet:f.alwaysSet})}return d}).then(d=>Br.mergeObjectSync(r,d)):Br.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return Ze.errToObj,new Hn({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{var i,o;const s=((o=(i=this._def).errorMap)==null?void 0:o.call(i,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:Ze.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new Hn({...this._def,unknownKeys:"strip"})}passthrough(){return new Hn({...this._def,unknownKeys:"passthrough"})}extend(e){return new Hn({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Hn({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:lt.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new Hn({...this._def,catchall:e})}pick(e){const n={};for(const r of Mt.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new Hn({...this._def,shape:()=>n})}omit(e){const n={};for(const r of Mt.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new Hn({...this._def,shape:()=>n})}deepPartial(){return Su(this)}partial(e){const n={};for(const r of Mt.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new Hn({...this._def,shape:()=>n})}required(e){const n={};for(const r of Mt.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Uo;)i=i._def.innerType;n[r]=i}return new Hn({...this._def,shape:()=>n})}keyof(){return zR(Mt.objectKeys(this.shape))}}Hn.create=(t,e)=>new Hn({shape:()=>t,unknownKeys:"strip",catchall:Xa.create(),typeName:lt.ZodObject,...ht(e)});Hn.strictCreate=(t,e)=>new Hn({shape:()=>t,unknownKeys:"strict",catchall:Xa.create(),typeName:lt.ZodObject,...ht(e)});Hn.lazycreate=(t,e)=>new Hn({shape:t,unknownKeys:"strip",catchall:Xa.create(),typeName:lt.ZodObject,...ht(e)});class tg extends St{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const o=i.map(l=>new Go(l.ctx.common.issues));return Pe(n,{code:we.invalid_union,unionErrors:o}),ot}if(n.common.async)return Promise.all(r.map(async i=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i;const o=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},f=u._parseSync({data:n.data,path:n.path,parent:d});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=o.map(u=>new Go(u));return Pe(n,{code:we.invalid_union,unionErrors:l}),ot}}get options(){return this._def.options}}tg.create=(t,e)=>new tg({options:t,typeName:lt.ZodUnion,...ht(e)});const Ro=t=>t instanceof U2?Ro(t.schema):t instanceof Sc?Ro(t.innerType()):t instanceof sg?[t.value]:t instanceof bc?t.options:t instanceof B2?Mt.objectValues(t.enum):t instanceof og?Ro(t._def.innerType):t instanceof F2?[void 0]:t instanceof V2?[null]:t instanceof Uo?[void 0,...Ro(t.unwrap())]:t instanceof kc?[null,...Ro(t.unwrap())]:t instanceof UR||t instanceof lg?Ro(t.unwrap()):t instanceof ag?Ro(t._def.innerType):[];class sb extends St{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ne.object)return Pe(n,{code:we.invalid_type,expected:Ne.object,received:n.parsedType}),ot;const r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Pe(n,{code:we.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),ot)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){const s=new Map;for(const i of n){const o=Ro(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new sb({typeName:lt.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ht(r)})}}function z2(t,e){const n=Aa(t),r=Aa(e);if(t===e)return{valid:!0,data:t};if(n===Ne.object&&r===Ne.object){const s=Mt.objectKeys(e),i=Mt.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(const l of i){const u=z2(t[l],e[l]);if(!u.valid)return{valid:!1};o[l]=u.data}return{valid:!0,data:o}}else if(n===Ne.array&&r===Ne.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<t.length;i++){const o=t[i],l=e[i],u=z2(o,l);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return n===Ne.date&&r===Ne.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class ng extends St{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(fE(i)||fE(o))return ot;const l=z2(i.value,o.value);return l.valid?((hE(i)||hE(o))&&n.dirty(),{status:n.value,value:l.data}):(Pe(r,{code:we.invalid_intersection_types}),ot)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ng.create=(t,e,n)=>new ng({left:t,right:e,typeName:lt.ZodIntersection,...ht(n)});class xc extends St{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ne.array)return Pe(r,{code:we.invalid_type,expected:Ne.array,received:r.parsedType}),ot;if(r.data.length<this._def.items.length)return Pe(r,{code:we.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ot;!this._def.rest&&r.data.length>this._def.items.length&&(Pe(r,{code:we.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((o,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ji(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Br.mergeArray(n,o)):Br.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new xc({...this._def,rest:e})}}xc.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new xc({items:t,typeName:lt.ZodTuple,rest:null,...ht(e)})};class rg extends St{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ne.object)return Pe(r,{code:we.invalid_type,expected:Ne.object,received:r.parsedType}),ot;const s=[],i=this._def.keyType,o=this._def.valueType;for(const l in r.data)s.push({key:i._parse(new Ji(r,l,r.path,l)),value:o._parse(new Ji(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?Br.mergeObjectAsync(n,s):Br.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof St?new rg({keyType:e,valueType:n,typeName:lt.ZodRecord,...ht(r)}):new rg({keyType:zo.create(),valueType:e,typeName:lt.ZodRecord,...ht(n)})}}class yE extends St{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ne.map)return Pe(r,{code:we.invalid_type,expected:Ne.map,received:r.parsedType}),ot;const s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,u],d)=>({key:s._parse(new Ji(r,l,r.path,[d,"key"])),value:i._parse(new Ji(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of o){const d=await u.key,f=await u.value;if(d.status==="aborted"||f.status==="aborted")return ot;(d.status==="dirty"||f.status==="dirty")&&n.dirty(),l.set(d.value,f.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of o){const d=u.key,f=u.value;if(d.status==="aborted"||f.status==="aborted")return ot;(d.status==="dirty"||f.status==="dirty")&&n.dirty(),l.set(d.value,f.value)}return{status:n.value,value:l}}}}yE.create=(t,e,n)=>new yE({valueType:e,keyType:t,typeName:lt.ZodMap,...ht(n)});class wh extends St{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ne.set)return Pe(r,{code:we.invalid_type,expected:Ne.set,received:r.parsedType}),ot;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(Pe(r,{code:we.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(Pe(r,{code:we.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function o(u){const d=new Set;for(const f of u){if(f.status==="aborted")return ot;f.status==="dirty"&&n.dirty(),d.add(f.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ji(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>o(u)):o(l)}min(e,n){return new wh({...this._def,minSize:{value:e,message:Ze.toString(n)}})}max(e,n){return new wh({...this._def,maxSize:{value:e,message:Ze.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}wh.create=(t,e)=>new wh({valueType:t,minSize:null,maxSize:null,typeName:lt.ZodSet,...ht(e)});class U2 extends St{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}U2.create=(t,e)=>new U2({getter:t,typeName:lt.ZodLazy,...ht(e)});class sg extends St{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return Pe(n,{received:n.data,code:we.invalid_literal,expected:this._def.value}),ot}return{status:"valid",value:e.data}}get value(){return this._def.value}}sg.create=(t,e)=>new sg({value:t,typeName:lt.ZodLiteral,...ht(e)});function zR(t,e){return new bc({values:t,typeName:lt.ZodEnum,...ht(e)})}class bc extends St{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return Pe(n,{expected:Mt.joinValues(r),received:n.parsedType,code:we.invalid_type}),ot}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return Pe(n,{received:n.data,code:we.invalid_enum_value,options:r}),ot}return ri(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return bc.create(e,{...this._def,...n})}exclude(e,n=this._def){return bc.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}}bc.create=zR;class B2 extends St{_parse(e){const n=Mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Ne.string&&r.parsedType!==Ne.number){const s=Mt.objectValues(n);return Pe(r,{expected:Mt.joinValues(s),received:r.parsedType,code:we.invalid_type}),ot}if(this._cache||(this._cache=new Set(Mt.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Mt.objectValues(n);return Pe(r,{received:r.data,code:we.invalid_enum_value,options:s}),ot}return ri(e.data)}get enum(){return this._def.values}}B2.create=(t,e)=>new B2({values:t,typeName:lt.ZodNativeEnum,...ht(e)});class ig extends St{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ne.promise&&n.common.async===!1)return Pe(n,{code:we.invalid_type,expected:Ne.promise,received:n.parsedType}),ot;const r=n.parsedType===Ne.promise?n.data:Promise.resolve(n.data);return ri(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ig.create=(t,e)=>new ig({type:t,typeName:lt.ZodPromise,...ht(e)});class Sc extends St{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===lt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{Pe(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return ot;const u=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return u.status==="aborted"?ot:u.status==="dirty"||n.value==="dirty"?$f(u.value):u});{if(n.value==="aborted")return ot;const l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?ot:l.status==="dirty"||n.value==="dirty"?$f(l.value):l}}if(s.type==="refinement"){const o=l=>{const u=s.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?ot:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?ot:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ud(o))return ot;const l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>ud(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):ot);Mt.assertNever(s)}}Sc.create=(t,e,n)=>new Sc({schema:t,typeName:lt.ZodEffects,effect:e,...ht(n)});Sc.createWithPreprocess=(t,e,n)=>new Sc({schema:e,effect:{type:"preprocess",transform:t},typeName:lt.ZodEffects,...ht(n)});class Uo extends St{_parse(e){return this._getType(e)===Ne.undefined?ri(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Uo.create=(t,e)=>new Uo({innerType:t,typeName:lt.ZodOptional,...ht(e)});class kc extends St{_parse(e){return this._getType(e)===Ne.null?ri(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}kc.create=(t,e)=>new kc({innerType:t,typeName:lt.ZodNullable,...ht(e)});class og extends St{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===Ne.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}og.create=(t,e)=>new og({innerType:t,typeName:lt.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ht(e)});class ag extends St{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Jm(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ag.create=(t,e)=>new ag({innerType:t,typeName:lt.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ht(e)});class _E extends St{_parse(e){if(this._getType(e)!==Ne.nan){const r=this._getOrReturnCtx(e);return Pe(r,{code:we.invalid_type,expected:Ne.nan,received:r.parsedType}),ot}return{status:"valid",value:e.data}}}_E.create=t=>new _E({typeName:lt.ZodNaN,...ht(t)});class UR extends St{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class ib extends St{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?ot:i.status==="dirty"?(n.dirty(),$f(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?ot:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new ib({in:e,out:n,typeName:lt.ZodPipeline})}}class lg extends St{_parse(e){const n=this._def.innerType._parse(e),r=s=>(ud(s)&&(s.value=Object.freeze(s.value)),s);return Jm(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}lg.create=(t,e)=>new lg({innerType:t,typeName:lt.ZodReadonly,...ht(e)});var lt;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(lt||(lt={}));const Ke=zo.create,ob=dd.create,Za=$2.create,Zae=H2.create;Xa.create;const Ec=Ki.create,yn=Hn.create,rz=tg.create,sz=sb.create;ng.create;xc.create;const BR=rg.create,wE=sg.create,cr=bc.create;ig.create;Uo.create;kc.create;const iz=ot,hi=ob().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),oz=yn({command:cr(["open","status","stop","wait","auth.status","variants.start","variants.status","variants.get","variants.list","variants.complete","variants.cancel","reference.fetch","evidence.capture"]).optional(),tool_name:cr(["rivet_login","rivet_explore_designs","rivet_get_exploration","rivet_cancel_exploration","rivet_complete_variant_work","rivet_get_design_context","rivet_find_references","rivet_save_reference","rivet_remove_reference","rivet_preview_reference_import","rivet_import_references","rivet_connect_reference_account","rivet_discover_reference_collections","rivet_save_design_preference","rivet_remove_design_preference","rivet_save_design_check","rivet_remove_design_check","rivet_run_design_check"]).optional(),caller_agent:cr(["claude","codex","cursor","unknown","other"]).optional(),mcp_editor:cr(["claude","claude-desktop","codex","cursor","unknown","other"]).optional(),source:cr(["cli","mcp","core","ui","visual_editor"]).optional(),surface:cr(["cli","mcp","visual_editor"]).optional(),mode:cr(["initial_generation","zero_to_one","source_grounded","comment_refine","vary","history_adoption","commit","unknown"]).optional(),entry_point:cr(["mcp_tool","visual_editor_comment","variants_panel","history","watch_loop","route","unknown","login_command","signin_command","install_flow","tool_call","account_menu","library","menu","onboarding","editor_gate","cli","mcp"]).optional(),project_context_kind:cr(["existing","fresh"]).optional(),preview_kind:cr(["dev_server","static_artifact"]).optional(),provider:cr(["pinterest","arena","cosmos","x"]).optional(),request_status:cr(["accepted","rejected","completed","failed","cancelled","degraded","superseded"]).optional(),error_code:cr(["OPERATION_FAILED","USAGE_ERROR","AUTH_REQUIRED","SERVER_UNAVAILABLE","WAIT_TIMEOUT","SESSION_NOT_FOUND","WORK_ITEM_NOT_FOUND","MCP_REMOVED","STATIC_PREVIEW_FAILED","DEV_SERVER_FAILED","PREVIEW_UNAVAILABLE"]).optional(),failure_reason:cr(["ack_failed","active_session","destination_not_empty","feature_disabled","invalid_stage_action","lease_expired","missing_artifact","missing_required_input","pending_change_conflict","queue_full","runtime_validation_failed","schema_validation_failed","source_context_invalid","start_in_flight","target_not_editable","timeout","unknown","work_item_not_found","local_server_failed","oauth_failed","popup_blocked","credential_store_failed","popup_closed","provider_failed","request_failed","auth_required","invalid_arguments","operation_failed","server_unavailable","usage_error","wait_timeout","session_not_found","mcp_removed","server_start_timeout","handshake_missing","handshake_invalid","process_not_running","health_check_failed","plugin_context_mismatch","telemetry_policy_mismatch","server_starting","transport_failed","server_shutdown_pending","server_process_exited","server_upgrade_required","replacement_version_mismatch","replacement_health_failed","app_health_failed","dev_server_resolution_failed","rivet_port_unavailable","editor_server_start_failed"]).optional(),ok:Za().optional(),is_recoverable:Za().optional(),is_fresh:Za().optional(),duration_ms:hi.optional(),dwell_ms_from_terminal:hi.optional(),exit_code:hi.optional(),requested_count:hi.optional(),accepted_count:hi.optional(),work_item_count:hi.optional(),completed_count:hi.optional(),failed_count:hi.optional(),cancelled_count:hi.optional(),reference_count:hi.optional(),changed_files_count:hi.optional()}),az=new Set(["cli_command_completed","cli_auth_started","cli_auth_completed","cli_auth_failed","mcp_auth_started","mcp_auth_completed","mcp_auth_failed","mcp_tool_executed","mcp_tool_failed","mcp_login_failed","mcp_login_started","mcp_login_completed","visual_editor_auth_started","visual_editor_auth_completed","visual_editor_auth_failed","visual_editor_reference_connection_started","visual_editor_reference_connection_completed","visual_editor_reference_connection_failed","agent_variants.request_started","agent_variants.request_accepted","agent_variants.request_rejected","agent_variants.refinement_requested","agent_variants.refinement_completed","agent_variants.refinement_failed","agent_variants.round_started","agent_variants.round_completed","agent_variants.preview_started","agent_variants.preview_ready","agent_variants.preview_failed"]),lz=(t,e)=>{if(!az.has(t))return null;const n={};for(const[r,s]of Object.entries(oz.shape)){const i=s.safeParse(e[r]);i.success&&i.data!==void 0&&(n[r]=i.data)}return n},cz=yn({token:Ke().min(1)}),uz=t=>cz.parse(t).token,Gg="rivet_library_token";let Ko="",fd=0,bi=null,xE=!1;const W2=new Set,xh=()=>W2.forEach(t=>t()),qae=()=>bi,Gae=()=>fd,bh=()=>{try{const t=window.localStorage.getItem(Gg)??"";Ko!==t&&(fd+=1),Ko=t,bi=null}catch{bi="Rivet cannot access browser storage. Allow site storage and try again."}},WR=()=>{xE||(window.addEventListener("storage",t=>{t.key!==Gg&&t.key!==null||(bh(),xh())}),xE=!0)},Kae=()=>!!Ko,Yae=t=>(WR(),W2.add(t),()=>W2.delete(t)),dz=(t,e)=>{if(e!==void 0&&bh(),e!==void 0&&e!==fd)throw new Error("Sign-in was cancelled because the browser login changed.");try{window.localStorage.setItem(Gg,t)}catch{throw bi="Rivet cannot save browser access. Allow site storage and try again.",xh(),new Error(bi)}Ko=t,fd+=1,bi=null,xh()},ZR=()=>{Ko="",fd+=1,bi=null;try{window.localStorage.removeItem(Gg)}catch{bi="Rivet cannot clear browser storage. Allow site storage and try again."}xh()},fz=async()=>{if(!window.location.pathname.startsWith("/rivet/library"))return;WR(),bh();const t=fd,e=new URLSearchParams(window.location.hash.slice(1)).get("code");if(e){window.history.replaceState(null,"",window.location.pathname+window.location.search);try{const n=await fetch("/api/library/browser-sessions/exchange",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(n.ok){dz(uz(await n.json()),t);return}n.status>=500&&!Ko&&(bi="Rivet is temporarily unavailable. Please retry this link.")}catch{!Ko&&!bi&&(bi="Rivet could not open this link. Please retry when the server is available.")}}xh()},qR=async(t,e={})=>{bh();const n=Ko,r=new Headers(e.headers);r.set("Authorization",`Bearer ${n}`);const s=await fetch(t,{...e,headers:r});return s.status===401&&(bh(),Ko===n&&ZR()),s},hz=async(t,e={})=>{const n=await qR(`/api/library${t}`,{method:e.method??"GET",signal:e.signal,headers:{"Content-Type":"application/json"},...e.body!==void 0?{body:JSON.stringify(e.body)}:{}});return pz(n)},pz=async t=>{const e=await t.text();let n;try{n=JSON.parse(e)}catch{if(t.ok)throw new Error("The library returned an invalid response.")}if(!t.ok){if(t.status===401)throw new Error("Sign in to access this library.");const r=n&&typeof n=="object"&&"error"in n&&typeof n.error=="string"&&n.error.trim()?n.error:`Library request failed (${t.status}).`;throw new Error(r)}return n},bt=(t,e={})=>{if(!window.location.pathname.startsWith("/rivet/library")){const n=new Headers(e.headers),r=_7();return r&&v7(t,e.method)&&n.set(p7,r),fetch(t,{...e,headers:n,redirect:"error"})}return qR(t,e)};let GR="off";const bE=t=>{GR=t},Z2=()=>GR==="full",mz="phc_Ntj9tXHbS64XgYxlTfhglRmFivFsfm0AERph4ZlnNH",gz=3e3,vz=/^plugin-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,yz=t=>({person_profiles:"never",autocapture:!1,opt_out_useragent_filter:!0,capture_pageview:!1,capture_pageleave:!1,capture_exceptions:!1,capture_performance:!1,disable_session_recording:!0,enable_recording_console_log:!1,disable_external_dependency_loading:!0,disable_surveys:!0,advanced_disable_flags:!0,advanced_disable_feature_flags:!0,mask_all_text:!0,mask_all_element_attributes:!0,persistence:"memory",bootstrap:{distinctID:t,isIdentifiedID:!1},before_send:e=>{const n=lz(e.event,e.properties);return n&&bt("/api/telemetry/events",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:e.event,properties:n}),keepalive:!0}).catch(()=>{}),null}}),_z=async()=>{try{const t=await bt("/api/telemetry",{signal:AbortSignal.timeout(gz),cache:"no-store"});if(!t.ok)return;const e=await t.json();if(e.mode!=="full"&&e.mode!=="metrics"||e.mode==="metrics"&&(typeof e.distinctId!="string"||!vz.test(e.distinctId)))return;const n=e.mode,s={api_host:"https://rivet-proxy.onrender.com/ingest",ui_host:"https://us.posthog.com",person_profiles:"always",capture_exceptions:!0,autocapture:!0,capture_pageview:!0,capture_performance:!0,persistence:"localStorage",...{session_recording:{maskAllInputs:!0,maskTextSelector:"[data-rivet-private]",blockSelector:"iframe[data-rivet-private]"}},mask_all_text:!1,mask_all_element_attributes:!1,loaded:i=>i.register({source:"visual_editor",surface:"visual_editor",telemetry_version:2,rivet_version:"0.26.0",env:"production"})};n==="metrics"&&Object.assign(s,yz(e.distinctId),{api_host:window.location.origin}),$e.init(mz,s),bE(n)}catch{bE("off")}},KR=g.createContext(void 0),YR=t=>{const e=g.useContext(KR);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},wz=({client:t,children:e})=>(g.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),S.jsx(KR.Provider,{value:t,children:e})),xz={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)};var Ta,Mx,r5,bz=(r5=class{constructor(){tt(this,Ta,xz);tt(this,Mx,!1)}setTimeoutProvider(t){Ae(this,Ta,t)}setTimeout(t,e){return Z(this,Ta).setTimeout(t,e)}clearTimeout(t){Z(this,Ta).clearTimeout(t)}setInterval(t,e){return Z(this,Ta).setInterval(t,e)}clearInterval(t){Z(this,Ta).clearInterval(t)}},Ta=new WeakMap,Mx=new WeakMap,r5);const Kl=new bz;function Sz(t){setTimeout(t,0)}const kz=typeof window>"u"||"Deno"in globalThis;function es(){}function Ez(t,e){return typeof t=="function"?t(e):t}function XR(t){return typeof t=="number"&&t>=0&&t!==1/0}function QR(t,e){return Math.max(t+(e||0)-Date.now(),0)}function mn(t,e){return typeof t=="function"?t(e):t}function SE(t,e){const{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:l}=t;if(o){if(r){if(e.queryHash!==ab(o,e.options))return!1}else if(!hd(e.queryKey,o))return!1}if(n!=="all"){const u=e.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&e.isStale()!==l||s&&s!==e.state.fetchStatus||i&&!i(e))}function kE(t,e){const{exact:n,status:r,predicate:s,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(n){if(Sh(e.options.mutationKey)!==Sh(i))return!1}else if(!hd(e.options.mutationKey,i))return!1}return!(r&&e.state.status!==r||s&&!s(e))}function ab(t,e){return((e==null?void 0:e.queryKeyHashFn)||Sh)(t)}function Sh(t){return JSON.stringify(t,(e,n)=>q2(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function hd(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(Array.isArray(t)&&Array.isArray(e)){if(e.length>t.length)return!1;for(let r=0;r<e.length;r++)if(!hd(t[r],e[r]))return!1;return!0}const n=Object.keys(e);for(const r of n)if(!hd(t[r],e[r]))return!1;return!0}return!1}const Cz=Object.prototype.hasOwnProperty;function JR(t,e,n=0){if(t===e)return t;if(n>500)return e;const r=EE(t)&&EE(e);if(!r&&!(q2(t)&&q2(e)))return e;const s=(r?t:Object.keys(t)).length,i=r?e:Object.keys(e),o=i.length,l=r?new Array(o):{};let u=0;for(let d=0;d<o;d++){const f=r?d:i[d],h=t[f],m=e[f];if(h===m){l[f]=h,(r?d<s:Cz.call(t,f))&&u++;continue}if(h===null||m===null||typeof h!="object"||typeof m!="object"){l[f]=m;continue}const v=JR(h,m,n+1);l[f]=v,v===h&&u++}return s===o&&u===s?t:l}function Xy(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(const n in t)if(t[n]!==e[n])return!1;return!0}function EE(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function q2(t){if(!CE(t))return!1;const e=Object.getPrototypeOf(t),n=e==null?void 0:e.constructor;if(n===void 0)return!0;if(typeof n!="function")return!1;const r=n.prototype;return!(!CE(r)||!r.hasOwnProperty("isPrototypeOf")||e!==Object.prototype)}function CE(t){return Object.prototype.toString.call(t)==="[object Object]"}function Pz(t){return new Promise(e=>{Kl.setTimeout(e,t)})}function G2(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?JR(t,e):e}function Az(t,e,n=0){const r=[...t,e];return n&&r.length>n?r.slice(1):r}function Tz(t,e,n=0){const r=[e,...t];return n&&r.length>n?r.slice(0,-1):r}const lb=Symbol();function eI(t,e){return!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===lb?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function tI(t,e){return typeof t=="function"?t(...e):!!t}function Rz(t,e,n){let r=!1,s;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(s??(s=e()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),t}let Iz=()=>kz;const cb=()=>Iz();var Xh=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Jl,Ra,Bu,s5,Mz=(s5=class extends Xh{constructor(){super();tt(this,Jl);tt(this,Ra);tt(this,Bu);Ae(this,Bu,e=>{if(typeof window<"u"&&window.addEventListener){const n=()=>e();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){Z(this,Ra)||this.setEventListener(Z(this,Bu))}onUnsubscribe(){var e;this.hasListeners()||((e=Z(this,Ra))==null||e.call(this),Ae(this,Ra,void 0))}setEventListener(e){var n;Ae(this,Bu,e),(n=Z(this,Ra))==null||n.call(this),Ae(this,Ra,e(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(e){Z(this,Jl)!==e&&(Ae(this,Jl,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(n=>{n(e)})}isFocused(){var e;return typeof Z(this,Jl)=="boolean"?Z(this,Jl):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},Jl=new WeakMap,Ra=new WeakMap,Bu=new WeakMap,s5);const ub=new Mz,Oz=Sz;function Lz(){let t=[],e=0,n=l=>{l()},r=l=>{l()},s=Oz;const i=l=>{e?t.push(l):s(()=>{n(l)})},o=()=>{const l=t;t=[],l.length&&s(()=>{r(()=>{l.forEach(u=>{n(u)})})})};return{batch:l=>{let u;e++;try{u=l()}finally{e--,e||o()}return u},batchCalls:l=>(...u)=>{i(()=>{l(...u)})},schedule:i,setNotifyFunction:l=>{n=l},setBatchNotifyFunction:l=>{r=l},setScheduler:l=>{s=l}}}const vr=Lz();var Wu,Ia,Zu,i5,Nz=(i5=class extends Xh{constructor(){super();tt(this,Wu,!0);tt(this,Ia);tt(this,Zu);Ae(this,Zu,e=>{if(typeof window<"u"&&window.addEventListener){const n=()=>e(!0),r=()=>e(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){Z(this,Ia)||this.setEventListener(Z(this,Zu))}onUnsubscribe(){var e;this.hasListeners()||((e=Z(this,Ia))==null||e.call(this),Ae(this,Ia,void 0))}setEventListener(e){var n;Ae(this,Zu,e),(n=Z(this,Ia))==null||n.call(this),Ae(this,Ia,e(this.setOnline.bind(this)))}setOnline(e){Z(this,Wu)!==e&&(Ae(this,Wu,e),this.listeners.forEach(n=>{n(e)}))}isOnline(){return Z(this,Wu)}},Wu=new WeakMap,Ia=new WeakMap,Zu=new WeakMap,i5);const cg=new Nz;function Dz(t){return Math.min(1e3*2**t,3e4)}function nI(t){return(t??"online")==="online"?cg.isOnline():!0}var K2=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function rI(t){let e=!1,n=0,r,s="pending",i,o;const l=new Promise((k,C)=>{i=k,o=C});l.catch(es);const u=()=>s!=="pending",d=k=>{var C;if(!u()){const P=new K2(k);_(P),(C=t.onCancel)==null||C.call(t,P)}},f=()=>{e=!0},h=()=>{e=!1},m=()=>ub.isFocused()&&(t.networkMode==="always"||cg.isOnline())&&t.canRun(),v=()=>nI(t.networkMode)&&t.canRun(),w=k=>{u()||(r==null||r(),s="resolved",i(k))},_=k=>{u()||(r==null||r(),s="rejected",o(k))},x=k=>new Promise(C=>{var P;r=T=>{(u()||k())&&C(T)},(P=t.onPause)==null||P.call(t)}).then(()=>{var C;r=void 0,u()||(C=t.onContinue)==null||C.call(t)}),b=()=>{if(u())return;let k;const C=n===0?t.initialPromise:void 0;try{k=C??t.fn()}catch(P){k=Promise.reject(P)}Promise.resolve(k).then(w).catch(P=>{var L;if(u())return;const T=t.retry??(cb()?0:3),M=t.retryDelay??Dz,I=typeof M=="function"?M(n,P):M,R=T===!0||typeof T=="number"&&n<T||typeof T=="function"&&T(n,P);if(e||!R){_(P);return}n++,(L=t.onFail)==null||L.call(t,n,P),Pz(I).then(()=>m()?void 0:x(m)).then(()=>{e?_(P):b()})})};return{promise:l,status:()=>s,cancel:d,continue:()=>(r==null||r(),l),cancelRetry:f,continueRetry:h,canStart:v,start:()=>(v()?b():x(v).then(b),l)}}var ec,o5,sI=(o5=class{constructor(){tt(this,ec)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),XR(this.gcTime)&&Ae(this,ec,Kl.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(cb()?1/0:3e5))}clearGcTimeout(){Z(this,ec)!==void 0&&(Kl.clearTimeout(Z(this,ec)),Ae(this,ec,void 0))}},ec=new WeakMap,o5);function jz(t){return{onFetch:(e,n)=>{var f,h,m,v,w;const r=e.options,s=(m=(h=(f=e.fetchOptions)==null?void 0:f.meta)==null?void 0:h.fetchMore)==null?void 0:m.direction,i=((v=e.state.data)==null?void 0:v.pages)||[],o=((w=e.state.data)==null?void 0:w.pageParams)||[];let l={pages:[],pageParams:[]},u=0;const d=async()=>{let _=!1;const x=C=>{Rz(C,()=>e.signal,()=>_=!0)},b=eI(e.options,e.fetchOptions),k=async(C,P,T)=>{if(_)return Promise.reject(e.signal.reason);if(P==null&&C.pages.length)return Promise.resolve(C);const I=(()=>{const F={client:e.client,queryKey:e.queryKey,pageParam:P,direction:T?"backward":"forward",meta:e.options.meta};return x(F),F})(),R=await b(I),{maxPages:L}=e.options,j=T?Tz:Az;return{pages:j(C.pages,R,L),pageParams:j(C.pageParams,P,L)}};if(s&&i.length){const C=s==="backward",P=C?$z:PE,T={pages:i,pageParams:o};l=await k(T,P(r,T),C)}else{const C=t??i.length;do{const P=u===0?o[0]===void 0?r.initialPageParam:o[0]:PE(r,l);if(u>0&&P==null)break;l=await k(l,P),u++}while(u<C)}return l};e.options.persister?e.fetchFn=()=>{var _,x;return(x=(_=e.options).persister)==null?void 0:x.call(_,d,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},n)}:e.fetchFn=d}}}function PE(t,{pages:e,pageParams:n}){const r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,n[r],n):void 0}function $z(t,{pages:e,pageParams:n}){var r;return e.length>0?(r=t.getPreviousPageParam)==null?void 0:r.call(t,e[0],e,n[0],n):void 0}var qu,tc,Gu,Ks,nc,Kn,Wh,rc,yi,Io,a5,Fz=(a5=class extends sI{constructor(e){super();tt(this,yi);tt(this,qu);tt(this,tc);tt(this,Gu);tt(this,Ks);tt(this,nc);tt(this,Kn);tt(this,Wh);tt(this,rc);Ae(this,rc,!1),Ae(this,Wh,e.defaultOptions),this.setOptions(e.options),this.observers=[],Ae(this,nc,e.client),Ae(this,Ks,Z(this,nc).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,Ae(this,tc,TE(this.options)),this.state=e.state??Z(this,tc),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return Z(this,qu)}get promise(){var e;return(e=Z(this,Kn))==null?void 0:e.promise}setOptions(e){if(this.options={...Z(this,Wh),...e},e!=null&&e._type&&Ae(this,qu,e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=TE(this.options);n.data!==void 0&&(this.setState(AE(n.data,n.dataUpdatedAt)),Ae(this,tc,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Z(this,Ks).remove(this)}setData(e,n){const r=G2(this.state.data,e,this.options);return xt(this,yi,Io).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(e){xt(this,yi,Io).call(this,{type:"setState",state:e})}cancel(e){var r,s;const n=(r=Z(this,Kn))==null?void 0:r.promise;return(s=Z(this,Kn))==null||s.cancel(e),n?n.then(es).catch(es):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return Z(this,tc)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>mn(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===lb||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>mn(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!QR(this.state.dataUpdatedAt,e)}onFocus(){var e,n;(e=this.observers.find(r=>r.shouldFetchOnWindowFocus()))==null||e.refetch({cancelRefetch:!1}),(n=Z(this,Kn))==null||n.continue()}onOnline(){var e,n;(e=this.observers.find(r=>r.shouldFetchOnReconnect()))==null||e.refetch({cancelRefetch:!1}),(n=Z(this,Kn))==null||n.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),Z(this,Ks).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){const n=this.observers.indexOf(e);n!==-1&&(this.observers.splice(n,1),this.observers.length||(Z(this,Kn)&&(Z(this,rc)||this.state.fetchStatus==="paused"&&this.state.status==="pending"?Z(this,Kn).cancel({revert:!0}):Z(this,Kn).cancelRetry()),this.scheduleGc()),Z(this,Ks).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||xt(this,yi,Io).call(this,{type:"invalidate"})}async fetch(e,n){var d,f,h,m,v,w,_,x,b,k,C,P;if(this.state.fetchStatus!=="idle"&&((d=Z(this,Kn))==null?void 0:d.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(Z(this,Kn))return Z(this,Kn).continueRetry(),Z(this,Kn).promise}if(e&&this.setOptions(e),!this.options.queryFn){const T=this.observers.find(M=>M.options.queryFn);T&&this.setOptions(T.options)}const r=new AbortController,s=T=>{Object.defineProperty(T,"signal",{enumerable:!0,get:()=>(Ae(this,rc,!0),r.signal)})},i=()=>{const T=eI(this.options,n),I=(()=>{const R={client:Z(this,nc),queryKey:this.queryKey,meta:this.meta};return s(R),R})();return Ae(this,rc,!1),this.options.persister?this.options.persister(T,I,this):T(I)},l=(()=>{const T={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:Z(this,nc),state:this.state,fetchFn:i};return s(T),T})();(f=Z(this,qu)==="infinite"?jz(this.options.pages):this.options.behavior)==null||f.onFetch(l,this),Ae(this,Gu,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((h=l.fetchOptions)==null?void 0:h.meta))&&xt(this,yi,Io).call(this,{type:"fetch",meta:(m=l.fetchOptions)==null?void 0:m.meta});const u=Ae(this,Kn,rI({initialPromise:n==null?void 0:n.initialPromise,fn:l.fetchFn,onCancel:T=>{T instanceof K2&&T.revert&&this.setState({...Z(this,Gu),fetchStatus:"idle"}),r.abort()},onFail:(T,M)=>{xt(this,yi,Io).call(this,{type:"failed",failureCount:T,error:M})},onPause:()=>{xt(this,yi,Io).call(this,{type:"pause"})},onContinue:()=>{xt(this,yi,Io).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0}));try{const T=await u.start();if(T===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(T),(w=(v=Z(this,Ks).config).onSuccess)==null||w.call(v,T,this),(x=(_=Z(this,Ks).config).onSettled)==null||x.call(_,T,this.state.error,this),T}catch(T){if(T instanceof K2){if(T.silent)return Z(this,Kn).promise;if(T.revert){if(this.state.data===void 0)throw T;return this.state.data}}throw xt(this,yi,Io).call(this,{type:"error",error:T}),(k=(b=Z(this,Ks).config).onError)==null||k.call(b,T,this),(P=(C=Z(this,Ks).config).onSettled)==null||P.call(C,this.state.data,T,this),T}finally{Z(this,Kn)===u&&Ae(this,Kn,void 0),this.scheduleGc()}}},qu=new WeakMap,tc=new WeakMap,Gu=new WeakMap,Ks=new WeakMap,nc=new WeakMap,Kn=new WeakMap,Wh=new WeakMap,rc=new WeakMap,yi=new WeakSet,Io=function(e){const n=r=>{switch(e.type){case"failed":return{...r,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...iI(r.data,this.options),fetchMeta:e.meta??null};case"success":const s={...r,...AE(e.data,e.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Ae(this,Gu,e.manual?s:void 0),s;case"error":const i=e.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...e.state}}};this.state=n(this.state),vr.batch(()=>{this.observers.slice().forEach(r=>{r.onQueryUpdate()}),Z(this,Ks).notify({query:this,type:"updated",action:e})})},a5);function iI(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:nI(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function AE(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function TE(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,n=e!==void 0,r=n?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var $r,kt,Zh,Fr,sc,Ku,Do,qh,Yu,Xu,ic,oc,Ma,Qu,Ft,Ff,Y2,X2,Q2,J2,ew,tw,nw,rw,l5,Vz=(l5=class extends Xh{constructor(e,n){super();tt(this,Ft);tt(this,$r);tt(this,kt);tt(this,Zh);tt(this,Fr);tt(this,sc);tt(this,Ku);tt(this,Do);tt(this,qh);tt(this,Yu);tt(this,Xu);tt(this,ic);tt(this,oc);tt(this,Ma);tt(this,Qu,new Set);this.options=n,Ae(this,$r,e),Ae(this,Do,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Z(this,kt).addObserver(this),RE(Z(this,kt),this.options)?xt(this,Ft,Ff).call(this):this.updateResult(),xt(this,Ft,ew).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return sw(Z(this,kt),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return sw(Z(this,kt),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,xt(this,Ft,tw).call(this),xt(this,Ft,nw).call(this),Z(this,kt).removeObserver(this)}setOptions(e){const n=this.options,r=Z(this,kt);if(this.options=Z(this,$r).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof mn(this.options.enabled,Z(this,kt))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");xt(this,Ft,rw).call(this),Z(this,kt).setOptions(this.options),n._defaulted&&!Xy(this.options,n)&&Z(this,$r).getQueryCache().notify({type:"observerOptionsUpdated",query:Z(this,kt),observer:this});const s=this.hasListeners();s&&IE(Z(this,kt),r,this.options,n)&&xt(this,Ft,Ff).call(this),this.updateResult(),s&&(Z(this,kt)!==r||mn(this.options.enabled,Z(this,kt))!==mn(n.enabled,Z(this,kt))||mn(this.options.staleTime,Z(this,kt))!==mn(n.staleTime,Z(this,kt)))&&xt(this,Ft,X2).call(this);const i=xt(this,Ft,Q2).call(this);s&&(Z(this,kt)!==r||mn(this.options.enabled,Z(this,kt))!==mn(n.enabled,Z(this,kt))||i!==Z(this,Ma))&&xt(this,Ft,J2).call(this,i)}getOptimisticResult(e){const n=Z(this,$r).getQueryCache().build(Z(this,$r),e),r=this.createResult(n,e);return Xy(this.getCurrentResult(),r)||(Ae(this,Fr,r),Ae(this,Ku,this.options),Ae(this,sc,Z(this,kt).state)),r}getCurrentResult(){return Z(this,Fr)}trackResult(e,n){return new Proxy(e,{get:(r,s)=>(this.trackProp(s),n==null||n(s),Reflect.get(r,s))})}trackProp(e){Z(this,Qu).add(e)}getCurrentQuery(){return Z(this,kt)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const n=Z(this,$r).defaultQueryOptions(e),r=Z(this,$r).getQueryCache().build(Z(this,$r),n);let s=()=>{},i;const o=new Promise(l=>{i=l,s=Z(this,$r).getQueryCache().subscribe(u=>{u.type==="updated"&&u.query.queryHash===r.queryHash&&r.state.data!==void 0&&(s(),l(this.createResult(r,n)))})});return Promise.race([r.fetch(n).then(()=>{const l=this.createResult(r,n);return i==null||i(l),l}).finally(()=>{s()}),o])}fetch(e){return xt(this,Ft,Ff).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),Z(this,Fr)))}createResult(e,n){var M;const r=Z(this,kt),s=this.options,i=Z(this,Fr),o=Z(this,sc),l=Z(this,Ku),u=e!==r?e.state:Z(this,Zh),{state:d}=e;let f={...d},h=!1,m;if(n._optimisticResults){const I=this.hasListeners(),R=!I&&RE(e,n),L=I&&IE(e,r,n,s);(R||L)&&(f={...f,...iI(d.data,e.options)}),n._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:v,errorUpdatedAt:w,status:_}=f;m=f.data;let x=!1;if(n.placeholderData!==void 0&&m===void 0&&_==="pending"){let I;i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData)?(I=i.data,x=!0):I=typeof n.placeholderData=="function"?n.placeholderData((M=Z(this,Xu))==null?void 0:M.state.data,Z(this,Xu)):n.placeholderData,I!==void 0&&(_="success",m=G2(i==null?void 0:i.data,I,n),h=!0)}if(n.select&&m!==void 0&&!x)if(i&&m===(o==null?void 0:o.data)&&n.select===Z(this,qh))m=Z(this,Yu);else try{Ae(this,qh,n.select),m=n.select(m),m=G2(i==null?void 0:i.data,m,n),Ae(this,Yu,m),Ae(this,Do,null)}catch(I){Ae(this,Do,I)}else m===void 0&&Ae(this,Do,null);Z(this,Do)&&(v=Z(this,Do),m=Z(this,Yu),w=Date.now(),_="error",h=!1);const b=f.fetchStatus==="fetching",k=_==="pending",C=_==="error",P=k&&b,T=m!==void 0;return{status:_,fetchStatus:f.fetchStatus,isPending:k,isSuccess:_==="success",isError:C,isInitialLoading:P,isLoading:P,data:m,dataUpdatedAt:f.dataUpdatedAt,error:v,errorUpdatedAt:w,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:f.dataUpdateCount>u.dataUpdateCount||f.errorUpdateCount>u.errorUpdateCount,isFetching:b,isRefetching:b&&!k,isLoadingError:C&&!T,isPaused:f.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:C&&T,isStale:db(e,n),refetch:this.refetch,isEnabled:mn(n.enabled,e)!==!1}}updateResult(){const e=Z(this,Fr),n=this.createResult(Z(this,kt),this.options);if(Ae(this,sc,Z(this,kt).state),Ae(this,Ku,this.options),Z(this,sc).data!==void 0&&Ae(this,Xu,Z(this,kt)),Xy(n,e))return;Ae(this,Fr,n);const s=(()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,o=typeof i=="function"?i():i;if(o==="all"||!o&&!Z(this,Qu).size)return!0;const l=new Set(o??Z(this,Qu));return this.options.throwOnError&&l.add("error"),Object.keys(Z(this,Fr)).some(u=>{const d=u;return Z(this,Fr)[d]!==e[d]&&l.has(d)})})();vr.batch(()=>{s&&this.listeners.forEach(i=>{i(Z(this,Fr))}),Z(this,$r).getQueryCache().notify({query:Z(this,kt),type:"observerResultsUpdated"})})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&xt(this,Ft,ew).call(this)}},$r=new WeakMap,kt=new WeakMap,Zh=new WeakMap,Fr=new WeakMap,sc=new WeakMap,Ku=new WeakMap,Do=new WeakMap,qh=new WeakMap,Yu=new WeakMap,Xu=new WeakMap,ic=new WeakMap,oc=new WeakMap,Ma=new WeakMap,Qu=new WeakMap,Ft=new WeakSet,Ff=function(e){xt(this,Ft,rw).call(this);let n=Z(this,kt).fetch(this.options,e);return e!=null&&e.throwOnError||(n=n.catch(es)),n},Y2=function(e){return!cb()&&mn(this.options.enabled,Z(this,kt))!==!1&&XR(e)},X2=function(){xt(this,Ft,tw).call(this);const e=mn(this.options.staleTime,Z(this,kt));if(Z(this,Fr).isStale||!xt(this,Ft,Y2).call(this,e))return;const n=QR(Z(this,Fr).dataUpdatedAt,e)+1;Ae(this,ic,Kl.setTimeout(()=>{Z(this,Fr).isStale||this.updateResult()},n))},Q2=function(){return mn(this.options.refetchInterval,Z(this,kt))??!1},J2=function(e){xt(this,Ft,nw).call(this),Ae(this,Ma,e),!(Z(this,Ma)===0||!xt(this,Ft,Y2).call(this,Z(this,Ma)))&&Ae(this,oc,Kl.setInterval(()=>{(this.options.refetchIntervalInBackground||ub.isFocused())&&xt(this,Ft,Ff).call(this)},Z(this,Ma)))},ew=function(){xt(this,Ft,X2).call(this),xt(this,Ft,J2).call(this,xt(this,Ft,Q2).call(this))},tw=function(){Z(this,ic)!==void 0&&(Kl.clearTimeout(Z(this,ic)),Ae(this,ic,void 0))},nw=function(){Z(this,oc)!==void 0&&(Kl.clearInterval(Z(this,oc)),Ae(this,oc,void 0))},rw=function(){const e=Z(this,$r).getQueryCache().build(Z(this,$r),this.options);if(e===Z(this,kt))return;const n=Z(this,kt);Ae(this,kt,e),Ae(this,Zh,e.state),this.hasListeners()&&(n==null||n.removeObserver(this),e.addObserver(this))},l5);function Hz(t,e){return mn(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&mn(e.retryOnMount,t)===!1)}function RE(t,e){return Hz(t,e)||t.state.data!==void 0&&sw(t,e,e.refetchOnMount)}function sw(t,e,n){if(mn(e.enabled,t)!==!1&&mn(e.staleTime,t)!=="static"){const r=mn(n,t);return r==="always"||r!==!1&&db(t,e)}return!1}function IE(t,e,n,r){return(t!==e||mn(r.enabled,t)===!1)&&(!n.suspense||t.state.status!=="error")&&db(t,n)}function db(t,e){return mn(e.enabled,t)!==!1&&t.isStaleByTime(mn(e.staleTime,t))}var Gh,Vi,Er,ac,Hi,Ca,c5,zz=(c5=class extends sI{constructor(e){super();tt(this,Hi);tt(this,Gh);tt(this,Vi);tt(this,Er);tt(this,ac);Ae(this,Gh,e.client),this.mutationId=e.mutationId,Ae(this,Er,e.mutationCache),Ae(this,Vi,[]),this.state=e.state||Uz(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){Z(this,Vi).includes(e)||(Z(this,Vi).push(e),this.clearGcTimeout(),Z(this,Er).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){Ae(this,Vi,Z(this,Vi).filter(n=>n!==e)),this.scheduleGc(),Z(this,Er).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){Z(this,Vi).length||(this.state.status==="pending"?this.scheduleGc():Z(this,Er).remove(this))}continue(){var e;return((e=Z(this,ac))==null?void 0:e.continue())??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(e){var l,u,d,f,h,m,v,w,_,x,b,k,C,P,T,M,I,R;const n=()=>{xt(this,Hi,Ca).call(this,{type:"continue"})},r={client:Z(this,Gh),meta:this.options.meta,mutationKey:this.options.mutationKey},s=Ae(this,ac,rI({fn:()=>this.options.mutationFn?this.options.mutationFn(e,r):Promise.reject(new Error("No mutationFn found")),onFail:(L,j)=>{xt(this,Hi,Ca).call(this,{type:"failed",failureCount:L,error:j})},onPause:()=>{xt(this,Hi,Ca).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Z(this,Er).canRun(this)})),i=this.state.status==="pending",o=!s.canStart();try{if(i)n();else{xt(this,Hi,Ca).call(this,{type:"pending",variables:e,isPaused:o}),Z(this,Er).config.onMutate&&await Z(this,Er).config.onMutate(e,this,r);const j=await((u=(l=this.options).onMutate)==null?void 0:u.call(l,e,r));j!==this.state.context&&xt(this,Hi,Ca).call(this,{type:"pending",context:j,variables:e,isPaused:o})}const L=await s.start();return await((f=(d=Z(this,Er).config).onSuccess)==null?void 0:f.call(d,L,e,this.state.context,this,r)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,L,e,this.state.context,r)),await((w=(v=Z(this,Er).config).onSettled)==null?void 0:w.call(v,L,null,this.state.variables,this.state.context,this,r)),await((x=(_=this.options).onSettled)==null?void 0:x.call(_,L,null,e,this.state.context,r)),xt(this,Hi,Ca).call(this,{type:"success",data:L}),L}catch(L){try{await((k=(b=Z(this,Er).config).onError)==null?void 0:k.call(b,L,e,this.state.context,this,r))}catch(j){Promise.reject(j)}try{await((P=(C=this.options).onError)==null?void 0:P.call(C,L,e,this.state.context,r))}catch(j){Promise.reject(j)}try{await((M=(T=Z(this,Er).config).onSettled)==null?void 0:M.call(T,void 0,L,this.state.variables,this.state.context,this,r))}catch(j){Promise.reject(j)}try{await((R=(I=this.options).onSettled)==null?void 0:R.call(I,void 0,L,e,this.state.context,r))}catch(j){Promise.reject(j)}throw xt(this,Hi,Ca).call(this,{type:"error",error:L}),L}finally{Z(this,ac)===s&&Ae(this,ac,void 0),Z(this,Er).runNext(this)}}},Gh=new WeakMap,Vi=new WeakMap,Er=new WeakMap,ac=new WeakMap,Hi=new WeakSet,Ca=function(e){const n=r=>{switch(e.type){case"failed":return{...r,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...r,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:e.error,failureCount:r.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=n(this.state),vr.batch(()=>{Z(this,Vi).forEach(r=>{r.onMutationUpdate(e)}),Z(this,Er).notify({mutation:this,type:"updated",action:e})})},c5);function Uz(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Oa,_i,Kh,u5,Bz=(u5=class extends Xh{constructor(e={}){super();tt(this,Oa);tt(this,_i);tt(this,Kh);this.config=e,Ae(this,Oa,new Set),Ae(this,_i,new Map),Ae(this,Kh,0)}build(e,n,r){const s=new zz({client:e,mutationCache:this,mutationId:++v0(this,Kh)._,options:e.defaultMutationOptions(n),state:r});return this.add(s),s}add(e){Z(this,Oa).add(e);const n=A0(e);if(typeof n=="string"){const r=Z(this,_i).get(n);r?r.push(e):Z(this,_i).set(n,[e])}this.notify({type:"added",mutation:e})}remove(e){if(Z(this,Oa).delete(e)){const n=A0(e);if(typeof n=="string"){const r=Z(this,_i).get(n);if(r)if(r.length>1){const s=r.indexOf(e);s!==-1&&r.splice(s,1)}else r[0]===e&&Z(this,_i).delete(n)}}this.notify({type:"removed",mutation:e})}canRun(e){var r;const n=A0(e);if(typeof n=="string"){const s=(r=Z(this,_i).get(n))==null?void 0:r.find(i=>i.state.status==="pending");return!s||s===e}else return!0}runNext(e){var r,s;const n=A0(e);return typeof n=="string"?((s=(r=Z(this,_i).get(n))==null?void 0:r.find(i=>i!==e&&i.state.isPaused))==null?void 0:s.continue())??Promise.resolve():Promise.resolve()}clear(){vr.batch(()=>{const e=this.getAll();Z(this,Oa).clear(),Z(this,_i).clear(),e.forEach(n=>{this.notify({type:"removed",mutation:n})})})}getAll(){return Array.from(Z(this,Oa))}find(e){const n={exact:!0,...e};return this.getAll().find(r=>kE(n,r))}findAll(e={}){return this.getAll().filter(n=>kE(e,n))}notify(e){vr.batch(()=>{this.listeners.forEach(n=>{n(e)})})}resumePausedMutations(){const e=this.getAll().filter(n=>n.state.isPaused);return vr.batch(()=>Promise.all(e.map(n=>n.continue().catch(es))))}},Oa=new WeakMap,_i=new WeakMap,Kh=new WeakMap,u5);function A0(t){var e;return(e=t.options.scope)==null?void 0:e.id}var zi,d5,Wz=(d5=class extends Xh{constructor(e={}){super();tt(this,zi);this.config=e,Ae(this,zi,new Map)}build(e,n,r){const s=n.queryKey,i=n.queryHash??ab(s,n);let o=this.get(i);return o||(o=new Fz({client:e,queryKey:s,queryHash:i,options:e.defaultQueryOptions(n),state:r,defaultOptions:e.getQueryDefaults(s)}),this.add(o)),o}add(e){Z(this,zi).has(e.queryHash)||(Z(this,zi).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){Z(this,zi).get(e.queryHash)===e&&(e.destroy(),Z(this,zi).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){vr.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return Z(this,zi).get(e)}getAll(){return[...Z(this,zi).values()]}find(e){const n={exact:!0,...e};return this.getAll().find(r=>SE(n,r))}findAll(e={}){const n=this.getAll();return Object.keys(e).length>0?n.filter(r=>SE(e,r)):n}notify(e){vr.batch(()=>{this.listeners.forEach(n=>{n(e)})})}onFocus(){vr.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){vr.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},zi=new WeakMap,d5),bn,La,Na,Ju,ed,Da,td,nd,f5,Zz=(f5=class{constructor(t={}){tt(this,bn);tt(this,La);tt(this,Na);tt(this,Ju);tt(this,ed);tt(this,Da);tt(this,td);tt(this,nd);Ae(this,bn,t.queryCache||new Wz),Ae(this,La,t.mutationCache||new Bz),Ae(this,Na,t.defaultOptions||{}),Ae(this,Ju,new Map),Ae(this,ed,new Map),Ae(this,Da,0)}mount(){v0(this,Da)._++,Z(this,Da)===1&&(Ae(this,td,ub.subscribe(async t=>{t&&(await this.resumePausedMutations(),Z(this,bn).onFocus())})),Ae(this,nd,cg.subscribe(async t=>{t&&(await this.resumePausedMutations(),Z(this,bn).onOnline())})))}unmount(){var t,e;v0(this,Da)._--,Z(this,Da)===0&&((t=Z(this,td))==null||t.call(this),Ae(this,td,void 0),(e=Z(this,nd))==null||e.call(this),Ae(this,nd,void 0))}isFetching(t){return Z(this,bn).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return Z(this,La).findAll({...t,status:"pending"}).length}getQueryData(t){var n;const e=this.defaultQueryOptions({queryKey:t});return(n=Z(this,bn).get(e.queryHash))==null?void 0:n.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),n=Z(this,bn).build(this,e),r=n.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&n.isStaleByTime(mn(e.staleTime,n))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return Z(this,bn).findAll(t).map(({queryKey:e,state:n})=>[e,n.data])}setQueryData(t,e,n){var o;const r=this.defaultQueryOptions({queryKey:t}),s=(o=Z(this,bn).get(r.queryHash))==null?void 0:o.state.data,i=Ez(e,s);if(i!==void 0)return Z(this,bn).build(this,r).setData(i,{...n,manual:!0})}setQueriesData(t,e,n){return vr.batch(()=>Z(this,bn).findAll(t).map(({queryKey:r})=>[r,this.setQueryData(r,e,n)]))}getQueryState(t){var n;const e=this.defaultQueryOptions({queryKey:t});return(n=Z(this,bn).get(e.queryHash))==null?void 0:n.state}removeQueries(t){const e=Z(this,bn);vr.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){const n=Z(this,bn);return vr.batch(()=>{const r=n.findAll(t),s=new Set(r);return r.forEach(i=>{i.reset()}),this.refetchQueries({type:"active",predicate:i=>s.has(i)},e)})}cancelQueries(t,e={}){const n={revert:!0,...e},r=vr.batch(()=>Z(this,bn).findAll(t).map(s=>s.cancel(n)));return Promise.all(r).then(es).catch(es)}invalidateQueries(t,e={}){return vr.batch(()=>(Z(this,bn).findAll(t).forEach(n=>{n.invalidate()}),(t==null?void 0:t.refetchType)==="none"?Promise.resolve():this.refetchQueries({...t,type:(t==null?void 0:t.refetchType)??(t==null?void 0:t.type)??"active"},e)))}refetchQueries(t,e={}){const n={...e,cancelRefetch:e.cancelRefetch??!0},r=vr.batch(()=>Z(this,bn).findAll(t).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(es)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(es)}async query(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const n=Z(this,bn).build(this,e),r=n.isStaleByTime(mn(e.staleTime,n))?await n.fetch(e):n.state.data,s=e.select;return s?s(r):r}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const n=Z(this,bn).build(this,e);return n.isStaleByTime(mn(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(es).catch(es)}infiniteQuery(t){return t._type="infinite",this.query(t)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(es).catch(es)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return cg.isOnline()?Z(this,La).resumePausedMutations():Promise.resolve()}getQueryCache(){return Z(this,bn)}getMutationCache(){return Z(this,La)}getDefaultOptions(){return Z(this,Na)}setDefaultOptions(t){Ae(this,Na,t)}setQueryDefaults(t,e){Z(this,Ju).set(Sh(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...Z(this,Ju).values()],n={};return e.forEach(r=>{hd(t,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(t,e){Z(this,ed).set(Sh(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...Z(this,ed).values()],n={};return e.forEach(r=>{hd(t,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(t){if(t._defaulted)return t;const e={...Z(this,Na).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=ab(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===lb&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...Z(this,Na).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){Z(this,bn).clear(),Z(this,La).clear()}},bn=new WeakMap,La=new WeakMap,Na=new WeakMap,Ju=new WeakMap,ed=new WeakMap,Da=new WeakMap,td=new WeakMap,nd=new WeakMap,f5);const oI=g.createContext(!1),qz=()=>g.useContext(oI);oI.Provider;function Gz(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}const Kz=g.createContext(Gz()),Yz=()=>g.useContext(Kz),Xz=(t,e,n)=>{const r=(n==null?void 0:n.state.status)==="error"&&typeof t.throwOnError=="function"?tI(t.throwOnError,[n.state.error,n]):t.throwOnError;(t.suspense||r)&&(e.isReset()||(t.retryOnMount=!1))},Qz=t=>{g.useEffect(()=>{t.clearReset()},[t])},Jz=({result:t,errorResetBoundary:e,throwOnError:n,query:r,suspense:s})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(s&&t.data===void 0||tI(n,[t.error,r])),eU=t=>{if(t.suspense){const n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=t.staleTime;t.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},tU=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,nU=(t,e,n)=>e.fetchOptimistic(t).catch(()=>{n.clearReset()});function rU(t,e,n){const r=qz(),s=Yz(),i=YR(),o=i.defaultQueryOptions(t),l=i.getQueryCache().get(o.queryHash),u=t.subscribed!==!1;o._optimisticResults=r?"isRestoring":u?"optimistic":void 0,eU(o),Xz(o,s,l),Qz(s);const[d]=g.useState(()=>new e(i,o)),f=d.getOptimisticResult(o),h=!r&&u;if(g.useSyncExternalStore(g.useCallback(m=>{const v=h?d.subscribe(vr.batchCalls(m)):es;return d.updateResult(),v},[d,h]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),g.useEffect(()=>{d.setOptions(o)},[o,d]),tU(o,f))throw nU(o,d,s);if(Jz({result:f,errorResetBoundary:s,throwOnError:o.throwOnError,query:l,suspense:o.suspense}))throw f.error;return o.notifyOnChangeProps?f:d.trackResult(f)}function kh(t,e){return rU(t,Vz)}var sU=(function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(r[i]=s[i])},t(e,n)};return function(e,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();var iU=function(t,e,n){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:n?"".concat(n," ",e):e})},T0,ME="__POSTHOG_REACT_SHARED_STATE__",OE=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},Eh;try{Eh=OE[ME]=OE[ME]||new WeakMap}catch{Eh=new WeakMap}Eh.has(g.createContext)||Eh.set(g.createContext,{});var dc=Eh.get(g.createContext),iw;function oU(t){(!dc.defaultPostHogInstance||dc.defaultPostHogInstance===iw)&&(dc.defaultPostHogInstance=t),iw=t}function ow(){return iw}dc.context||(dc.context=g.createContext({get client(){return ow()||dc.defaultPostHogInstance},bootstrap:void 0}));var fb=dc.context;function aI(t,e,n){if(n===void 0&&(n=new WeakMap),t===e)return!0;if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;if(n.has(t)&&n.get(t)===e)return!0;n.set(t,e);var r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return!1;for(var i=0,o=r;i<o.length;i++){var l=o[i];if(!s.includes(l)||!aI(t[l],e[l],n))return!1}return!0}function aU(t){var e,n,r=t.children,s=t.client,i=t.apiKey,o=t.options,l=g.useRef(null),u=g.useMemo(function(){if(s)return i&&console.warn("[PostHog.js] You have provided both `client` and `apiKey` to `PostHogProvider`. `apiKey` will be ignored in favour of `client`."),o&&console.warn("[PostHog.js] You have provided both `client` and `options` to `PostHogProvider`. `options` will be ignored in favour of `client`."),s;var d=ow();return i||console.warn("[PostHog.js] No `apiKey` or `client` were provided to `PostHogProvider`. Using default global `window.posthog` instance. You must initialize it manually. This is not recommended behavior."),d},[s,i,JSON.stringify(o)]);return g.useEffect(function(){if(!(s||!i)){var d=ow(),f=l.current;f?(i!==f.apiKey&&console.warn("[PostHog.js] You have provided a different `apiKey` to `PostHogProvider` than the one that was already initialized. This is not supported by our provider and we'll keep using the previous key. If you need to toggle between API Keys you need to control the `client` yourself and pass it in as a prop rather than an `apiKey` prop."),o&&!aI(o,f.options)&&d.set_config(o),l.current={apiKey:i,options:o??{}}):(d.__loaded&&console.warn("[PostHog.js] `posthog` was already loaded elsewhere. This may cause issues."),d.init(i,o),l.current={apiKey:i,options:o??{}})}},[s,i,JSON.stringify(o)]),_e.createElement(fb.Provider,{value:{client:u,bootstrap:(e=o==null?void 0:o.bootstrap)!==null&&e!==void 0?e:(n=s==null?void 0:s.config)===null||n===void 0?void 0:n.bootstrap}},r)}var Qy=function(t){return typeof t=="function"},lU=function(t){return t===void 0},si=function(){var t=g.useContext(fb).client;return t},cm=function(t){var e=Object.prototype.toString.call(t);return t instanceof Error||e==="[object Error]"||e==="[object Exception]"||e==="[object DOMException]"||e==="[object DOMError]"},cU=function(t,e){try{Object.defineProperty(t,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}},uU=function(t,e){for(var n=new WeakSet,r=t;!n.has(r);){if(n.add(r),!cm(r.cause)){lU(r.cause)||(e.cause=r.cause),r.cause=e;return}r=r.cause}},dU=function(t,e){if(!e)return t;var n=new Error(cm(t)?t.message:"Primitive value captured as exception: ".concat(String(t)));return cU(n,"React ErrorBoundary ".concat(cm(t)?t.name:"Error")),n.stack=e,cm(t)?(uU(t,n),t):n},LE={componentStack:null,exceptionEvent:null,error:null},fU={INVALID_FALLBACK:"[PostHog.js][PostHogErrorBoundary] Invalid fallback prop, provide a valid React element or a function that returns a valid React element."},hU=(T0=(function(t){sU(e,t);function e(n){var r=t.call(this,n)||this;return r._resetError=function(){r.setState(LE)},r.state=LE,r}return e.prototype.componentDidCatch=function(n,r){var s=this.props.additionalProperties,i;Qy(s)?i=s(n,r):typeof s=="object"&&(i=s);var o=this.context.client,l=r.componentStack,u=o.captureException(dU(n,l),i);this.setState({error:n,componentStack:l??null,exceptionEvent:u})},e.prototype.render=function(){var n=this.props,r=n.children,s=n.fallback,i=this.state;if(i.componentStack==null)return Qy(r)?r():r;var o=Qy(s)?_e.createElement(s,{error:i.error,componentStack:i.componentStack,exceptionEvent:i.exceptionEvent,resetError:this._resetError}):s;return _e.isValidElement(o)?o:(console.warn(fU.INVALID_FALLBACK),_e.createElement(_e.Fragment,null))},e})(_e.Component),iU(T0,"PostHogErrorBoundary"),(function(){T0.contextType=fb})(),T0);oU($e);const pU="rivet-preview-bridge",mU=["ArrowUp","ArrowDown"],gU=new Set(["INPUT","TEXTAREA","SELECT"]),lI=t=>!t||!("tagName"in t)||typeof t.tagName!="string"?!1:gU.has(t.tagName.toUpperCase())||"isContentEditable"in t&&t.isContentEditable===!0,vU=t=>typeof t!="object"||t===null||!("channel"in t)||t.channel!==pU||!("direction"in t)||t.direction!=="event"||!("type"in t)||t.type!=="keydown"||!("key"in t)?null:mU.find(e=>e===t.key)??null,yU=t=>{try{return new URL(t.src,window.location.href).origin}catch{return null}},_U=t=>t.source===null?null:Array.from(document.querySelectorAll("iframe")).find(e=>e.contentWindow===t.source&&yU(e)===t.origin)??null,wU=t=>{const e=n=>{lI(n.target)||t(n)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},xU=()=>{const t=e=>{const n=vU(e.data),r=n?_U(e):null;!n||!r||r.dispatchEvent(new KeyboardEvent("keydown",{key:n,bubbles:!0,cancelable:!0}))};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)};var R0={},Jy={exports:{}},Xr={},e_={exports:{}},t_={};/**
|
|
19
|
+
`),d=Math.min(u.length,o+1e3),f=[];for(let v=o;d>v;v++){const w=u[v];if(w.length>1024)continue;const _=Fk.test(w)?w.replace(Fk,"$1"):w;if(!_.match(/\S*Error: /)){for(const x of s){const b=x(_,r);if(b){l.push(b);const k=J7(l);if(k){for(let C=f.length-1;C>=0;C--){const P=f[C];if(k.start>=P.start+P.length)break;f.pop()}f.push(k)}break}}if(t$(l,f)>=50)break}}const h=[...f].sort((v,w)=>w.start-v.start),m=h[h.length-1];if(m){const v=Q5(l,m);l.splice(m.start-v,v);for(const w of h)w.start-=v}for(const v of h)e$(l,v);return f.some(v=>v.start===0&&l.length===v.length)&&(function(v){const w=v.map(x=>`${x.function}|${x.filename}|${x.lineno}|${x.colno}|${x.module}`);let _=0;for(let x=1;w.length>x;x++)n$(w,x,_)&&(_=x);v.push(...v.splice(0,_))})(l),(function(v){if(!v.length)return[];const w=Array.from(v);return w.reverse(),w.slice(0,50).map(_=>{return $($({},_),{},{filename:_.filename||(x=w,x[x.length-1]||{}).filename,function:_.function||"?"});var x})})(l)}})("web:javascript",K7,Q7)),this._instance=t,this.pp=(e=(n=this._instance.persistence)===null||n===void 0?void 0:n.get_property("$error_tracking_suppression_rules"))!==null&&e!==void 0?e:[],this.mp=Fm(this.yp()),this.bp=new p$(this.mp)}onConfigChange(){this.mp=Fm(this.yp()),this.bp.setConfig(this.mp)}onRemoteConfig(t){var e,n,r;if(!t.ok)return;const s=t.config;if(!("errorTracking"in s))return;const i=(e=(n=s.errorTracking)===null||n===void 0?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(r=s.errorTracking)===null||r===void 0?void 0:r.captureExtensionExceptions;this.pp=i,this._instance.persistence&&this._instance.persistence.register({[_T]:this.pp,[w2]:o})}get _p(){var t;const e=!!this._instance.get_property(w2),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.gp.buildFromUnknown(t,{syntheticException:e==null?void 0:e.syntheticException,mechanism:{handled:e==null?void 0:e.handled}})}addExceptionStep(t,e){if(this.mp.enabled)try{if(!rt(t)||t.trim().length===0)return void fi.warn("Ignoring exception step because message must be a non-empty string");const{sanitizedProperties:n,droppedKeys:r}=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};const i=[];return{sanitizedProperties:Object.keys(s).reduce((o,l)=>h$.has(l)?(i.push(l),o):(o[l]=s[l],o),{}),droppedKeys:i}})(this.wp(e));r.length>0&&fi.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.bp.add($({[jm]:t,[$m]:new Date().toISOString()},n))}catch(n){fi.error("Failed to add exception step. Ignoring breadcrumb.",n)}}sendExceptionEvent(t){try{const e=t.$exception_list;if(this.kp(e)){if(this.Sp(e))return this.xp("Exception dropped: matched a suppression rule"),void fi.info("Skipping exception capture because a suppression rule matched");if(!this._p&&this.$p(e))return this.xp("Exception dropped: thrown by a browser extension"),void fi.info("Skipping exception capture because it was thrown by an extension");if(!this._p&&this.Cp(e))return this.xp("Exception dropped: thrown by an injected browser script"),void fi.info("Skipping exception capture because it was thrown by an injected browser script");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.Tp(e))return this.xp("Exception dropped: thrown by the PostHog SDK"),void fi.info("Skipping exception capture because it was thrown by the PostHog SDK")}const n=this.mp.enabled&&Xe(t.$exception_steps)?this.Ip(t):t,r=(function(){if("u">typeof process){var s;const o=(s=w7.POSTHOG_RELEASE_ID)===null||s===void 0?void 0:s.trim();if(o)return o}const i=globalThis._posthogReleaseId;return typeof i=="string"&&i.length>0?i:void 0})();r&&(n.$release_id=r);try{const s=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",sd:!0});return s&&this.bp.clear(),s}catch(s){return nE(s)||fi.error("Failed to capture exception event. Dropping this exception.",s),void this.bp.clear()}}catch(e){return void(nE(e)||fi.error("Failed to process exception event. Ignoring this exception.",e))}}Ip(t){try{const e=this.bp.getAttachable();return e.length===0?t:$($({},t),{},{$exception_steps:e})}catch(e){return fi.error("Failed to read buffered exception steps. Capturing exception without steps.",e),t}}xp(t){this.mp.enabled&&this.bp.add({[jm]:t,[$m]:new Date().toISOString()})}wp(t){return nt(t)?$({},t):{}}yp(){var t,e;return(t=(e=this._instance.config.error_tracking)===null||e===void 0?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}Sp(t){if(t.length===0)return!1;try{const e=t.reduce((n,{type:r,value:s})=>(rt(r)&&r.length>0&&n.$exception_types.push(r),rt(s)&&s.length>0&&n.$exception_values.push(s),n),{$exception_types:[],$exception_values:[]});return this.pp.some(n=>{const r=n.values.map(s=>{const i=AR[s.operator],o=e[s.key];if(!i||!o)return!1;const l=ze(s.value)?s.value:[s.value];return l.length>0&&i(l,o)});return n.type==="OR"?r.some(Boolean):r.every(Boolean)})}catch(e){return fi.warn("Failed to evaluate suppression rules. Capturing the exception.",e),!1}}$p(t){const e=t.flatMap(r=>{var s,i;return(s=(i=r.stacktrace)===null||i===void 0?void 0:i.frames)!==null&&s!==void 0?s:[]}),n=e.filter(({filename:r})=>!!r&&tH.some(s=>r.startsWith(s)));return n.length!==0&&(!n.every(({filename:r})=>!!r&&r.startsWith(N2))||t.some(({type:r,value:s})=>r==="NoResponse"||rt(s)&&eH.some(({value:i,exact:o})=>o?s===i:s.includes(i)))&&!e.some(({in_app:r,filename:s})=>r&&!(s!=null&&s.startsWith(N2))))}Cp(t){return t.some(({value:e})=>rt(e)&&nH.some(n=>e.includes(n)))}Tp(t){if(t.length>0){var e,n,r,s;const i=(e=(n=t[0].stacktrace)===null||n===void 0?void 0:n.frames)!==null&&e!==void 0?e:[],o=i[i.length-1];return(r=o==null||(s=o.filename)===null||s===void 0?void 0:s.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}kp(t){return!Xe(t)&&ze(t)}}},xH=$({productTours:class{get _c(){return this._instance.persistence}constructor(t){this.Mp=null,this.Ep=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!t.ok)return;const e=t.config;if("productTours"in e){var n,r;if(this._c&&this._c.register({[Bx]:!!e.productTours}),!Wy(this._instance))return!this.Mp&&Xe((n=this._c)===null||n===void 0?void 0:n.props.ph_product_tours)||P0.info("product tours disabled; stopping and clearing cached tours"),(r=this.Mp)===null||r===void 0||r.stop(),this.Mp=null,void this.clearCache();this.loadIfEnabled()}}loadIfEnabled(){!this.Mp&&Wy(this._instance)&&this.Ml(()=>this.Pp())}Ml(t){var e,n,r;!((e=qe.__PosthogExtensions__)===null||e===void 0)&&e.generateProductTours?t():(n=qe.__PosthogExtensions__)===null||n===void 0||(r=n.loadExternalDependency)===null||r===void 0||r.call(n,this._instance,"product-tours",s=>{s?P0.error("Could not load product tours script",s):t()})}Pp(){var t;!this.Mp&&(!((t=qe.__PosthogExtensions__)===null||t===void 0)&&t.generateProductTours)&&(this.Mp=qe.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e=!1){if(ze(this.Ep)&&!e)return void t(this.Ep,{isLoaded:!0});const n=this._c;if(n){const r=n.props[b2];if(ze(r)&&!e)return this.Ep=r,void t(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/product_tours/?token=${this._instance.config.token}`),method:"GET",timestampMode:"query",callback:r=>{if(!Wy(this._instance))return void t([],{isLoaded:!0});const s=r.statusCode;if(s!==200||!r.json){const o=`Product Tours API could not be loaded, status: ${s}`;return s===0?r.error||P0.warn(o):P0.error(o),void t([],{isLoaded:!1,error:o})}const i=ze(r.json.product_tours)?r.json.product_tours:[];this.Ep=i,n&&n.register({[b2]:i}),t(i,{isLoaded:!0})}})}getActiveProductTours(t){Xe(this.Mp)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.Mp.getActiveProductTours(t)}showProductTour(t){var e;(e=this.Mp)===null||e===void 0||e.showTourById(t)}previewTour(t){this.Mp?this.Mp.previewTour(t):this.Ml(()=>{var e;this.Pp(),(e=this.Mp)===null||e===void 0||e.previewTour(t)})}dismissProductTour(){var t;(t=this.Mp)===null||t===void 0||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.Mp)===null||t===void 0||t.nextStep()}previousStep(){var t;(t=this.Mp)===null||t===void 0||t.previousStep()}clearCache(){var t;this.Ep=null,(t=this._c)===null||t===void 0||t.unregister("ph_product_tours")}resetTour(t){var e;(e=this.Mp)===null||e===void 0||e.resetTour(t)}resetAllTours(){var t;(t=this.Mp)===null||t===void 0||t.resetAllTours()}cancelPendingTour(t){var e;(e=this.Mp)===null||e===void 0||e.cancelPendingTour(t)}}},qg),bH={siteApps:class{constructor(t){this._instance=t,this.Rp=0,this.Ap=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Fp(t,e){if(!e)return;const n=this.globalsForEvent(e);this.Ap.push(n),this.Ap.length>1e3&&(this.Ap=this.Ap.slice(10))}get siteAppLoaders(){var t;return(t=qe._POSTHOG_REMOTE_CONFIG)===null||t===void 0||(t=t[this._instance.config.token])===null||t===void 0?void 0:t.siteApps}initialize(){if(this.isEnabled){const t=this._instance._addCaptureHook(this.Fp.bind(this));this.Op=()=>{t(),this.Ap=[],this.Op=void 0}}}globalsForEvent(t){var e,n,r,s,i,o,l;if(!t)throw new Error("Event payload is required");const u={},d=this._instance.get_property("$groups")||[],f=this._instance.get_property("$stored_group_properties")||{};for(const[v,w]of Object.entries(f))u[v]={id:d[v],type:v,properties:w};const{$set_once:h,$set:m}=t;return{event:$($({},nT(t,BV)),{},{properties:$($($({},t.properties),m?{$set:$($({},(e=(n=t.properties)===null||n===void 0?void 0:n.$set)!==null&&e!==void 0?e:{}),m)}:{}),h?{$set_once:$($({},(r=(s=t.properties)===null||s===void 0?void 0:s.$set_once)!==null&&r!==void 0?r:{}),h)}:{}),elements_chain:(i=(o=t.properties)===null||o===void 0?void 0:o.$elements_chain)!==null&&i!==void 0?i:"",distinct_id:(l=t.properties)===null||l===void 0?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:u}}Dp(t){var e;const n=(e=t.tagName)===null||e===void 0?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Mi.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Mi.error("prepare_external_dependency_script returned null"),null):t}Lp(){var t,e,n,r,s,i,o,l;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};const u=ke==null?void 0:ke.defaultView,d=u==null||(t=u.Node)===null||t===void 0?void 0:t.prototype;if(!u||!d)return()=>{};if(this.Rp++,this.Np)return this.qp();const f=[],h=this,m=new WeakSet,v=(x,b,k)=>{if(!(x!=null&&x[b]))return;const C=x[b];x[b]=k(C),f.push(()=>{x[b]=C})},w=x=>{if(m.has(x))return x;const b=h.Dp(x);return b&&m.add(b),b},_=x=>x.map(b=>typeof b=="string"?b:w(b)).filter(b=>!dn(b));return v(d,"appendChild",x=>function(b){const k=w(b);return k?x.call(this,k):b}),v(d,"insertBefore",x=>function(b,k){const C=w(b);return C?x.call(this,C,k):b}),v(d,"replaceChild",x=>function(b,k){const C=w(b);return C?x.call(this,C,k):k}),[(e=u.Element)===null||e===void 0?void 0:e.prototype,(n=u.Document)===null||n===void 0?void 0:n.prototype,(r=u.DocumentFragment)===null||r===void 0?void 0:r.prototype].forEach(x=>{v(x,"append",b=>function(...k){return b.apply(this,_(k))}),v(x,"prepend",b=>function(...k){return b.apply(this,_(k))})}),[(s=u.Element)===null||s===void 0?void 0:s.prototype,(i=u.CharacterData)===null||i===void 0?void 0:i.prototype,(o=u.DocumentType)===null||o===void 0?void 0:o.prototype].forEach(x=>{v(x,"before",b=>function(...k){return b.apply(this,_(k))}),v(x,"after",b=>function(...k){return b.apply(this,_(k))}),v(x,"replaceWith",b=>function(...k){const C=_(k);return k.length&&!C.length?void 0:b.apply(this,C)})}),v((l=u.Element)===null||l===void 0?void 0:l.prototype,"insertAdjacentElement",x=>function(b,k){const C=w(k);return C?x.call(this,b,C):null}),this.Np=()=>{f.forEach(x=>x()),this.Np=void 0},this.qp()}qp(){let t=!1;return()=>{var e;t||(t=!0,this.Rp--,this.Rp===0&&((e=this.Np)===null||e===void 0||e.call(this)))}}jp(t,e=!0){const n=this.Lp();try{const r=t(n);return e&&n(),r}catch(r){throw n(),r}}setupSiteApp(t){const e=this.apps[t.id],n=()=>{var i;!e.errored&&this.Ap.length&&(Mi.info(`Processing ${this.Ap.length} events for site app with id ${t.id}`),this.Ap.forEach(o=>this.jp(()=>{var l;return(l=e.processEvent)===null||l===void 0?void 0:l.call(e,o)})),e.processedBuffer=!0),Object.values(this.apps).every(o=>o.processedBuffer||o.errored)&&((i=this.Op)===null||i===void 0||i.call(this))};let r=!1;const s=i=>{e.errored=!i,e.loaded=!0,Mi.info(`Site app with id ${t.id} ${i?"loaded":"errored"}`),r&&n()};try{const{processEvent:i}=this.jp(o=>t.init({posthog:this._instance,callback(l){o(),s(l)}}),!1);i&&(e.processEvent=i),r=!0}catch(i){Mi.error(Z8+t.id,i),s(!1)}if(r&&e.loaded)try{n()}catch(i){Mi.error(`Error while processing buffered events PostHog app with config id ${t.id}`,i),e.errored=!0}}Bp(){const t=this.siteAppLoaders||[];for(const e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(const e of t)this.setupSiteApp(e)}zp(t){if(Object.keys(this.apps).length===0)return;const e=this.globalsForEvent(t);for(const n of Object.values(this.apps))try{this.jp(()=>{var r;return(r=n.processEvent)===null||r===void 0?void 0:r.call(n,e)})}catch(r){Mi.error(`Error while processing event ${t.event} for site app ${n.id}`,r)}}onRemoteConfig(t){var e,n,r;if(!((e=this.siteAppLoaders)===null||e===void 0)&&e.length)return this.isEnabled?(this.Bp(),void this._instance.on("eventCaptured",l=>this.zp(l))):void Mi.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.Op)===null||n===void 0||n.call(this),!t.ok)return;const s=t.config;if(!((r=s.siteApps)===null||r===void 0)&&r.length)if(this.isEnabled)for(const{id:l,url:u}of s.siteApps){var i,o;qe[`__$$ph_site_app_${l}`]=this._instance,(i=qe.__PosthogExtensions__)===null||i===void 0||(o=i.loadSiteApp)===null||o===void 0||o.call(i,this._instance,u,d=>{if(d)return Mi.error(Z8+l,d)})}else Mi.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},SH={tracingHeaders:class{constructor(t){this._instance=t,this.Hp=void 0,this.Up=void 0,this.Wp=void 0,this.op=()=>{const e=this.Vp();var n,r;e?(ae(this.Hp)&&(this.Hp=(n=qe.__PosthogExtensions__)===null||n===void 0||(n=n.tracingHeadersPatchFns)===null||n===void 0?void 0:n._patchXHR(e,()=>this._instance.get_distinct_id(),this._instance.sessionManager)),ae(this.Up)&&(this.Up=(r=qe.__PosthogExtensions__)===null||r===void 0||(r=r.tracingHeadersPatchFns)===null||r===void 0?void 0:r._patchFetch(e,()=>this._instance.get_distinct_id(),this._instance.sessionManager))):this.dp()}}initialize(){this.startIfEnabledOrStop()}Ml(t){var e,n,r;!((e=qe.__PosthogExtensions__)===null||e===void 0)&&e.tracingHeadersPatchFns?t():(n=qe.__PosthogExtensions__)===null||n===void 0||(r=n.loadExternalDependency)===null||r===void 0||r.call(n,this._instance,"tracing-headers",s=>{if(s)return FV.error("failed to load script",s);t()})}Gp(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Vp(){const t=this.Gp();return ze(t)?(ze(this.Wp)?this.Wp.splice(0,this.Wp.length,...t):this.Wp=[...t],t.length>0?this.Wp:void 0):(ze(this.Wp)&&this.Wp.splice(0),this.Wp=t||void 0,this.Wp)}dp(){var t,e;(t=this.Hp)===null||t===void 0||t.call(this),(e=this.Up)===null||e===void 0||e.call(this),this.Hp=void 0,this.Up=void 0}startIfEnabledOrStop(){this.Vp()?this.Ml(this.op):this.dp()}}},kH=$({surveys:class extends GV{constructor(t){super(new KV(t))}}},qg),EH={toolbar:class{constructor(t){this.instance=t}Qp(t){qe.ph_toolbar_state=t}Zp(){var t;return(t=qe.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t=void 0,e=void 0,n=void 0){var r,s;if(k2(this.instance.config)||!oe||!ke)return!1;t=(r=t)!==null&&r!==void 0?r:oe.location,n=(s=n)!==null&&s!==void 0?s:oe.history;try{if(!e){try{oe.localStorage.setItem("test","test"),oe.localStorage.removeItem("test")}catch{return!1}e=oe==null?void 0:oe.localStorage}const i=YV||qm(t.hash,"__posthog")||qm(t.hash,"state");let o;const l=i?Ok(()=>JSON.parse(atob(decodeURIComponent(i))))||Ok(()=>JSON.parse(decodeURIComponent(i))):null;return l&&l.action==="ph_authorize"?(o=l,o.source="url",o&&Object.keys(o).length>0&&(l.desiredHash?t.hash=l.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):(o=JSON.parse(e.getItem(G8)||"{}"),o.source="localstorage",delete o.userIntent),!(!o.token||this.instance.config.token!==o.token||(this.loadToolbar(o),0))}catch{return!1}}Jp(t){const e=qe.ph_load_toolbar||qe.ph_load_editor;!Xe(e)&&gn(e)?e(t,this.instance):K8.warn("No toolbar load function found")}loadToolbar(t){const e=!!(ke!=null&&ke.getElementById("__POSTHOG_TOOLBAR__"));if(!oe||e)return!1;const n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=$($({token:this.instance.config.token},t),{},{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(oe.localStorage.setItem(G8,JSON.stringify($($({},r),{},{source:void 0}))),this.Zp()===2)this.Jp(r);else if(this.Zp()===0){var s,i;this.Qp(1),(s=qe.__PosthogExtensions__)===null||s===void 0||(i=s.loadExternalDependency)===null||i===void 0||i.call(s,this.instance,"toolbar",o=>{if(o)return K8.error("[Toolbar] Failed to load",o),void this.Qp(0);this.Qp(2),this.Jp(r)}),_t(oe,"turbolinks:load",()=>{this.Qp(0),this.loadToolbar(r)})}return!0}Kp(t){return this.loadToolbar(t)}maybeLoadEditor(t=void 0,e=void 0,n=void 0){return this.maybeLoadToolbar(t,e,n)}}},CH=$({experiments:class jr{get Ar(){return this._instance.config}constructor(e){this._instance=e,this.getWebExperimentsAndEvaluateDisplayLogic=(n=!1)=>{this.getWebExperiments(r=>{jr.Xp("retrieved web experiments from the server"),this.Yp=new Map,r.forEach(s=>{if(s.feature_flag_key){var i;this.Yp&&(jr.Xp("setting flag key ",s.feature_flag_key," to web experiment ",s),(i=this.Yp)===null||i===void 0||i.set(s.feature_flag_key,s));const o=this._instance.getFeatureFlag(s.feature_flag_key);rt(o)&&s.variants[o]&&this.tg(s.name,o,s.variants[o].transforms)}else if(s.variants)for(const o in s.variants){const l=s.variants[o];jr.eg(l,this._instance)&&this.tg(s.name,o,l.transforms)}})},n)},this._instance.onFeatureFlags(n=>{this.onFeatureFlags(n)})}initialize(){}onFeatureFlags(e){if(this._is_bot())jr.Xp(rE);else if(!this.Ar.disable_web_experiments){if(Xe(this.Yp))return this.Yp=new Map,this.loadIfEnabled(),void this.previewWebExperiment();jr.Xp("applying feature flags",e),e.forEach(n=>{var r;if(this.Yp&&(!((r=this.Yp)===null||r===void 0)&&r.has(n))){var s;const i=this._instance.getFeatureFlag(n),o=(s=this.Yp)===null||s===void 0?void 0:s.get(n);i&&(o!=null&&o.variants[i])&&this.tg(o.name,i,o.variants[i].transforms)}})}}previewWebExperiment(){const e=jr.getWindowLocation();if(e!=null&&e.search){const n=od(e==null?void 0:e.search,"__experiment_id"),r=od(e==null?void 0:e.search,"__experiment_variant");n&&r&&(jr.Xp(`previewing web experiments ${n} && ${r}`),this.getWebExperiments(s=>{this.ig(parseInt(n),r,s)},!1,!0))}}loadIfEnabled(){this.Ar.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,r){if(this.Ar.disable_web_experiments&&!r)return e([]);const s=this._instance.get_property("$web_experiments");if(s&&!n)return e(s);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/web_experiments/?token=${this.Ar.token}`),method:"GET",timestampMode:"query",callback:i=>e(i.statusCode===200&&i.json&&i.json.experiments||[])})}ig(e,n,r){const s=r.filter(i=>i.id===e);s&&s.length>0&&(jr.Xp(`Previewing web experiment [${s[0].name}] with variant [${n}]`),this.tg(s[0].name,n,s[0].variants[n].transforms))}static eg(e,n){return!Xe(e.conditions)&&jr.ng(e,n)&&jr.sg(e)}static ng(e,n){var r;if(Xe(e.conditions)||Xe((r=e.conditions)===null||r===void 0?void 0:r.url))return!0;const s=jr.getWindowLocation();if(s){var i,o,l;const u=VT(n,s.href);return!(!((i=e.conditions)===null||i===void 0)&&i.url)||rH[(o=(l=e.conditions)===null||l===void 0?void 0:l.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,u)}return!1}static getWindowLocation(){return oe==null?void 0:oe.location}static sg(e){var n;if(Xe(e.conditions)||Xe((n=e.conditions)===null||n===void 0?void 0:n.utm))return!0;const r=eR();if(r.utm_source){var s,i,o,l,u,d,f,h;const m=!(!((s=e.conditions)===null||s===void 0||(s=s.utm)===null||s===void 0)&&s.utm_campaign)||((i=e.conditions)===null||i===void 0||(i=i.utm)===null||i===void 0?void 0:i.utm_campaign)==r.utm_campaign,v=!(!((o=e.conditions)===null||o===void 0||(o=o.utm)===null||o===void 0)&&o.utm_source)||((l=e.conditions)===null||l===void 0||(l=l.utm)===null||l===void 0?void 0:l.utm_source)==r.utm_source,w=!(!((u=e.conditions)===null||u===void 0||(u=u.utm)===null||u===void 0)&&u.utm_medium)||((d=e.conditions)===null||d===void 0||(d=d.utm)===null||d===void 0?void 0:d.utm_medium)==r.utm_medium,_=!(!((f=e.conditions)===null||f===void 0||(f=f.utm)===null||f===void 0)&&f.utm_term)||((h=e.conditions)===null||h===void 0||(h=h.utm)===null||h===void 0?void 0:h.utm_term)==r.utm_term;return m&&w&&_&&v}return!1}static Xp(e,...n){he.info(`[WebExperiments] ${e}`,n)}tg(e,n,r){this._is_bot()?jr.Xp(rE):n!=="control"?r.forEach(s=>{if(s.selector){var i;jr.Xp(`applying transform of variant ${n} for experiment ${e} `,s);const o=(i=document)===null||i===void 0?void 0:i.querySelectorAll(s.selector);o==null||o.forEach(l=>{const u=l;s.html&&(u.innerHTML=s.html),s.css&&u.setAttribute("style",s.css)})}}):jr.Xp("Control variants leave the page unmodified.")}_is_bot(){return gr&&this._instance?ER(gr,this.Ar.custom_blocked_useragents):void 0}}},qg),PH={conversations:class{constructor(t){this._instance=t,this.rg=void 0,this._conversationsManager=null,this.og=!1,this.ne=null,this.ag=!1,this.lg=0,this.ug=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(this._instance.config.disable_conversations)return void(this.ug=null);if(this.cg=t.ok,!t.ok)return;const e=t.config.conversations;Xe(e)?this.ug=null:(Hr(e)?this.rg=e:(this.rg=e.enabled,this.ne=e),this.rg||(this.ug=null),this.loadIfEnabled())}reset(){var t;(t=this._conversationsManager)===null||t===void 0||t.reset(),this._conversationsManager=null,this.lg++,this.rg=void 0,this.ne=null,this.cg=void 0,this.ag=!1,this.ug=null}loadIfEnabled(){if(this._conversationsManager||this.og||this._instance.config.disable_conversations||k2(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())return;const t=qe==null?void 0:qe.__PosthogExtensions__;if(t&&!ae(this.rg)&&this.rg)if(this.ne&&this.ne.token){this.og=!0;try{const e=t.initConversations;if(e)return this.hg(e),void(this.og=!1);const n=t.loadExternalDependency;if(!n)return void this.dg(Hx);const r=this.lg;n(this._instance,"conversations",s=>{if(r!==this.lg)return this.og=!1,void this.loadIfEnabled();s||!t.initConversations?this.dg("Could not load conversations script",s):this.hg(t.initConversations),this.og=!1})}catch(e){this.dg("Error initializing conversations",e),this.og=!1}}else Zs.error("Conversations enabled but missing token in remote config.")}hg(t){if(this.ne){try{this._conversationsManager=t(this.ne,this._instance),this.ag=!1,Zs.info("Conversations loaded successfully")}catch(e){return void this.dg("Error completing conversations initialization",e)}this.vg()}else Zs.error("Cannot complete initialization: remote config is null")}vg(){const t=this.ug;this.ug=null,this._conversationsManager&&t&&(t==="open"?this._conversationsManager.open():this._conversationsManager.close())}dg(t,e){Zs.error(t,e),this._conversationsManager=null,this.og=!1,this.ag=!0}show(){this._conversationsManager?this._conversationsManager.show():Zs.warn("Conversations not loaded yet.")}hide(){this.ug==="open"&&(this.ug=null),this._conversationsManager&&this._conversationsManager.hide()}open(){this._conversationsManager?(this.ug=null,this._conversationsManager.open()):this.ug="open"}close(){this._conversationsManager?(this.ug=null,this._conversationsManager.close()):this.ug="close"}isAvailable(){return this.rg===!0&&!dn(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":k2(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.cg===!1?"remote_config_failed":ae(this.rg)?this.cg?"disabled_in_project":"remote_config_pending":this.rg?Xe(this.ne)||!this.ne.token?"missing_token":qe!=null&&qe.__PosthogExtensions__?this.og?"initializing":this.ag?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)===null||e===void 0?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var r=this;return Wt(function*(){return r._conversationsManager?r._conversationsManager.sendMessage(t,e,n):(Zs.warn(Ll),null)})()}getMessages(t,e){var n=this;return Wt(function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(Zs.warn(Ll),null)})()}markAsRead(t){var e=this;return Wt(function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Zs.warn(Ll),null)})()}getTickets(t){var e=this;return Wt(function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Zs.warn(Ll),null)})()}requestRestoreLink(t){var e=this;return Wt(function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Zs.warn(Ll),null)})()}restoreFromToken(t){var e=this;return Wt(function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Zs.warn(Ll),null)})()}restoreFromUrlToken(){var t=this;return Wt(function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Zs.warn(Ll),null)})()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)===null||e===void 0?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)===null||e===void 0?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}fd(){var t;(t=this._conversationsManager)===null||t===void 0||t.setIdentity()}pd(){var t;(t=this._conversationsManager)===null||t===void 0||t.clearIdentity()}}},AH={logs:class extends oH{constructor(t){super({get(){var e;return t==null||(e=t.config)===null||e===void 0?void 0:e.logs},captureHintKey:wT,get remoteConfigWillArrive(){var e,n;return!(!((e=t.Qu)===null||e===void 0)&&e.call(t))||!!(!((n=qe._POSTHOG_REMOTE_CONFIG)===null||n===void 0||(n=n[t.config.token])===null||n===void 0)&&n.config)}},()=>(function(e){var n;const r={};if(r.distinctId=e.get_distinct_id(),e.sessionManager){const{sessionId:s,windowId:i,sessionStartTimestamp:o,lastActivityTimestamp:l}=e.sessionManager.checkAndGetSessionAndWindowId(!0);r.sessionId=s,r.windowId=i,Xe(o)||(r.sessionStartTimestamp=o),Xe(l)||(r.lastActivityTimestamp=l)}if(!(qe==null||(n=qe.location)===null||n===void 0)&&n.href&&(r.currentUrl=e.config.disable_capture_url_hashes?Ya(qe.location.href):qe.location.href),e.featureFlags){const s=e.featureFlags.getFlags();s&&s.length>0&&(r.activeFeatureFlags=s)}return r})(t)),this._instance=t,this.name=LR,this.Uv()}get zv(){return this._instance.__loaded}Hv(){const t=an("[logs]"),e=qe==null?void 0:qe.__PosthogExtensions__;if(!e)return void t.error("PostHog Extensions not found.");const n=e.loadExternalDependency;if(n)return r=>{n(this._instance,"logs",s=>{const i=e.logs;r(s,i!=null&&i.initializeLogs?{initialize:o=>i.initializeLogs(o),replay(o,l){var u;return(u=i.replayConsoleBuffer)===null||u===void 0?void 0:u.call(i,o,l)}}:void 0)})};t.error(Hx)}}},TH={metrics:class{constructor(t){this._instance=t,this.$=an("[metrics]"),this.Ci=!1}initialize(){this.onConfigChange()}onConfigChange(){var t;if(this.Ci)return;const e=!!(!((t=this._instance.config.metrics)===null||t===void 0)&&t.network);e&&!this.fg?this.fg=(n=>{let r=!0;const s=()=>r?(l=>{var u;const d=(u=l.config.metrics)===null||u===void 0?void 0:u.network;return d===!0?{}:d||void 0})(n):void 0,i=cH(n,s),o=uH(n,s);return()=>{r=!1,i(),o()}})(this._instance):!e&&this.fg&&(this.fg(),this.fg=void 0)}Gv(){var t;const e=(t=this._instance)===null||t===void 0||(t=t.config)===null||t===void 0?void 0:t.metrics;var n;return this.jv&&this.Qv===e||((n=this.jv)===null||n===void 0||n.reset(),this.Qv=e,this.jv=new J$(this.Vv(),(function(r){var s,i,o,l,u;const d=r==null?void 0:r.resourceAttributes;return{serviceName:(s=d==null?void 0:d["service.name"])!==null&&s!==void 0?s:r==null?void 0:r.serviceName,serviceVersion:(i=d==null?void 0:d["service.version"])!==null&&i!==void 0?i:r==null?void 0:r.serviceVersion,environment:(o=d==null?void 0:d["deployment.environment"])!==null&&o!==void 0?o:r==null?void 0:r.environment,resourceAttributes:d,beforeSend:r==null?void 0:r.beforeSend,flushIntervalMs:(l=r==null?void 0:r.flushIntervalMs)!==null&&l!==void 0?l:1e4,maxSeriesPerFlush:(u=r==null?void 0:r.maxSeriesPerFlush)!==null&&u!==void 0?u:1e3}})(e),this.$)),this.jv}count(t,e=1,n){this.Gv().count(t,e,n)}gauge(t,e,n){this.Gv().gauge(t,e,n)}histogram(t,e,n){this.Gv().histogram(t,e,n)}flush(t){if(!this.jv)return Promise.resolve();if(t){const e=this.jv.drainWindow();return e&&this.po(e,t),Promise.resolve()}return this.jv.flush().catch(e=>this.$.error("PostHog metrics flush failed:",e))}reset(){var t;(t=this.jv)===null||t===void 0||t.reset()}dispose(){var t,e;this.Ci=!0,(t=this.fg)===null||t===void 0||t.call(this),this.fg=void 0,(e=this.jv)===null||e===void 0||e.reset()}Vv(){const t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},po:n=>e.po(n),getLibraryId:()=>Jr.LIB_NAME,getLibraryVersion:()=>Jr.LIB_VERSION}}po(t,e){return new Promise(n=>{let r=!1;const s=o=>{r||(r=!0,clearTimeout(i),n(o))},i=setTimeout(()=>s({kind:"retry-later",error:new Error("metrics request timed out")}),9e4);this._instance._send_request($($({method:"POST",url:this.pg(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e}),{},{fireCallbackOnDrop:!0,callback(o){const l=o.statusCode;if(l>=200&&300>l)s({kind:"ok"});else if(l===413)s({kind:"too-large"});else if(l!==0&&l!==408&&l!==429&&500>l)s({kind:"fatal",error:new Error(`metrics request failed with status ${l}`)});else{var u;s({kind:"retry-later",error:(u=o.error)!==null&&u!==void 0?u:new Error(`metrics request failed with status ${l}`)})}}}))})}pg(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},RH={webMCP:class{constructor(t){this._instance=t,this.gg=!1}initialize(){this.startIfEnabled()}startIfEnabled(){if(!this._instance.config.capture_webmcp||this.gg)return;const t=ke==null?void 0:ke.modelContext;if(!t||!gn(t.registerTool))return;const e=aE.get(t);if(e)return e.instances.add(this._instance),void(this.gg=!0);const n={instances:new Set([this._instance])},r=t.registerTool,s=this;cd(t,"registerTool",i=>{const o=i;return function(l,...u){let d=l;try{d=s.mg(l,n)}catch{return o.call(this,l,...u)}return o.call(this,d,...u)}}),t.registerTool!==r&&(aE.set(t,n),this.gg=!0)}mg(t,e){if(!t||!gn(t.execute))return t;const n=t.execute,r=this,{tool:s,injected:i}=(function(o,l){const u={intent:!1,model:!1},d=o.inputSchema;if(!(function(w){return!!ae(w)||nt(w)&&Object.keys(w).every(_=>dH.has(_)||_.startsWith("x-"))&&w.additionalProperties!==!0&&!nt(w.additionalProperties)&&(!w.type||w.type==="object")&&(!w.properties||nt(w.properties))&&(!w.required||ze(w.required))})(d))return{tool:Ky(o),injected:u};const f=(d==null?void 0:d.properties)||{},h=w=>Gy(f,w)||ze(d==null?void 0:d.required)&&d.required.includes(w);if(u.intent=l.intent&&!h("context"),u.model=l.model&&!h("llm_model"),!u.intent&&!u.model)return{tool:Ky(o),injected:u};const m=$({},f),v=ze(d==null?void 0:d.required)?[...d.required]:[];return u.intent&&(m.context={type:"string",description:`Explain why this tool is called and how it supports the user's goal. Describe the abstract purpose only. Do not include personal or identifying information. Generalize specific entities as roles such as "a customer".`},v.includes("context")||v.push("context")),u.model&&(m.llm_model={type:"string",description:'The exact model identifier you are running as, taken from your system prompt or environment. Pass "unknown" if you do not know it. Never guess.'},v.includes("llm_model")||v.push("llm_model")),{tool:Ky(o,$($({},d),{},{type:(d==null?void 0:d.type)||"object",properties:m,required:v})),injected:u}})(t,(function(o){const l={intent:!1,model:!1};for(const u of o.instances){const d=lE(u.config.capture_webmcp);l.intent||(l.intent=(d==null?void 0:d.intent)===!0),l.model||(l.model=(d==null?void 0:d.model)===!0)}return l})(e));return Object.defineProperty(s,"execute",{configurable:!0,enumerable:!0,writable:!0,value(...o){const l=new Date,u=(function(v,w){if(!nt(v))return{};try{const _=w.intent?cE(v.context,2048,!0):void 0,x=w.model?cE(v.llm_model,256):void 0;return $($({},_&&_!=="{}"?{intent:_}:{}),x&&x.toLowerCase()!=="unknown"?{model:x}:{})}catch{return{}}})(o[0],i),d=(function(v,w){const _=v[0];if(!nt(_))return v;try{const x=w.intent&&Gy(_,"context"),b=w.model&&Gy(_,"llm_model");if(!x&&!b)return v;const k=$({},_);return x&&delete k.context,b&&delete k.llm_model,[k,...v.slice(1)]}catch{return v}})(o,i);let f;try{f=n.apply(this===s?t:this,d)}catch(v){throw r.yg(e,s,l,{error:v,errorResult:!1},u),v}if((h=f)&&typeof h.then=="function")return Promise.resolve(f).then(v=>{const w=uE(v)?{error:v,errorResult:!0}:void 0;return r.yg(e,s,l,w,u),v},v=>{throw r.yg(e,s,l,{error:v,errorResult:!1},u),v});var h;const m=uE(f)?{error:f,errorResult:!0}:void 0;return r.yg(e,s,l,m,u),f}}),s}yg(t,e,n,r,s){const i=Date.now()-n.getTime();let o;for(const u of t.instances){var l;const d=lE(u.config.capture_webmcp);if(d){r&&!o&&(o=vH(r.error,r.errorResult));try{u.capture("$mcp_tool_call",$($($({$mcp_source:"posthog_mcp_analytics",$mcp_interface:"webmcp",$mcp_tool_name:e.name,$mcp_resource_name:e.name,$mcp_tool_description:e.description,$mcp_server_name:Ut==null?void 0:Ut.hostname,$mcp_duration_ms:i,$mcp_is_error:!!r},o?{$mcp_error_type:o.type,$mcp_error_message:o.message}:{}),d.intent&&s.intent?{$mcp_intent:s.intent,$mcp_intent_source:"context_parameter"}:{}),d.model&&s.model?{$mcp_llm_model:s.model,$mcp_llm_model_source:"self_reported"}:{}),{timestamp:n})}catch{continue}if(r&&o&&u.exceptions&&(!((l=u.exceptionObserver)===null||l===void 0)&&l.isEnabled))try{const f={$exception_list:mH(u.exceptions,r,o.message),$exception_level:"error",$exception_source:"mcp.tool_call",$mcp_interface:"webmcp",$mcp_tool_name:e.name,$mcp_resource_name:e.name,$mcp_tool_description:e.description,$mcp_server_name:Ut==null?void 0:Ut.hostname};u.exceptionObserver.captureException(f)}catch{}}}}}};th.__defaultExtensionClasses=$({},$($($($($($($($($($($($($($({},qg),yH),_H),wH),xH),bH),kH),SH),EH),CH),PH),AH),TH),RH));const IH=(function(){Jr.SDK_DIST_CHANNEL="npm";const t=Jf[jf]=new th;return(function(){function e(){e.done||(e.done=!0,SR=!1,Pt(Jf,function(n){n._dom_loaded()}))}ke!=null&&ke.addEventListener?ke.readyState==="complete"?e():_t(ke,"DOMContentLoaded",e,{capture:!1}):oe&&he.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();var $e=IH,Mt;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{const i={};for(const o of s)i[o]=o;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(const l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},t.find=(s,i)=>{for(const o of s)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Mt||(Mt={}));var dE;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(dE||(dE={}));const Ne=Mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Aa=t=>{switch(typeof t){case"undefined":return Ne.undefined;case"string":return Ne.string;case"number":return Number.isNaN(t)?Ne.nan:Ne.number;case"boolean":return Ne.boolean;case"function":return Ne.function;case"bigint":return Ne.bigint;case"symbol":return Ne.symbol;case"object":return Array.isArray(t)?Ne.array:t===null?Ne.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Ne.promise:typeof Map<"u"&&t instanceof Map?Ne.map:typeof Set<"u"&&t instanceof Set?Ne.set:typeof Date<"u"&&t instanceof Date?Ne.date:Ne.object;default:return Ne.unknown}},we=Mt.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Go extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let l=r,u=0;for(;u<o.path.length;){const d=o.path[u];u===o.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(n(o))):l[d]=l[d]||{_errors:[]},l=l[d],u++}}};return s(this),r}static assert(e){if(!(e instanceof Go))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Mt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},r=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Go.create=t=>new Go(t);const j2=(t,e)=>{let n;switch(t.code){case we.invalid_type:t.received===Ne.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case we.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Mt.jsonStringifyReplacer)}`;break;case we.unrecognized_keys:n=`Unrecognized key(s) in object: ${Mt.joinValues(t.keys,", ")}`;break;case we.invalid_union:n="Invalid input";break;case we.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Mt.joinValues(t.options)}`;break;case we.invalid_enum_value:n=`Invalid enum value. Expected ${Mt.joinValues(t.options)}, received '${t.received}'`;break;case we.invalid_arguments:n="Invalid function arguments";break;case we.invalid_return_type:n="Invalid function return type";break;case we.invalid_date:n="Invalid date";break;case we.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Mt.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case we.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case we.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case we.custom:n="Invalid input";break;case we.invalid_intersection_types:n="Intersection results could not be merged";break;case we.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case we.not_finite:n="Number must be finite";break;default:n=e.defaultError,Mt.assertNever(t)}return{message:n}};let MH=j2;function OH(){return MH}const LH=t=>{const{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}};function Pe(t,e){const n=OH(),r=LH({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===j2?void 0:j2].filter(s=>!!s)});t.common.issues.push(r)}class Br{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const s of n){if(s.status==="aborted")return ot;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const s of n){const i=await s.key,o=await s.value;r.push({key:i,value:o})}return Br.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const s of n){const{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return ot;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}}const ot=Object.freeze({status:"aborted"}),$f=t=>({status:"dirty",value:t}),ri=t=>({status:"valid",value:t}),fE=t=>t.status==="aborted",hE=t=>t.status==="dirty",ud=t=>t.status==="valid",Jm=t=>typeof Promise<"u"&&t instanceof Promise;var Ze;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(Ze||(Ze={}));class Ji{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const pE=(t,e)=>{if(ud(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Go(t.common.issues);return this._error=n,this._error}}};function ht(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{const{message:u}=t;return o.code==="invalid_enum_value"?{message:u??l.defaultError}:typeof l.data>"u"?{message:u??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:u??n??l.defaultError}},description:s}}class St{get description(){return this._def.description}_getType(e){return Aa(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Aa(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Br,ctx:{common:e.parent.common,data:e.data,parsedType:Aa(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(Jm(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){const r={common:{issues:[],async:(n==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Aa(e)},s=this._parseSync({data:e,path:r.path,parent:r});return pE(r,s)}"~validate"(e){var r,s;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Aa(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:n});return ud(i)?{value:i.value}:{issues:n.common.issues}}catch(i){(s=(r=i==null?void 0:i.message)==null?void 0:r.toLowerCase())!=null&&s.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(i=>ud(i)?{value:i.value}:{issues:n.common.issues})}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Aa(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Jm(s)?s:Promise.resolve(s));return pE(r,i)}refine(e,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const o=e(s),l=()=>i.addIssue({code:we.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Sc({schema:this,typeName:lt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Uo.create(this,this._def)}nullable(){return kc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ki.create(this)}promise(){return ig.create(this,this._def)}or(e){return tg.create([this,e],this._def)}and(e){return ng.create(this,e,this._def)}transform(e){return new Sc({...ht(this._def),schema:this,typeName:lt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new og({...ht(this._def),innerType:this,defaultValue:n,typeName:lt.ZodDefault})}brand(){return new UR({typeName:lt.ZodBranded,type:this,...ht(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new ag({...ht(this._def),innerType:this,catchValue:n,typeName:lt.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ib.create(this,e)}readonly(){return lg.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const NH=/^c[^\s-]{8,}$/i,DH=/^[0-9a-z]+$/,jH=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$H=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,FH=/^[a-z0-9_-]{21}$/i,VH=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,HH=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,zH=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,UH="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Yy;const BH=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,WH=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ZH=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,qH=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,GH=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,KH=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,VR="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",YH=new RegExp(`^${VR}$`);function HR(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function XH(t){return new RegExp(`^${HR(t)}$`)}function QH(t){let e=`${VR}T${HR(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function JH(t,e){return!!((e==="v4"||!e)&&BH.test(t)||(e==="v6"||!e)&&ZH.test(t))}function ez(t,e){if(!VH.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&(s==null?void 0:s.typ)!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function tz(t,e){return!!((e==="v4"||!e)&&WH.test(t)||(e==="v6"||!e)&&qH.test(t))}class zo extends St{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Ne.string){const i=this._getOrReturnCtx(e);return Pe(i,{code:we.invalid_type,expected:Ne.string,received:i.parsedType}),ot}const r=new Br;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?Pe(s,{code:we.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&Pe(s,{code:we.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")zH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"email",code:we.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Yy||(Yy=new RegExp(UH,"u")),Yy.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"emoji",code:we.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")$H.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"uuid",code:we.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")FH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"nanoid",code:we.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")NH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"cuid",code:we.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")DH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"cuid2",code:we.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")jH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"ulid",code:we.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),Pe(s,{validation:"url",code:we.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"regex",code:we.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?QH(i).test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?YH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?XH(i).test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?HH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"duration",code:we.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?JH(e.data,i.version)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"ip",code:we.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?ez(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"jwt",code:we.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?tz(e.data,i.version)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"cidr",code:we.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?GH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"base64",code:we.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?KH.test(e.data)||(s=this._getOrReturnCtx(e,s),Pe(s,{validation:"base64url",code:we.invalid_string,message:i.message}),r.dirty()):Mt.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:we.invalid_string,...Ze.errToObj(r)})}_addCheck(e){return new zo({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Ze.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Ze.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Ze.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Ze.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Ze.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Ze.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Ze.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Ze.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Ze.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Ze.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Ze.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Ze.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Ze.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...Ze.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...Ze.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...Ze.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...Ze.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n==null?void 0:n.position,...Ze.errToObj(n==null?void 0:n.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...Ze.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...Ze.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...Ze.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...Ze.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...Ze.errToObj(n)})}nonempty(e){return this.min(1,Ze.errToObj(e))}trim(){return new zo({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new zo({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new zo({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}zo.create=t=>new zo({checks:[],typeName:lt.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...ht(t)});function nz(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}class dd extends St{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Ne.number){const i=this._getOrReturnCtx(e);return Pe(i,{code:we.invalid_type,expected:Ne.number,received:i.parsedType}),ot}let r;const s=new Br;for(const i of this._def.checks)i.kind==="int"?Mt.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?nz(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.not_finite,message:i.message}),s.dirty()):Mt.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Ze.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Ze.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Ze.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Ze.toString(n))}setLimit(e,n,r,s){return new dd({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Ze.toString(s)}]})}_addCheck(e){return new dd({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Ze.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ze.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ze.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ze.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ze.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Ze.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:Ze.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ze.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ze.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Mt.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}}dd.create=t=>new dd({checks:[],typeName:lt.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...ht(t)});class _h extends St{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Ne.bigint)return this._getInvalidInput(e);let r;const s=new Br;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),Pe(r,{code:we.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):Mt.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return Pe(n,{code:we.invalid_type,expected:Ne.bigint,received:n.parsedType}),ot}gte(e,n){return this.setLimit("min",e,!0,Ze.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Ze.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Ze.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Ze.toString(n))}setLimit(e,n,r,s){return new _h({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Ze.toString(s)}]})}_addCheck(e){return new _h({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ze.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ze.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ze.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ze.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Ze.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}_h.create=t=>new _h({checks:[],typeName:lt.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...ht(t)});class $2 extends St{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Ne.boolean){const r=this._getOrReturnCtx(e);return Pe(r,{code:we.invalid_type,expected:Ne.boolean,received:r.parsedType}),ot}return ri(e.data)}}$2.create=t=>new $2({typeName:lt.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...ht(t)});class eg extends St{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Ne.date){const i=this._getOrReturnCtx(e);return Pe(i,{code:we.invalid_type,expected:Ne.date,received:i.parsedType}),ot}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return Pe(i,{code:we.invalid_date}),ot}const r=new Br;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),Pe(s,{code:we.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):Mt.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new eg({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:Ze.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:Ze.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}eg.create=t=>new eg({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:lt.ZodDate,...ht(t)});class mE extends St{_parse(e){if(this._getType(e)!==Ne.symbol){const r=this._getOrReturnCtx(e);return Pe(r,{code:we.invalid_type,expected:Ne.symbol,received:r.parsedType}),ot}return ri(e.data)}}mE.create=t=>new mE({typeName:lt.ZodSymbol,...ht(t)});class F2 extends St{_parse(e){if(this._getType(e)!==Ne.undefined){const r=this._getOrReturnCtx(e);return Pe(r,{code:we.invalid_type,expected:Ne.undefined,received:r.parsedType}),ot}return ri(e.data)}}F2.create=t=>new F2({typeName:lt.ZodUndefined,...ht(t)});class V2 extends St{_parse(e){if(this._getType(e)!==Ne.null){const r=this._getOrReturnCtx(e);return Pe(r,{code:we.invalid_type,expected:Ne.null,received:r.parsedType}),ot}return ri(e.data)}}V2.create=t=>new V2({typeName:lt.ZodNull,...ht(t)});class gE extends St{constructor(){super(...arguments),this._any=!0}_parse(e){return ri(e.data)}}gE.create=t=>new gE({typeName:lt.ZodAny,...ht(t)});class H2 extends St{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ri(e.data)}}H2.create=t=>new H2({typeName:lt.ZodUnknown,...ht(t)});class Xa extends St{_parse(e){const n=this._getOrReturnCtx(e);return Pe(n,{code:we.invalid_type,expected:Ne.never,received:n.parsedType}),ot}}Xa.create=t=>new Xa({typeName:lt.ZodNever,...ht(t)});class vE extends St{_parse(e){if(this._getType(e)!==Ne.undefined){const r=this._getOrReturnCtx(e);return Pe(r,{code:we.invalid_type,expected:Ne.void,received:r.parsedType}),ot}return ri(e.data)}}vE.create=t=>new vE({typeName:lt.ZodVoid,...ht(t)});class Ki extends St{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==Ne.array)return Pe(n,{code:we.invalid_type,expected:Ne.array,received:n.parsedType}),ot;if(s.exactLength!==null){const o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&(Pe(n,{code:o?we.too_big:we.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(Pe(n,{code:we.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(Pe(n,{code:we.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>s.type._parseAsync(new Ji(n,o,n.path,l)))).then(o=>Br.mergeArray(r,o));const i=[...n.data].map((o,l)=>s.type._parseSync(new Ji(n,o,n.path,l)));return Br.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new Ki({...this._def,minLength:{value:e,message:Ze.toString(n)}})}max(e,n){return new Ki({...this._def,maxLength:{value:e,message:Ze.toString(n)}})}length(e,n){return new Ki({...this._def,exactLength:{value:e,message:Ze.toString(n)}})}nonempty(e){return this.min(1,e)}}Ki.create=(t,e)=>new Ki({type:t,minLength:null,maxLength:null,exactLength:null,typeName:lt.ZodArray,...ht(e)});function Su(t){if(t instanceof Hn){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=Uo.create(Su(r))}return new Hn({...t._def,shape:()=>e})}else return t instanceof Ki?new Ki({...t._def,type:Su(t.element)}):t instanceof Uo?Uo.create(Su(t.unwrap())):t instanceof kc?kc.create(Su(t.unwrap())):t instanceof xc?xc.create(t.items.map(e=>Su(e))):t}class Hn extends St{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=Mt.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==Ne.object){const d=this._getOrReturnCtx(e);return Pe(d,{code:we.invalid_type,expected:Ne.object,received:d.parsedType}),ot}const{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof Xa&&this._def.unknownKeys==="strip"))for(const d in s.data)o.includes(d)||l.push(d);const u=[];for(const d of o){const f=i[d],h=s.data[d];u.push({key:{status:"valid",value:d},value:f._parse(new Ji(s,h,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof Xa){const d=this._def.unknownKeys;if(d==="passthrough")for(const f of l)u.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(d==="strict")l.length>0&&(Pe(s,{code:we.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const f of l){const h=s.data[f];u.push({key:{status:"valid",value:f},value:d._parse(new Ji(s,h,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const f of u){const h=await f.key,m=await f.value;d.push({key:h,value:m,alwaysSet:f.alwaysSet})}return d}).then(d=>Br.mergeObjectSync(r,d)):Br.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return Ze.errToObj,new Hn({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{var i,o;const s=((o=(i=this._def).errorMap)==null?void 0:o.call(i,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:Ze.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new Hn({...this._def,unknownKeys:"strip"})}passthrough(){return new Hn({...this._def,unknownKeys:"passthrough"})}extend(e){return new Hn({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Hn({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:lt.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new Hn({...this._def,catchall:e})}pick(e){const n={};for(const r of Mt.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new Hn({...this._def,shape:()=>n})}omit(e){const n={};for(const r of Mt.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new Hn({...this._def,shape:()=>n})}deepPartial(){return Su(this)}partial(e){const n={};for(const r of Mt.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new Hn({...this._def,shape:()=>n})}required(e){const n={};for(const r of Mt.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Uo;)i=i._def.innerType;n[r]=i}return new Hn({...this._def,shape:()=>n})}keyof(){return zR(Mt.objectKeys(this.shape))}}Hn.create=(t,e)=>new Hn({shape:()=>t,unknownKeys:"strip",catchall:Xa.create(),typeName:lt.ZodObject,...ht(e)});Hn.strictCreate=(t,e)=>new Hn({shape:()=>t,unknownKeys:"strict",catchall:Xa.create(),typeName:lt.ZodObject,...ht(e)});Hn.lazycreate=(t,e)=>new Hn({shape:t,unknownKeys:"strip",catchall:Xa.create(),typeName:lt.ZodObject,...ht(e)});class tg extends St{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const o=i.map(l=>new Go(l.ctx.common.issues));return Pe(n,{code:we.invalid_union,unionErrors:o}),ot}if(n.common.async)return Promise.all(r.map(async i=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i;const o=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},f=u._parseSync({data:n.data,path:n.path,parent:d});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=o.map(u=>new Go(u));return Pe(n,{code:we.invalid_union,unionErrors:l}),ot}}get options(){return this._def.options}}tg.create=(t,e)=>new tg({options:t,typeName:lt.ZodUnion,...ht(e)});const Ro=t=>t instanceof U2?Ro(t.schema):t instanceof Sc?Ro(t.innerType()):t instanceof sg?[t.value]:t instanceof bc?t.options:t instanceof B2?Mt.objectValues(t.enum):t instanceof og?Ro(t._def.innerType):t instanceof F2?[void 0]:t instanceof V2?[null]:t instanceof Uo?[void 0,...Ro(t.unwrap())]:t instanceof kc?[null,...Ro(t.unwrap())]:t instanceof UR||t instanceof lg?Ro(t.unwrap()):t instanceof ag?Ro(t._def.innerType):[];class sb extends St{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ne.object)return Pe(n,{code:we.invalid_type,expected:Ne.object,received:n.parsedType}),ot;const r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Pe(n,{code:we.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),ot)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){const s=new Map;for(const i of n){const o=Ro(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new sb({typeName:lt.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ht(r)})}}function z2(t,e){const n=Aa(t),r=Aa(e);if(t===e)return{valid:!0,data:t};if(n===Ne.object&&r===Ne.object){const s=Mt.objectKeys(e),i=Mt.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(const l of i){const u=z2(t[l],e[l]);if(!u.valid)return{valid:!1};o[l]=u.data}return{valid:!0,data:o}}else if(n===Ne.array&&r===Ne.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<t.length;i++){const o=t[i],l=e[i],u=z2(o,l);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return n===Ne.date&&r===Ne.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class ng extends St{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(fE(i)||fE(o))return ot;const l=z2(i.value,o.value);return l.valid?((hE(i)||hE(o))&&n.dirty(),{status:n.value,value:l.data}):(Pe(r,{code:we.invalid_intersection_types}),ot)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ng.create=(t,e,n)=>new ng({left:t,right:e,typeName:lt.ZodIntersection,...ht(n)});class xc extends St{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ne.array)return Pe(r,{code:we.invalid_type,expected:Ne.array,received:r.parsedType}),ot;if(r.data.length<this._def.items.length)return Pe(r,{code:we.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ot;!this._def.rest&&r.data.length>this._def.items.length&&(Pe(r,{code:we.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((o,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ji(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Br.mergeArray(n,o)):Br.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new xc({...this._def,rest:e})}}xc.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new xc({items:t,typeName:lt.ZodTuple,rest:null,...ht(e)})};class rg extends St{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ne.object)return Pe(r,{code:we.invalid_type,expected:Ne.object,received:r.parsedType}),ot;const s=[],i=this._def.keyType,o=this._def.valueType;for(const l in r.data)s.push({key:i._parse(new Ji(r,l,r.path,l)),value:o._parse(new Ji(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?Br.mergeObjectAsync(n,s):Br.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof St?new rg({keyType:e,valueType:n,typeName:lt.ZodRecord,...ht(r)}):new rg({keyType:zo.create(),valueType:e,typeName:lt.ZodRecord,...ht(n)})}}class yE extends St{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ne.map)return Pe(r,{code:we.invalid_type,expected:Ne.map,received:r.parsedType}),ot;const s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,u],d)=>({key:s._parse(new Ji(r,l,r.path,[d,"key"])),value:i._parse(new Ji(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of o){const d=await u.key,f=await u.value;if(d.status==="aborted"||f.status==="aborted")return ot;(d.status==="dirty"||f.status==="dirty")&&n.dirty(),l.set(d.value,f.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of o){const d=u.key,f=u.value;if(d.status==="aborted"||f.status==="aborted")return ot;(d.status==="dirty"||f.status==="dirty")&&n.dirty(),l.set(d.value,f.value)}return{status:n.value,value:l}}}}yE.create=(t,e,n)=>new yE({valueType:e,keyType:t,typeName:lt.ZodMap,...ht(n)});class wh extends St{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ne.set)return Pe(r,{code:we.invalid_type,expected:Ne.set,received:r.parsedType}),ot;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(Pe(r,{code:we.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(Pe(r,{code:we.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function o(u){const d=new Set;for(const f of u){if(f.status==="aborted")return ot;f.status==="dirty"&&n.dirty(),d.add(f.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ji(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>o(u)):o(l)}min(e,n){return new wh({...this._def,minSize:{value:e,message:Ze.toString(n)}})}max(e,n){return new wh({...this._def,maxSize:{value:e,message:Ze.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}wh.create=(t,e)=>new wh({valueType:t,minSize:null,maxSize:null,typeName:lt.ZodSet,...ht(e)});class U2 extends St{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}U2.create=(t,e)=>new U2({getter:t,typeName:lt.ZodLazy,...ht(e)});class sg extends St{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return Pe(n,{received:n.data,code:we.invalid_literal,expected:this._def.value}),ot}return{status:"valid",value:e.data}}get value(){return this._def.value}}sg.create=(t,e)=>new sg({value:t,typeName:lt.ZodLiteral,...ht(e)});function zR(t,e){return new bc({values:t,typeName:lt.ZodEnum,...ht(e)})}class bc extends St{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return Pe(n,{expected:Mt.joinValues(r),received:n.parsedType,code:we.invalid_type}),ot}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return Pe(n,{received:n.data,code:we.invalid_enum_value,options:r}),ot}return ri(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return bc.create(e,{...this._def,...n})}exclude(e,n=this._def){return bc.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}}bc.create=zR;class B2 extends St{_parse(e){const n=Mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Ne.string&&r.parsedType!==Ne.number){const s=Mt.objectValues(n);return Pe(r,{expected:Mt.joinValues(s),received:r.parsedType,code:we.invalid_type}),ot}if(this._cache||(this._cache=new Set(Mt.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Mt.objectValues(n);return Pe(r,{received:r.data,code:we.invalid_enum_value,options:s}),ot}return ri(e.data)}get enum(){return this._def.values}}B2.create=(t,e)=>new B2({values:t,typeName:lt.ZodNativeEnum,...ht(e)});class ig extends St{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ne.promise&&n.common.async===!1)return Pe(n,{code:we.invalid_type,expected:Ne.promise,received:n.parsedType}),ot;const r=n.parsedType===Ne.promise?n.data:Promise.resolve(n.data);return ri(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ig.create=(t,e)=>new ig({type:t,typeName:lt.ZodPromise,...ht(e)});class Sc extends St{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===lt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{Pe(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return ot;const u=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return u.status==="aborted"?ot:u.status==="dirty"||n.value==="dirty"?$f(u.value):u});{if(n.value==="aborted")return ot;const l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?ot:l.status==="dirty"||n.value==="dirty"?$f(l.value):l}}if(s.type==="refinement"){const o=l=>{const u=s.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?ot:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?ot:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ud(o))return ot;const l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>ud(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):ot);Mt.assertNever(s)}}Sc.create=(t,e,n)=>new Sc({schema:t,typeName:lt.ZodEffects,effect:e,...ht(n)});Sc.createWithPreprocess=(t,e,n)=>new Sc({schema:e,effect:{type:"preprocess",transform:t},typeName:lt.ZodEffects,...ht(n)});class Uo extends St{_parse(e){return this._getType(e)===Ne.undefined?ri(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Uo.create=(t,e)=>new Uo({innerType:t,typeName:lt.ZodOptional,...ht(e)});class kc extends St{_parse(e){return this._getType(e)===Ne.null?ri(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}kc.create=(t,e)=>new kc({innerType:t,typeName:lt.ZodNullable,...ht(e)});class og extends St{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===Ne.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}og.create=(t,e)=>new og({innerType:t,typeName:lt.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ht(e)});class ag extends St{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Jm(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ag.create=(t,e)=>new ag({innerType:t,typeName:lt.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ht(e)});class _E extends St{_parse(e){if(this._getType(e)!==Ne.nan){const r=this._getOrReturnCtx(e);return Pe(r,{code:we.invalid_type,expected:Ne.nan,received:r.parsedType}),ot}return{status:"valid",value:e.data}}}_E.create=t=>new _E({typeName:lt.ZodNaN,...ht(t)});class UR extends St{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class ib extends St{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?ot:i.status==="dirty"?(n.dirty(),$f(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?ot:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new ib({in:e,out:n,typeName:lt.ZodPipeline})}}class lg extends St{_parse(e){const n=this._def.innerType._parse(e),r=s=>(ud(s)&&(s.value=Object.freeze(s.value)),s);return Jm(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}lg.create=(t,e)=>new lg({innerType:t,typeName:lt.ZodReadonly,...ht(e)});var lt;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(lt||(lt={}));const Ke=zo.create,ob=dd.create,Za=$2.create,Zae=H2.create;Xa.create;const Ec=Ki.create,yn=Hn.create,rz=tg.create,sz=sb.create;ng.create;xc.create;const BR=rg.create,wE=sg.create,cr=bc.create;ig.create;Uo.create;kc.create;const iz=ot,hi=ob().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),oz=yn({command:cr(["open","status","stop","wait","auth.status","variants.start","variants.status","variants.get","variants.list","variants.complete","variants.cancel","reference.fetch","evidence.capture"]).optional(),tool_name:cr(["rivet_login","rivet_explore_designs","rivet_get_exploration","rivet_cancel_exploration","rivet_complete_variant_work","rivet_get_design_context","rivet_find_references","rivet_save_reference","rivet_remove_reference","rivet_preview_reference_import","rivet_import_references","rivet_connect_reference_account","rivet_discover_reference_collections","rivet_save_design_preference","rivet_remove_design_preference","rivet_save_design_check","rivet_remove_design_check","rivet_run_design_check"]).optional(),caller_agent:cr(["claude","codex","cursor","unknown","other"]).optional(),mcp_editor:cr(["claude","claude-desktop","codex","cursor","unknown","other"]).optional(),source:cr(["cli","mcp","core","ui","visual_editor"]).optional(),surface:cr(["cli","mcp","visual_editor"]).optional(),mode:cr(["initial_generation","zero_to_one","source_grounded","comment_refine","vary","history_adoption","commit","unknown"]).optional(),entry_point:cr(["mcp_tool","visual_editor_comment","variants_panel","history","watch_loop","route","unknown","login_command","signin_command","install_flow","tool_call","account_menu","library","menu","onboarding","editor_gate","cli","mcp"]).optional(),project_context_kind:cr(["existing","fresh"]).optional(),preview_kind:cr(["dev_server","static_artifact"]).optional(),provider:cr(["pinterest","arena","cosmos","x"]).optional(),request_status:cr(["accepted","rejected","completed","failed","cancelled","degraded","superseded"]).optional(),error_code:cr(["OPERATION_FAILED","USAGE_ERROR","AUTH_REQUIRED","SERVER_UNAVAILABLE","WAIT_TIMEOUT","SESSION_NOT_FOUND","WORK_ITEM_NOT_FOUND","MCP_REMOVED","STATIC_PREVIEW_FAILED","DEV_SERVER_FAILED","PREVIEW_UNAVAILABLE"]).optional(),failure_reason:cr(["ack_failed","active_session","destination_not_empty","feature_disabled","invalid_stage_action","lease_expired","missing_artifact","missing_required_input","pending_change_conflict","queue_full","runtime_validation_failed","schema_validation_failed","source_context_invalid","start_in_flight","target_not_editable","timeout","unknown","work_item_not_found","local_server_failed","oauth_failed","popup_blocked","credential_store_failed","popup_closed","provider_failed","request_failed","auth_required","invalid_arguments","operation_failed","server_unavailable","usage_error","wait_timeout","session_not_found","mcp_removed","server_start_timeout","handshake_missing","handshake_invalid","process_not_running","health_check_failed","plugin_context_mismatch","telemetry_policy_mismatch","server_starting","transport_failed","server_shutdown_pending","server_process_exited","server_upgrade_required","replacement_version_mismatch","replacement_health_failed","app_health_failed","dev_server_resolution_failed","rivet_port_unavailable","editor_server_start_failed"]).optional(),ok:Za().optional(),is_recoverable:Za().optional(),is_fresh:Za().optional(),duration_ms:hi.optional(),dwell_ms_from_terminal:hi.optional(),exit_code:hi.optional(),requested_count:hi.optional(),accepted_count:hi.optional(),work_item_count:hi.optional(),completed_count:hi.optional(),failed_count:hi.optional(),cancelled_count:hi.optional(),reference_count:hi.optional(),changed_files_count:hi.optional()}),az=new Set(["cli_command_completed","cli_auth_started","cli_auth_completed","cli_auth_failed","mcp_auth_started","mcp_auth_completed","mcp_auth_failed","mcp_tool_executed","mcp_tool_failed","mcp_login_failed","mcp_login_started","mcp_login_completed","visual_editor_auth_started","visual_editor_auth_completed","visual_editor_auth_failed","visual_editor_reference_connection_started","visual_editor_reference_connection_completed","visual_editor_reference_connection_failed","agent_variants.request_started","agent_variants.request_accepted","agent_variants.request_rejected","agent_variants.refinement_requested","agent_variants.refinement_completed","agent_variants.refinement_failed","agent_variants.round_started","agent_variants.round_completed","agent_variants.preview_started","agent_variants.preview_ready","agent_variants.preview_failed"]),lz=(t,e)=>{if(!az.has(t))return null;const n={};for(const[r,s]of Object.entries(oz.shape)){const i=s.safeParse(e[r]);i.success&&i.data!==void 0&&(n[r]=i.data)}return n},cz=yn({token:Ke().min(1)}),uz=t=>cz.parse(t).token,Gg="rivet_library_token";let Ko="",fd=0,bi=null,xE=!1;const W2=new Set,xh=()=>W2.forEach(t=>t()),qae=()=>bi,Gae=()=>fd,bh=()=>{try{const t=window.localStorage.getItem(Gg)??"";Ko!==t&&(fd+=1),Ko=t,bi=null}catch{bi="Rivet cannot access browser storage. Allow site storage and try again."}},WR=()=>{xE||(window.addEventListener("storage",t=>{t.key!==Gg&&t.key!==null||(bh(),xh())}),xE=!0)},Kae=()=>!!Ko,Yae=t=>(WR(),W2.add(t),()=>W2.delete(t)),dz=(t,e)=>{if(e!==void 0&&bh(),e!==void 0&&e!==fd)throw new Error("Sign-in was cancelled because the browser login changed.");try{window.localStorage.setItem(Gg,t)}catch{throw bi="Rivet cannot save browser access. Allow site storage and try again.",xh(),new Error(bi)}Ko=t,fd+=1,bi=null,xh()},ZR=()=>{Ko="",fd+=1,bi=null;try{window.localStorage.removeItem(Gg)}catch{bi="Rivet cannot clear browser storage. Allow site storage and try again."}xh()},fz=async()=>{if(!window.location.pathname.startsWith("/rivet/library"))return;WR(),bh();const t=fd,e=new URLSearchParams(window.location.hash.slice(1)).get("code");if(e){window.history.replaceState(null,"",window.location.pathname+window.location.search);try{const n=await fetch("/api/library/browser-sessions/exchange",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(n.ok){dz(uz(await n.json()),t);return}n.status>=500&&!Ko&&(bi="Rivet is temporarily unavailable. Please retry this link.")}catch{!Ko&&!bi&&(bi="Rivet could not open this link. Please retry when the server is available.")}}xh()},qR=async(t,e={})=>{bh();const n=Ko,r=new Headers(e.headers);r.set("Authorization",`Bearer ${n}`);const s=await fetch(t,{...e,headers:r});return s.status===401&&(bh(),Ko===n&&ZR()),s},hz=async(t,e={})=>{const n=await qR(`/api/library${t}`,{method:e.method??"GET",signal:e.signal,headers:{"Content-Type":"application/json"},...e.body!==void 0?{body:JSON.stringify(e.body)}:{}});return pz(n)},pz=async t=>{const e=await t.text();let n;try{n=JSON.parse(e)}catch{if(t.ok)throw new Error("The library returned an invalid response.")}if(!t.ok){if(t.status===401)throw new Error("Sign in to access this library.");const r=n&&typeof n=="object"&&"error"in n&&typeof n.error=="string"&&n.error.trim()?n.error:`Library request failed (${t.status}).`;throw new Error(r)}return n},bt=(t,e={})=>{if(!window.location.pathname.startsWith("/rivet/library")){const n=new Headers(e.headers),r=_7();return r&&v7(t,e.method)&&n.set(p7,r),fetch(t,{...e,headers:n,redirect:"error"})}return qR(t,e)};let GR="off";const bE=t=>{GR=t},Z2=()=>GR==="full",mz="phc_Ntj9tXHbS64XgYxlTfhglRmFivFsfm0AERph4ZlnNH",gz=3e3,vz=/^plugin-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,yz=t=>({person_profiles:"never",autocapture:!1,opt_out_useragent_filter:!0,capture_pageview:!1,capture_pageleave:!1,capture_exceptions:!1,capture_performance:!1,disable_session_recording:!0,enable_recording_console_log:!1,disable_external_dependency_loading:!0,disable_surveys:!0,advanced_disable_flags:!0,advanced_disable_feature_flags:!0,mask_all_text:!0,mask_all_element_attributes:!0,persistence:"memory",bootstrap:{distinctID:t,isIdentifiedID:!1},before_send:e=>{const n=lz(e.event,e.properties);return n&&bt("/api/telemetry/events",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:e.event,properties:n}),keepalive:!0}).catch(()=>{}),null}}),_z=async()=>{try{const t=await bt("/api/telemetry",{signal:AbortSignal.timeout(gz),cache:"no-store"});if(!t.ok)return;const e=await t.json();if(e.mode!=="full"&&e.mode!=="metrics"||e.mode==="metrics"&&(typeof e.distinctId!="string"||!vz.test(e.distinctId)))return;const n=e.mode,s={api_host:"https://rivet-proxy.onrender.com/ingest",ui_host:"https://us.posthog.com",person_profiles:"always",capture_exceptions:!0,autocapture:!0,capture_pageview:!0,capture_performance:!0,persistence:"localStorage",...{session_recording:{maskAllInputs:!0,maskTextSelector:"[data-rivet-private]",blockSelector:"iframe[data-rivet-private]"}},mask_all_text:!1,mask_all_element_attributes:!1,loaded:i=>i.register({source:"visual_editor",surface:"visual_editor",telemetry_version:2,rivet_version:"0.26.1",env:"production"})};n==="metrics"&&Object.assign(s,yz(e.distinctId),{api_host:window.location.origin}),$e.init(mz,s),bE(n)}catch{bE("off")}},KR=g.createContext(void 0),YR=t=>{const e=g.useContext(KR);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},wz=({client:t,children:e})=>(g.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),S.jsx(KR.Provider,{value:t,children:e})),xz={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)};var Ta,Mx,r5,bz=(r5=class{constructor(){tt(this,Ta,xz);tt(this,Mx,!1)}setTimeoutProvider(t){Ae(this,Ta,t)}setTimeout(t,e){return Z(this,Ta).setTimeout(t,e)}clearTimeout(t){Z(this,Ta).clearTimeout(t)}setInterval(t,e){return Z(this,Ta).setInterval(t,e)}clearInterval(t){Z(this,Ta).clearInterval(t)}},Ta=new WeakMap,Mx=new WeakMap,r5);const Kl=new bz;function Sz(t){setTimeout(t,0)}const kz=typeof window>"u"||"Deno"in globalThis;function es(){}function Ez(t,e){return typeof t=="function"?t(e):t}function XR(t){return typeof t=="number"&&t>=0&&t!==1/0}function QR(t,e){return Math.max(t+(e||0)-Date.now(),0)}function mn(t,e){return typeof t=="function"?t(e):t}function SE(t,e){const{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:l}=t;if(o){if(r){if(e.queryHash!==ab(o,e.options))return!1}else if(!hd(e.queryKey,o))return!1}if(n!=="all"){const u=e.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&e.isStale()!==l||s&&s!==e.state.fetchStatus||i&&!i(e))}function kE(t,e){const{exact:n,status:r,predicate:s,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(n){if(Sh(e.options.mutationKey)!==Sh(i))return!1}else if(!hd(e.options.mutationKey,i))return!1}return!(r&&e.state.status!==r||s&&!s(e))}function ab(t,e){return((e==null?void 0:e.queryKeyHashFn)||Sh)(t)}function Sh(t){return JSON.stringify(t,(e,n)=>q2(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function hd(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(Array.isArray(t)&&Array.isArray(e)){if(e.length>t.length)return!1;for(let r=0;r<e.length;r++)if(!hd(t[r],e[r]))return!1;return!0}const n=Object.keys(e);for(const r of n)if(!hd(t[r],e[r]))return!1;return!0}return!1}const Cz=Object.prototype.hasOwnProperty;function JR(t,e,n=0){if(t===e)return t;if(n>500)return e;const r=EE(t)&&EE(e);if(!r&&!(q2(t)&&q2(e)))return e;const s=(r?t:Object.keys(t)).length,i=r?e:Object.keys(e),o=i.length,l=r?new Array(o):{};let u=0;for(let d=0;d<o;d++){const f=r?d:i[d],h=t[f],m=e[f];if(h===m){l[f]=h,(r?d<s:Cz.call(t,f))&&u++;continue}if(h===null||m===null||typeof h!="object"||typeof m!="object"){l[f]=m;continue}const v=JR(h,m,n+1);l[f]=v,v===h&&u++}return s===o&&u===s?t:l}function Xy(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(const n in t)if(t[n]!==e[n])return!1;return!0}function EE(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function q2(t){if(!CE(t))return!1;const e=Object.getPrototypeOf(t),n=e==null?void 0:e.constructor;if(n===void 0)return!0;if(typeof n!="function")return!1;const r=n.prototype;return!(!CE(r)||!r.hasOwnProperty("isPrototypeOf")||e!==Object.prototype)}function CE(t){return Object.prototype.toString.call(t)==="[object Object]"}function Pz(t){return new Promise(e=>{Kl.setTimeout(e,t)})}function G2(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?JR(t,e):e}function Az(t,e,n=0){const r=[...t,e];return n&&r.length>n?r.slice(1):r}function Tz(t,e,n=0){const r=[e,...t];return n&&r.length>n?r.slice(0,-1):r}const lb=Symbol();function eI(t,e){return!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===lb?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function tI(t,e){return typeof t=="function"?t(...e):!!t}function Rz(t,e,n){let r=!1,s;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(s??(s=e()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),t}let Iz=()=>kz;const cb=()=>Iz();var Xh=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Jl,Ra,Bu,s5,Mz=(s5=class extends Xh{constructor(){super();tt(this,Jl);tt(this,Ra);tt(this,Bu);Ae(this,Bu,e=>{if(typeof window<"u"&&window.addEventListener){const n=()=>e();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){Z(this,Ra)||this.setEventListener(Z(this,Bu))}onUnsubscribe(){var e;this.hasListeners()||((e=Z(this,Ra))==null||e.call(this),Ae(this,Ra,void 0))}setEventListener(e){var n;Ae(this,Bu,e),(n=Z(this,Ra))==null||n.call(this),Ae(this,Ra,e(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(e){Z(this,Jl)!==e&&(Ae(this,Jl,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(n=>{n(e)})}isFocused(){var e;return typeof Z(this,Jl)=="boolean"?Z(this,Jl):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},Jl=new WeakMap,Ra=new WeakMap,Bu=new WeakMap,s5);const ub=new Mz,Oz=Sz;function Lz(){let t=[],e=0,n=l=>{l()},r=l=>{l()},s=Oz;const i=l=>{e?t.push(l):s(()=>{n(l)})},o=()=>{const l=t;t=[],l.length&&s(()=>{r(()=>{l.forEach(u=>{n(u)})})})};return{batch:l=>{let u;e++;try{u=l()}finally{e--,e||o()}return u},batchCalls:l=>(...u)=>{i(()=>{l(...u)})},schedule:i,setNotifyFunction:l=>{n=l},setBatchNotifyFunction:l=>{r=l},setScheduler:l=>{s=l}}}const vr=Lz();var Wu,Ia,Zu,i5,Nz=(i5=class extends Xh{constructor(){super();tt(this,Wu,!0);tt(this,Ia);tt(this,Zu);Ae(this,Zu,e=>{if(typeof window<"u"&&window.addEventListener){const n=()=>e(!0),r=()=>e(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){Z(this,Ia)||this.setEventListener(Z(this,Zu))}onUnsubscribe(){var e;this.hasListeners()||((e=Z(this,Ia))==null||e.call(this),Ae(this,Ia,void 0))}setEventListener(e){var n;Ae(this,Zu,e),(n=Z(this,Ia))==null||n.call(this),Ae(this,Ia,e(this.setOnline.bind(this)))}setOnline(e){Z(this,Wu)!==e&&(Ae(this,Wu,e),this.listeners.forEach(n=>{n(e)}))}isOnline(){return Z(this,Wu)}},Wu=new WeakMap,Ia=new WeakMap,Zu=new WeakMap,i5);const cg=new Nz;function Dz(t){return Math.min(1e3*2**t,3e4)}function nI(t){return(t??"online")==="online"?cg.isOnline():!0}var K2=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function rI(t){let e=!1,n=0,r,s="pending",i,o;const l=new Promise((k,C)=>{i=k,o=C});l.catch(es);const u=()=>s!=="pending",d=k=>{var C;if(!u()){const P=new K2(k);_(P),(C=t.onCancel)==null||C.call(t,P)}},f=()=>{e=!0},h=()=>{e=!1},m=()=>ub.isFocused()&&(t.networkMode==="always"||cg.isOnline())&&t.canRun(),v=()=>nI(t.networkMode)&&t.canRun(),w=k=>{u()||(r==null||r(),s="resolved",i(k))},_=k=>{u()||(r==null||r(),s="rejected",o(k))},x=k=>new Promise(C=>{var P;r=T=>{(u()||k())&&C(T)},(P=t.onPause)==null||P.call(t)}).then(()=>{var C;r=void 0,u()||(C=t.onContinue)==null||C.call(t)}),b=()=>{if(u())return;let k;const C=n===0?t.initialPromise:void 0;try{k=C??t.fn()}catch(P){k=Promise.reject(P)}Promise.resolve(k).then(w).catch(P=>{var L;if(u())return;const T=t.retry??(cb()?0:3),M=t.retryDelay??Dz,I=typeof M=="function"?M(n,P):M,R=T===!0||typeof T=="number"&&n<T||typeof T=="function"&&T(n,P);if(e||!R){_(P);return}n++,(L=t.onFail)==null||L.call(t,n,P),Pz(I).then(()=>m()?void 0:x(m)).then(()=>{e?_(P):b()})})};return{promise:l,status:()=>s,cancel:d,continue:()=>(r==null||r(),l),cancelRetry:f,continueRetry:h,canStart:v,start:()=>(v()?b():x(v).then(b),l)}}var ec,o5,sI=(o5=class{constructor(){tt(this,ec)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),XR(this.gcTime)&&Ae(this,ec,Kl.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(cb()?1/0:3e5))}clearGcTimeout(){Z(this,ec)!==void 0&&(Kl.clearTimeout(Z(this,ec)),Ae(this,ec,void 0))}},ec=new WeakMap,o5);function jz(t){return{onFetch:(e,n)=>{var f,h,m,v,w;const r=e.options,s=(m=(h=(f=e.fetchOptions)==null?void 0:f.meta)==null?void 0:h.fetchMore)==null?void 0:m.direction,i=((v=e.state.data)==null?void 0:v.pages)||[],o=((w=e.state.data)==null?void 0:w.pageParams)||[];let l={pages:[],pageParams:[]},u=0;const d=async()=>{let _=!1;const x=C=>{Rz(C,()=>e.signal,()=>_=!0)},b=eI(e.options,e.fetchOptions),k=async(C,P,T)=>{if(_)return Promise.reject(e.signal.reason);if(P==null&&C.pages.length)return Promise.resolve(C);const I=(()=>{const F={client:e.client,queryKey:e.queryKey,pageParam:P,direction:T?"backward":"forward",meta:e.options.meta};return x(F),F})(),R=await b(I),{maxPages:L}=e.options,j=T?Tz:Az;return{pages:j(C.pages,R,L),pageParams:j(C.pageParams,P,L)}};if(s&&i.length){const C=s==="backward",P=C?$z:PE,T={pages:i,pageParams:o};l=await k(T,P(r,T),C)}else{const C=t??i.length;do{const P=u===0?o[0]===void 0?r.initialPageParam:o[0]:PE(r,l);if(u>0&&P==null)break;l=await k(l,P),u++}while(u<C)}return l};e.options.persister?e.fetchFn=()=>{var _,x;return(x=(_=e.options).persister)==null?void 0:x.call(_,d,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},n)}:e.fetchFn=d}}}function PE(t,{pages:e,pageParams:n}){const r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,n[r],n):void 0}function $z(t,{pages:e,pageParams:n}){var r;return e.length>0?(r=t.getPreviousPageParam)==null?void 0:r.call(t,e[0],e,n[0],n):void 0}var qu,tc,Gu,Ks,nc,Kn,Wh,rc,yi,Io,a5,Fz=(a5=class extends sI{constructor(e){super();tt(this,yi);tt(this,qu);tt(this,tc);tt(this,Gu);tt(this,Ks);tt(this,nc);tt(this,Kn);tt(this,Wh);tt(this,rc);Ae(this,rc,!1),Ae(this,Wh,e.defaultOptions),this.setOptions(e.options),this.observers=[],Ae(this,nc,e.client),Ae(this,Ks,Z(this,nc).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,Ae(this,tc,TE(this.options)),this.state=e.state??Z(this,tc),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return Z(this,qu)}get promise(){var e;return(e=Z(this,Kn))==null?void 0:e.promise}setOptions(e){if(this.options={...Z(this,Wh),...e},e!=null&&e._type&&Ae(this,qu,e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=TE(this.options);n.data!==void 0&&(this.setState(AE(n.data,n.dataUpdatedAt)),Ae(this,tc,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Z(this,Ks).remove(this)}setData(e,n){const r=G2(this.state.data,e,this.options);return xt(this,yi,Io).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(e){xt(this,yi,Io).call(this,{type:"setState",state:e})}cancel(e){var r,s;const n=(r=Z(this,Kn))==null?void 0:r.promise;return(s=Z(this,Kn))==null||s.cancel(e),n?n.then(es).catch(es):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return Z(this,tc)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>mn(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===lb||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>mn(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!QR(this.state.dataUpdatedAt,e)}onFocus(){var e,n;(e=this.observers.find(r=>r.shouldFetchOnWindowFocus()))==null||e.refetch({cancelRefetch:!1}),(n=Z(this,Kn))==null||n.continue()}onOnline(){var e,n;(e=this.observers.find(r=>r.shouldFetchOnReconnect()))==null||e.refetch({cancelRefetch:!1}),(n=Z(this,Kn))==null||n.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),Z(this,Ks).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){const n=this.observers.indexOf(e);n!==-1&&(this.observers.splice(n,1),this.observers.length||(Z(this,Kn)&&(Z(this,rc)||this.state.fetchStatus==="paused"&&this.state.status==="pending"?Z(this,Kn).cancel({revert:!0}):Z(this,Kn).cancelRetry()),this.scheduleGc()),Z(this,Ks).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||xt(this,yi,Io).call(this,{type:"invalidate"})}async fetch(e,n){var d,f,h,m,v,w,_,x,b,k,C,P;if(this.state.fetchStatus!=="idle"&&((d=Z(this,Kn))==null?void 0:d.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(Z(this,Kn))return Z(this,Kn).continueRetry(),Z(this,Kn).promise}if(e&&this.setOptions(e),!this.options.queryFn){const T=this.observers.find(M=>M.options.queryFn);T&&this.setOptions(T.options)}const r=new AbortController,s=T=>{Object.defineProperty(T,"signal",{enumerable:!0,get:()=>(Ae(this,rc,!0),r.signal)})},i=()=>{const T=eI(this.options,n),I=(()=>{const R={client:Z(this,nc),queryKey:this.queryKey,meta:this.meta};return s(R),R})();return Ae(this,rc,!1),this.options.persister?this.options.persister(T,I,this):T(I)},l=(()=>{const T={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:Z(this,nc),state:this.state,fetchFn:i};return s(T),T})();(f=Z(this,qu)==="infinite"?jz(this.options.pages):this.options.behavior)==null||f.onFetch(l,this),Ae(this,Gu,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((h=l.fetchOptions)==null?void 0:h.meta))&&xt(this,yi,Io).call(this,{type:"fetch",meta:(m=l.fetchOptions)==null?void 0:m.meta});const u=Ae(this,Kn,rI({initialPromise:n==null?void 0:n.initialPromise,fn:l.fetchFn,onCancel:T=>{T instanceof K2&&T.revert&&this.setState({...Z(this,Gu),fetchStatus:"idle"}),r.abort()},onFail:(T,M)=>{xt(this,yi,Io).call(this,{type:"failed",failureCount:T,error:M})},onPause:()=>{xt(this,yi,Io).call(this,{type:"pause"})},onContinue:()=>{xt(this,yi,Io).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0}));try{const T=await u.start();if(T===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(T),(w=(v=Z(this,Ks).config).onSuccess)==null||w.call(v,T,this),(x=(_=Z(this,Ks).config).onSettled)==null||x.call(_,T,this.state.error,this),T}catch(T){if(T instanceof K2){if(T.silent)return Z(this,Kn).promise;if(T.revert){if(this.state.data===void 0)throw T;return this.state.data}}throw xt(this,yi,Io).call(this,{type:"error",error:T}),(k=(b=Z(this,Ks).config).onError)==null||k.call(b,T,this),(P=(C=Z(this,Ks).config).onSettled)==null||P.call(C,this.state.data,T,this),T}finally{Z(this,Kn)===u&&Ae(this,Kn,void 0),this.scheduleGc()}}},qu=new WeakMap,tc=new WeakMap,Gu=new WeakMap,Ks=new WeakMap,nc=new WeakMap,Kn=new WeakMap,Wh=new WeakMap,rc=new WeakMap,yi=new WeakSet,Io=function(e){const n=r=>{switch(e.type){case"failed":return{...r,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...iI(r.data,this.options),fetchMeta:e.meta??null};case"success":const s={...r,...AE(e.data,e.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Ae(this,Gu,e.manual?s:void 0),s;case"error":const i=e.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...e.state}}};this.state=n(this.state),vr.batch(()=>{this.observers.slice().forEach(r=>{r.onQueryUpdate()}),Z(this,Ks).notify({query:this,type:"updated",action:e})})},a5);function iI(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:nI(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function AE(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function TE(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,n=e!==void 0,r=n?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var $r,kt,Zh,Fr,sc,Ku,Do,qh,Yu,Xu,ic,oc,Ma,Qu,Ft,Ff,Y2,X2,Q2,J2,ew,tw,nw,rw,l5,Vz=(l5=class extends Xh{constructor(e,n){super();tt(this,Ft);tt(this,$r);tt(this,kt);tt(this,Zh);tt(this,Fr);tt(this,sc);tt(this,Ku);tt(this,Do);tt(this,qh);tt(this,Yu);tt(this,Xu);tt(this,ic);tt(this,oc);tt(this,Ma);tt(this,Qu,new Set);this.options=n,Ae(this,$r,e),Ae(this,Do,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Z(this,kt).addObserver(this),RE(Z(this,kt),this.options)?xt(this,Ft,Ff).call(this):this.updateResult(),xt(this,Ft,ew).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return sw(Z(this,kt),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return sw(Z(this,kt),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,xt(this,Ft,tw).call(this),xt(this,Ft,nw).call(this),Z(this,kt).removeObserver(this)}setOptions(e){const n=this.options,r=Z(this,kt);if(this.options=Z(this,$r).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof mn(this.options.enabled,Z(this,kt))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");xt(this,Ft,rw).call(this),Z(this,kt).setOptions(this.options),n._defaulted&&!Xy(this.options,n)&&Z(this,$r).getQueryCache().notify({type:"observerOptionsUpdated",query:Z(this,kt),observer:this});const s=this.hasListeners();s&&IE(Z(this,kt),r,this.options,n)&&xt(this,Ft,Ff).call(this),this.updateResult(),s&&(Z(this,kt)!==r||mn(this.options.enabled,Z(this,kt))!==mn(n.enabled,Z(this,kt))||mn(this.options.staleTime,Z(this,kt))!==mn(n.staleTime,Z(this,kt)))&&xt(this,Ft,X2).call(this);const i=xt(this,Ft,Q2).call(this);s&&(Z(this,kt)!==r||mn(this.options.enabled,Z(this,kt))!==mn(n.enabled,Z(this,kt))||i!==Z(this,Ma))&&xt(this,Ft,J2).call(this,i)}getOptimisticResult(e){const n=Z(this,$r).getQueryCache().build(Z(this,$r),e),r=this.createResult(n,e);return Xy(this.getCurrentResult(),r)||(Ae(this,Fr,r),Ae(this,Ku,this.options),Ae(this,sc,Z(this,kt).state)),r}getCurrentResult(){return Z(this,Fr)}trackResult(e,n){return new Proxy(e,{get:(r,s)=>(this.trackProp(s),n==null||n(s),Reflect.get(r,s))})}trackProp(e){Z(this,Qu).add(e)}getCurrentQuery(){return Z(this,kt)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const n=Z(this,$r).defaultQueryOptions(e),r=Z(this,$r).getQueryCache().build(Z(this,$r),n);let s=()=>{},i;const o=new Promise(l=>{i=l,s=Z(this,$r).getQueryCache().subscribe(u=>{u.type==="updated"&&u.query.queryHash===r.queryHash&&r.state.data!==void 0&&(s(),l(this.createResult(r,n)))})});return Promise.race([r.fetch(n).then(()=>{const l=this.createResult(r,n);return i==null||i(l),l}).finally(()=>{s()}),o])}fetch(e){return xt(this,Ft,Ff).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),Z(this,Fr)))}createResult(e,n){var M;const r=Z(this,kt),s=this.options,i=Z(this,Fr),o=Z(this,sc),l=Z(this,Ku),u=e!==r?e.state:Z(this,Zh),{state:d}=e;let f={...d},h=!1,m;if(n._optimisticResults){const I=this.hasListeners(),R=!I&&RE(e,n),L=I&&IE(e,r,n,s);(R||L)&&(f={...f,...iI(d.data,e.options)}),n._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:v,errorUpdatedAt:w,status:_}=f;m=f.data;let x=!1;if(n.placeholderData!==void 0&&m===void 0&&_==="pending"){let I;i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData)?(I=i.data,x=!0):I=typeof n.placeholderData=="function"?n.placeholderData((M=Z(this,Xu))==null?void 0:M.state.data,Z(this,Xu)):n.placeholderData,I!==void 0&&(_="success",m=G2(i==null?void 0:i.data,I,n),h=!0)}if(n.select&&m!==void 0&&!x)if(i&&m===(o==null?void 0:o.data)&&n.select===Z(this,qh))m=Z(this,Yu);else try{Ae(this,qh,n.select),m=n.select(m),m=G2(i==null?void 0:i.data,m,n),Ae(this,Yu,m),Ae(this,Do,null)}catch(I){Ae(this,Do,I)}else m===void 0&&Ae(this,Do,null);Z(this,Do)&&(v=Z(this,Do),m=Z(this,Yu),w=Date.now(),_="error",h=!1);const b=f.fetchStatus==="fetching",k=_==="pending",C=_==="error",P=k&&b,T=m!==void 0;return{status:_,fetchStatus:f.fetchStatus,isPending:k,isSuccess:_==="success",isError:C,isInitialLoading:P,isLoading:P,data:m,dataUpdatedAt:f.dataUpdatedAt,error:v,errorUpdatedAt:w,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:f.dataUpdateCount>u.dataUpdateCount||f.errorUpdateCount>u.errorUpdateCount,isFetching:b,isRefetching:b&&!k,isLoadingError:C&&!T,isPaused:f.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:C&&T,isStale:db(e,n),refetch:this.refetch,isEnabled:mn(n.enabled,e)!==!1}}updateResult(){const e=Z(this,Fr),n=this.createResult(Z(this,kt),this.options);if(Ae(this,sc,Z(this,kt).state),Ae(this,Ku,this.options),Z(this,sc).data!==void 0&&Ae(this,Xu,Z(this,kt)),Xy(n,e))return;Ae(this,Fr,n);const s=(()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,o=typeof i=="function"?i():i;if(o==="all"||!o&&!Z(this,Qu).size)return!0;const l=new Set(o??Z(this,Qu));return this.options.throwOnError&&l.add("error"),Object.keys(Z(this,Fr)).some(u=>{const d=u;return Z(this,Fr)[d]!==e[d]&&l.has(d)})})();vr.batch(()=>{s&&this.listeners.forEach(i=>{i(Z(this,Fr))}),Z(this,$r).getQueryCache().notify({query:Z(this,kt),type:"observerResultsUpdated"})})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&xt(this,Ft,ew).call(this)}},$r=new WeakMap,kt=new WeakMap,Zh=new WeakMap,Fr=new WeakMap,sc=new WeakMap,Ku=new WeakMap,Do=new WeakMap,qh=new WeakMap,Yu=new WeakMap,Xu=new WeakMap,ic=new WeakMap,oc=new WeakMap,Ma=new WeakMap,Qu=new WeakMap,Ft=new WeakSet,Ff=function(e){xt(this,Ft,rw).call(this);let n=Z(this,kt).fetch(this.options,e);return e!=null&&e.throwOnError||(n=n.catch(es)),n},Y2=function(e){return!cb()&&mn(this.options.enabled,Z(this,kt))!==!1&&XR(e)},X2=function(){xt(this,Ft,tw).call(this);const e=mn(this.options.staleTime,Z(this,kt));if(Z(this,Fr).isStale||!xt(this,Ft,Y2).call(this,e))return;const n=QR(Z(this,Fr).dataUpdatedAt,e)+1;Ae(this,ic,Kl.setTimeout(()=>{Z(this,Fr).isStale||this.updateResult()},n))},Q2=function(){return mn(this.options.refetchInterval,Z(this,kt))??!1},J2=function(e){xt(this,Ft,nw).call(this),Ae(this,Ma,e),!(Z(this,Ma)===0||!xt(this,Ft,Y2).call(this,Z(this,Ma)))&&Ae(this,oc,Kl.setInterval(()=>{(this.options.refetchIntervalInBackground||ub.isFocused())&&xt(this,Ft,Ff).call(this)},Z(this,Ma)))},ew=function(){xt(this,Ft,X2).call(this),xt(this,Ft,J2).call(this,xt(this,Ft,Q2).call(this))},tw=function(){Z(this,ic)!==void 0&&(Kl.clearTimeout(Z(this,ic)),Ae(this,ic,void 0))},nw=function(){Z(this,oc)!==void 0&&(Kl.clearInterval(Z(this,oc)),Ae(this,oc,void 0))},rw=function(){const e=Z(this,$r).getQueryCache().build(Z(this,$r),this.options);if(e===Z(this,kt))return;const n=Z(this,kt);Ae(this,kt,e),Ae(this,Zh,e.state),this.hasListeners()&&(n==null||n.removeObserver(this),e.addObserver(this))},l5);function Hz(t,e){return mn(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&mn(e.retryOnMount,t)===!1)}function RE(t,e){return Hz(t,e)||t.state.data!==void 0&&sw(t,e,e.refetchOnMount)}function sw(t,e,n){if(mn(e.enabled,t)!==!1&&mn(e.staleTime,t)!=="static"){const r=mn(n,t);return r==="always"||r!==!1&&db(t,e)}return!1}function IE(t,e,n,r){return(t!==e||mn(r.enabled,t)===!1)&&(!n.suspense||t.state.status!=="error")&&db(t,n)}function db(t,e){return mn(e.enabled,t)!==!1&&t.isStaleByTime(mn(e.staleTime,t))}var Gh,Vi,Er,ac,Hi,Ca,c5,zz=(c5=class extends sI{constructor(e){super();tt(this,Hi);tt(this,Gh);tt(this,Vi);tt(this,Er);tt(this,ac);Ae(this,Gh,e.client),this.mutationId=e.mutationId,Ae(this,Er,e.mutationCache),Ae(this,Vi,[]),this.state=e.state||Uz(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){Z(this,Vi).includes(e)||(Z(this,Vi).push(e),this.clearGcTimeout(),Z(this,Er).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){Ae(this,Vi,Z(this,Vi).filter(n=>n!==e)),this.scheduleGc(),Z(this,Er).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){Z(this,Vi).length||(this.state.status==="pending"?this.scheduleGc():Z(this,Er).remove(this))}continue(){var e;return((e=Z(this,ac))==null?void 0:e.continue())??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(e){var l,u,d,f,h,m,v,w,_,x,b,k,C,P,T,M,I,R;const n=()=>{xt(this,Hi,Ca).call(this,{type:"continue"})},r={client:Z(this,Gh),meta:this.options.meta,mutationKey:this.options.mutationKey},s=Ae(this,ac,rI({fn:()=>this.options.mutationFn?this.options.mutationFn(e,r):Promise.reject(new Error("No mutationFn found")),onFail:(L,j)=>{xt(this,Hi,Ca).call(this,{type:"failed",failureCount:L,error:j})},onPause:()=>{xt(this,Hi,Ca).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Z(this,Er).canRun(this)})),i=this.state.status==="pending",o=!s.canStart();try{if(i)n();else{xt(this,Hi,Ca).call(this,{type:"pending",variables:e,isPaused:o}),Z(this,Er).config.onMutate&&await Z(this,Er).config.onMutate(e,this,r);const j=await((u=(l=this.options).onMutate)==null?void 0:u.call(l,e,r));j!==this.state.context&&xt(this,Hi,Ca).call(this,{type:"pending",context:j,variables:e,isPaused:o})}const L=await s.start();return await((f=(d=Z(this,Er).config).onSuccess)==null?void 0:f.call(d,L,e,this.state.context,this,r)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,L,e,this.state.context,r)),await((w=(v=Z(this,Er).config).onSettled)==null?void 0:w.call(v,L,null,this.state.variables,this.state.context,this,r)),await((x=(_=this.options).onSettled)==null?void 0:x.call(_,L,null,e,this.state.context,r)),xt(this,Hi,Ca).call(this,{type:"success",data:L}),L}catch(L){try{await((k=(b=Z(this,Er).config).onError)==null?void 0:k.call(b,L,e,this.state.context,this,r))}catch(j){Promise.reject(j)}try{await((P=(C=this.options).onError)==null?void 0:P.call(C,L,e,this.state.context,r))}catch(j){Promise.reject(j)}try{await((M=(T=Z(this,Er).config).onSettled)==null?void 0:M.call(T,void 0,L,this.state.variables,this.state.context,this,r))}catch(j){Promise.reject(j)}try{await((R=(I=this.options).onSettled)==null?void 0:R.call(I,void 0,L,e,this.state.context,r))}catch(j){Promise.reject(j)}throw xt(this,Hi,Ca).call(this,{type:"error",error:L}),L}finally{Z(this,ac)===s&&Ae(this,ac,void 0),Z(this,Er).runNext(this)}}},Gh=new WeakMap,Vi=new WeakMap,Er=new WeakMap,ac=new WeakMap,Hi=new WeakSet,Ca=function(e){const n=r=>{switch(e.type){case"failed":return{...r,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...r,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:e.error,failureCount:r.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=n(this.state),vr.batch(()=>{Z(this,Vi).forEach(r=>{r.onMutationUpdate(e)}),Z(this,Er).notify({mutation:this,type:"updated",action:e})})},c5);function Uz(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Oa,_i,Kh,u5,Bz=(u5=class extends Xh{constructor(e={}){super();tt(this,Oa);tt(this,_i);tt(this,Kh);this.config=e,Ae(this,Oa,new Set),Ae(this,_i,new Map),Ae(this,Kh,0)}build(e,n,r){const s=new zz({client:e,mutationCache:this,mutationId:++v0(this,Kh)._,options:e.defaultMutationOptions(n),state:r});return this.add(s),s}add(e){Z(this,Oa).add(e);const n=A0(e);if(typeof n=="string"){const r=Z(this,_i).get(n);r?r.push(e):Z(this,_i).set(n,[e])}this.notify({type:"added",mutation:e})}remove(e){if(Z(this,Oa).delete(e)){const n=A0(e);if(typeof n=="string"){const r=Z(this,_i).get(n);if(r)if(r.length>1){const s=r.indexOf(e);s!==-1&&r.splice(s,1)}else r[0]===e&&Z(this,_i).delete(n)}}this.notify({type:"removed",mutation:e})}canRun(e){var r;const n=A0(e);if(typeof n=="string"){const s=(r=Z(this,_i).get(n))==null?void 0:r.find(i=>i.state.status==="pending");return!s||s===e}else return!0}runNext(e){var r,s;const n=A0(e);return typeof n=="string"?((s=(r=Z(this,_i).get(n))==null?void 0:r.find(i=>i!==e&&i.state.isPaused))==null?void 0:s.continue())??Promise.resolve():Promise.resolve()}clear(){vr.batch(()=>{const e=this.getAll();Z(this,Oa).clear(),Z(this,_i).clear(),e.forEach(n=>{this.notify({type:"removed",mutation:n})})})}getAll(){return Array.from(Z(this,Oa))}find(e){const n={exact:!0,...e};return this.getAll().find(r=>kE(n,r))}findAll(e={}){return this.getAll().filter(n=>kE(e,n))}notify(e){vr.batch(()=>{this.listeners.forEach(n=>{n(e)})})}resumePausedMutations(){const e=this.getAll().filter(n=>n.state.isPaused);return vr.batch(()=>Promise.all(e.map(n=>n.continue().catch(es))))}},Oa=new WeakMap,_i=new WeakMap,Kh=new WeakMap,u5);function A0(t){var e;return(e=t.options.scope)==null?void 0:e.id}var zi,d5,Wz=(d5=class extends Xh{constructor(e={}){super();tt(this,zi);this.config=e,Ae(this,zi,new Map)}build(e,n,r){const s=n.queryKey,i=n.queryHash??ab(s,n);let o=this.get(i);return o||(o=new Fz({client:e,queryKey:s,queryHash:i,options:e.defaultQueryOptions(n),state:r,defaultOptions:e.getQueryDefaults(s)}),this.add(o)),o}add(e){Z(this,zi).has(e.queryHash)||(Z(this,zi).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){Z(this,zi).get(e.queryHash)===e&&(e.destroy(),Z(this,zi).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){vr.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return Z(this,zi).get(e)}getAll(){return[...Z(this,zi).values()]}find(e){const n={exact:!0,...e};return this.getAll().find(r=>SE(n,r))}findAll(e={}){const n=this.getAll();return Object.keys(e).length>0?n.filter(r=>SE(e,r)):n}notify(e){vr.batch(()=>{this.listeners.forEach(n=>{n(e)})})}onFocus(){vr.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){vr.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},zi=new WeakMap,d5),bn,La,Na,Ju,ed,Da,td,nd,f5,Zz=(f5=class{constructor(t={}){tt(this,bn);tt(this,La);tt(this,Na);tt(this,Ju);tt(this,ed);tt(this,Da);tt(this,td);tt(this,nd);Ae(this,bn,t.queryCache||new Wz),Ae(this,La,t.mutationCache||new Bz),Ae(this,Na,t.defaultOptions||{}),Ae(this,Ju,new Map),Ae(this,ed,new Map),Ae(this,Da,0)}mount(){v0(this,Da)._++,Z(this,Da)===1&&(Ae(this,td,ub.subscribe(async t=>{t&&(await this.resumePausedMutations(),Z(this,bn).onFocus())})),Ae(this,nd,cg.subscribe(async t=>{t&&(await this.resumePausedMutations(),Z(this,bn).onOnline())})))}unmount(){var t,e;v0(this,Da)._--,Z(this,Da)===0&&((t=Z(this,td))==null||t.call(this),Ae(this,td,void 0),(e=Z(this,nd))==null||e.call(this),Ae(this,nd,void 0))}isFetching(t){return Z(this,bn).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return Z(this,La).findAll({...t,status:"pending"}).length}getQueryData(t){var n;const e=this.defaultQueryOptions({queryKey:t});return(n=Z(this,bn).get(e.queryHash))==null?void 0:n.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),n=Z(this,bn).build(this,e),r=n.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&n.isStaleByTime(mn(e.staleTime,n))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return Z(this,bn).findAll(t).map(({queryKey:e,state:n})=>[e,n.data])}setQueryData(t,e,n){var o;const r=this.defaultQueryOptions({queryKey:t}),s=(o=Z(this,bn).get(r.queryHash))==null?void 0:o.state.data,i=Ez(e,s);if(i!==void 0)return Z(this,bn).build(this,r).setData(i,{...n,manual:!0})}setQueriesData(t,e,n){return vr.batch(()=>Z(this,bn).findAll(t).map(({queryKey:r})=>[r,this.setQueryData(r,e,n)]))}getQueryState(t){var n;const e=this.defaultQueryOptions({queryKey:t});return(n=Z(this,bn).get(e.queryHash))==null?void 0:n.state}removeQueries(t){const e=Z(this,bn);vr.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){const n=Z(this,bn);return vr.batch(()=>{const r=n.findAll(t),s=new Set(r);return r.forEach(i=>{i.reset()}),this.refetchQueries({type:"active",predicate:i=>s.has(i)},e)})}cancelQueries(t,e={}){const n={revert:!0,...e},r=vr.batch(()=>Z(this,bn).findAll(t).map(s=>s.cancel(n)));return Promise.all(r).then(es).catch(es)}invalidateQueries(t,e={}){return vr.batch(()=>(Z(this,bn).findAll(t).forEach(n=>{n.invalidate()}),(t==null?void 0:t.refetchType)==="none"?Promise.resolve():this.refetchQueries({...t,type:(t==null?void 0:t.refetchType)??(t==null?void 0:t.type)??"active"},e)))}refetchQueries(t,e={}){const n={...e,cancelRefetch:e.cancelRefetch??!0},r=vr.batch(()=>Z(this,bn).findAll(t).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(es)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(es)}async query(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const n=Z(this,bn).build(this,e),r=n.isStaleByTime(mn(e.staleTime,n))?await n.fetch(e):n.state.data,s=e.select;return s?s(r):r}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const n=Z(this,bn).build(this,e);return n.isStaleByTime(mn(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(es).catch(es)}infiniteQuery(t){return t._type="infinite",this.query(t)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(es).catch(es)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return cg.isOnline()?Z(this,La).resumePausedMutations():Promise.resolve()}getQueryCache(){return Z(this,bn)}getMutationCache(){return Z(this,La)}getDefaultOptions(){return Z(this,Na)}setDefaultOptions(t){Ae(this,Na,t)}setQueryDefaults(t,e){Z(this,Ju).set(Sh(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...Z(this,Ju).values()],n={};return e.forEach(r=>{hd(t,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(t,e){Z(this,ed).set(Sh(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...Z(this,ed).values()],n={};return e.forEach(r=>{hd(t,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(t){if(t._defaulted)return t;const e={...Z(this,Na).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=ab(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===lb&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...Z(this,Na).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){Z(this,bn).clear(),Z(this,La).clear()}},bn=new WeakMap,La=new WeakMap,Na=new WeakMap,Ju=new WeakMap,ed=new WeakMap,Da=new WeakMap,td=new WeakMap,nd=new WeakMap,f5);const oI=g.createContext(!1),qz=()=>g.useContext(oI);oI.Provider;function Gz(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}const Kz=g.createContext(Gz()),Yz=()=>g.useContext(Kz),Xz=(t,e,n)=>{const r=(n==null?void 0:n.state.status)==="error"&&typeof t.throwOnError=="function"?tI(t.throwOnError,[n.state.error,n]):t.throwOnError;(t.suspense||r)&&(e.isReset()||(t.retryOnMount=!1))},Qz=t=>{g.useEffect(()=>{t.clearReset()},[t])},Jz=({result:t,errorResetBoundary:e,throwOnError:n,query:r,suspense:s})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(s&&t.data===void 0||tI(n,[t.error,r])),eU=t=>{if(t.suspense){const n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=t.staleTime;t.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},tU=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,nU=(t,e,n)=>e.fetchOptimistic(t).catch(()=>{n.clearReset()});function rU(t,e,n){const r=qz(),s=Yz(),i=YR(),o=i.defaultQueryOptions(t),l=i.getQueryCache().get(o.queryHash),u=t.subscribed!==!1;o._optimisticResults=r?"isRestoring":u?"optimistic":void 0,eU(o),Xz(o,s,l),Qz(s);const[d]=g.useState(()=>new e(i,o)),f=d.getOptimisticResult(o),h=!r&&u;if(g.useSyncExternalStore(g.useCallback(m=>{const v=h?d.subscribe(vr.batchCalls(m)):es;return d.updateResult(),v},[d,h]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),g.useEffect(()=>{d.setOptions(o)},[o,d]),tU(o,f))throw nU(o,d,s);if(Jz({result:f,errorResetBoundary:s,throwOnError:o.throwOnError,query:l,suspense:o.suspense}))throw f.error;return o.notifyOnChangeProps?f:d.trackResult(f)}function kh(t,e){return rU(t,Vz)}var sU=(function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(r[i]=s[i])},t(e,n)};return function(e,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();var iU=function(t,e,n){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:n?"".concat(n," ",e):e})},T0,ME="__POSTHOG_REACT_SHARED_STATE__",OE=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},Eh;try{Eh=OE[ME]=OE[ME]||new WeakMap}catch{Eh=new WeakMap}Eh.has(g.createContext)||Eh.set(g.createContext,{});var dc=Eh.get(g.createContext),iw;function oU(t){(!dc.defaultPostHogInstance||dc.defaultPostHogInstance===iw)&&(dc.defaultPostHogInstance=t),iw=t}function ow(){return iw}dc.context||(dc.context=g.createContext({get client(){return ow()||dc.defaultPostHogInstance},bootstrap:void 0}));var fb=dc.context;function aI(t,e,n){if(n===void 0&&(n=new WeakMap),t===e)return!0;if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;if(n.has(t)&&n.get(t)===e)return!0;n.set(t,e);var r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return!1;for(var i=0,o=r;i<o.length;i++){var l=o[i];if(!s.includes(l)||!aI(t[l],e[l],n))return!1}return!0}function aU(t){var e,n,r=t.children,s=t.client,i=t.apiKey,o=t.options,l=g.useRef(null),u=g.useMemo(function(){if(s)return i&&console.warn("[PostHog.js] You have provided both `client` and `apiKey` to `PostHogProvider`. `apiKey` will be ignored in favour of `client`."),o&&console.warn("[PostHog.js] You have provided both `client` and `options` to `PostHogProvider`. `options` will be ignored in favour of `client`."),s;var d=ow();return i||console.warn("[PostHog.js] No `apiKey` or `client` were provided to `PostHogProvider`. Using default global `window.posthog` instance. You must initialize it manually. This is not recommended behavior."),d},[s,i,JSON.stringify(o)]);return g.useEffect(function(){if(!(s||!i)){var d=ow(),f=l.current;f?(i!==f.apiKey&&console.warn("[PostHog.js] You have provided a different `apiKey` to `PostHogProvider` than the one that was already initialized. This is not supported by our provider and we'll keep using the previous key. If you need to toggle between API Keys you need to control the `client` yourself and pass it in as a prop rather than an `apiKey` prop."),o&&!aI(o,f.options)&&d.set_config(o),l.current={apiKey:i,options:o??{}}):(d.__loaded&&console.warn("[PostHog.js] `posthog` was already loaded elsewhere. This may cause issues."),d.init(i,o),l.current={apiKey:i,options:o??{}})}},[s,i,JSON.stringify(o)]),_e.createElement(fb.Provider,{value:{client:u,bootstrap:(e=o==null?void 0:o.bootstrap)!==null&&e!==void 0?e:(n=s==null?void 0:s.config)===null||n===void 0?void 0:n.bootstrap}},r)}var Qy=function(t){return typeof t=="function"},lU=function(t){return t===void 0},si=function(){var t=g.useContext(fb).client;return t},cm=function(t){var e=Object.prototype.toString.call(t);return t instanceof Error||e==="[object Error]"||e==="[object Exception]"||e==="[object DOMException]"||e==="[object DOMError]"},cU=function(t,e){try{Object.defineProperty(t,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}},uU=function(t,e){for(var n=new WeakSet,r=t;!n.has(r);){if(n.add(r),!cm(r.cause)){lU(r.cause)||(e.cause=r.cause),r.cause=e;return}r=r.cause}},dU=function(t,e){if(!e)return t;var n=new Error(cm(t)?t.message:"Primitive value captured as exception: ".concat(String(t)));return cU(n,"React ErrorBoundary ".concat(cm(t)?t.name:"Error")),n.stack=e,cm(t)?(uU(t,n),t):n},LE={componentStack:null,exceptionEvent:null,error:null},fU={INVALID_FALLBACK:"[PostHog.js][PostHogErrorBoundary] Invalid fallback prop, provide a valid React element or a function that returns a valid React element."},hU=(T0=(function(t){sU(e,t);function e(n){var r=t.call(this,n)||this;return r._resetError=function(){r.setState(LE)},r.state=LE,r}return e.prototype.componentDidCatch=function(n,r){var s=this.props.additionalProperties,i;Qy(s)?i=s(n,r):typeof s=="object"&&(i=s);var o=this.context.client,l=r.componentStack,u=o.captureException(dU(n,l),i);this.setState({error:n,componentStack:l??null,exceptionEvent:u})},e.prototype.render=function(){var n=this.props,r=n.children,s=n.fallback,i=this.state;if(i.componentStack==null)return Qy(r)?r():r;var o=Qy(s)?_e.createElement(s,{error:i.error,componentStack:i.componentStack,exceptionEvent:i.exceptionEvent,resetError:this._resetError}):s;return _e.isValidElement(o)?o:(console.warn(fU.INVALID_FALLBACK),_e.createElement(_e.Fragment,null))},e})(_e.Component),iU(T0,"PostHogErrorBoundary"),(function(){T0.contextType=fb})(),T0);oU($e);const pU="rivet-preview-bridge",mU=["ArrowUp","ArrowDown"],gU=new Set(["INPUT","TEXTAREA","SELECT"]),lI=t=>!t||!("tagName"in t)||typeof t.tagName!="string"?!1:gU.has(t.tagName.toUpperCase())||"isContentEditable"in t&&t.isContentEditable===!0,vU=t=>typeof t!="object"||t===null||!("channel"in t)||t.channel!==pU||!("direction"in t)||t.direction!=="event"||!("type"in t)||t.type!=="keydown"||!("key"in t)?null:mU.find(e=>e===t.key)??null,yU=t=>{try{return new URL(t.src,window.location.href).origin}catch{return null}},_U=t=>t.source===null?null:Array.from(document.querySelectorAll("iframe")).find(e=>e.contentWindow===t.source&&yU(e)===t.origin)??null,wU=t=>{const e=n=>{lI(n.target)||t(n)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},xU=()=>{const t=e=>{const n=vU(e.data),r=n?_U(e):null;!n||!r||r.dispatchEvent(new KeyboardEvent("keydown",{key:n,bubbles:!0,cancelable:!0}))};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)};var R0={},Jy={exports:{}},Xr={},e_={exports:{}},t_={};/**
|
|
20
20
|
* @license React
|
|
21
21
|
* scheduler.production.min.js
|
|
22
22
|
*
|
|
@@ -138,7 +138,7 @@ function useAtomValueWithDelay<Value>(
|
|
|
138
138
|
<body>
|
|
139
139
|
<div class="panel">${lA}</div>
|
|
140
140
|
</body>
|
|
141
|
-
</html>`,Ute=yn({success:Za(),authUrl:Ke().optional(),sessionId:Ke().optional(),pollSecret:Ke().optional(),error:Ke().optional(),message:Ke().optional()}),Bte=yn({success:Za(),token:Ke().optional(),refreshToken:Ke().optional(),user:yn({id:Ke().optional(),email:Ke().optional()}).optional(),error:Ke().optional(),message:Ke().optional()}),Wte="/api/auth/install-ref",Zte=yn({installRef:Ke().nullable()}),qte=async()=>{try{const t=await fetch(Wte);if(!t.ok)return;const e=Zte.safeParse(await t.json());return e.success?e.data.installRef??void 0:void 0}catch{return}},G9=(t="editor_gate",e)=>{const n=si(),[r,s]=g.useState(!1),[i,o]=g.useState(null);return{startLogin:g.useCallback(async()=>{var m;const u=globalThis.crypto.randomUUID(),d=Date.now();s(!0),o(null);const f=D_({outcome:"started",authAttemptId:u,entryPoint:t,startedAt:d,now:d});n==null||n.capture(f.event,f.properties);let h=null;try{if(h=window.open("","_blank"),!h)throw new Error("Pop-up blocked. Please allow pop-ups and try again.");try{h.document.open(),h.document.write(zte),h.document.close()}catch(b){aA.warn("Failed to render loading state in auth popup:",b)}const v=await qte(),w=await fetch(`${ix}/api/auth/google/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"core",...v?{ref:v}:{}})}),_=Ute.safeParse(await w.json());if(!_.success)throw new Error("Invalid Google login response");const x=_.data;if(!w.ok||!x.success||!x.authUrl||!x.sessionId||!x.pollSecret)throw new Error(x.error||x.message||"Failed to start Google login");if(h.closed)throw new Error("Sign-in window was closed before Google login started.");h.location.href=x.authUrl;for(let b=0;b<Hte;b+=1){if(h.closed)throw new Error("Sign-in window was closed before authentication completed.");const k=await fetch(`${ix}/api/auth/google/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session:x.sessionId,pollSecret:x.pollSecret})}),C=Bte.safeParse(await k.json());if(!C.success)throw new Error("Invalid Google token response");const P=C.data;if(P.success&&P.token&&((m=P.user)!=null&&m.email)){const T={email:P.user.email,token:P.token,refreshToken:P.refreshToken,userId:P.user.id,...v?{installRef:v}:{}};if(e)await e(T);else if(!(await bt("/api/auth/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(T)})).ok)throw new Error("Signed in, but failed to store session locally.");h.close(),window.sessionStorage.setItem(Ig,"1");const M=D_({outcome:"completed",authAttemptId:u,entryPoint:t,startedAt:d,now:Date.now()});n==null||n.capture(M.event,M.properties),window.location.reload();return}if(P.error&&P.error!=="Pending")throw new Error(P.error||"Google login failed");await new Promise(T=>setTimeout(T,Vte))}throw new Error("Authentication timed out. Please try again.")}catch(v){h&&!h.closed&&h.close();const w=Rr(v,"Failed to start login flow");aA.warn("Login failed:",w);const _=D_({outcome:"failed",authAttemptId:u,entryPoint:t,startedAt:d,now:Date.now(),failureReason:Fte(w)});n==null||n.capture(_.event,_.properties),o(w),s(!1)}},[n,t,e]),isStartingLogin:r,loginError:i}},Gte=Ls("useIntegrations"),Kte=yn({provider:Ke(),status:Ke(),externalUsername:Ke().nullable(),connectedAt:Ke()}),Yte=yn({integrations:Ec(Kte).optional()}),Xte=yn({authUrl:Ke().min(1).optional(),error:Ke().optional()}),Qte=yn({error:Ke().optional()}),j_=["integrations"],Jte="rivet:connect-result",ene=t=>typeof t=="object"&&t!==null&&t.type===Jte,tne=qt(null),cA=async()=>{const t=await bt("/api/integrations");if(!t.ok)throw new Error(`Failed to load integrations (${t.status})`);return Yte.parse(await t.json()).integrations??[]},nne=()=>{const t=YR(),[e,n]=mI(tne),r=kh({queryKey:j_,queryFn:cA,staleTime:1e4}),s=g.useCallback(async()=>(await t.invalidateQueries({queryKey:j_,refetchType:"none"}),t.fetchQuery({queryKey:j_,queryFn:cA})),[t]),i=g.useCallback(async l=>{const u=window.open("","_blank","width=560,height=720");if(!u)throw new Error("Popup blocked. Allow popups to connect.");n(l);try{const d=await bt(`/api/integrations/${l}/connect`,{method:"POST"}),f=Xte.safeParse(await d.json().catch(()=>({}))),h=f.success?f.data:{};if(!d.ok||!h.authUrl)throw u.close(),new Error(h.error||`Could not connect ${l}`);return u.location.href=h.authUrl,await new Promise(m=>{let v=!1,w=null;const _=async(b,k=!1)=>{if(!v){v=!0,window.removeEventListener("message",x),w&&clearInterval(w);try{const P=(await s()).some(T=>T.provider===l&&T.status==="connected");m(k&&P?"connected":b)}catch{m(b)}}},x=b=>{if(ene(b.data)&&b.data.provider===l){if(b.data.status==="error"){Gte.warn(`Connect failed for ${l}:`,b.data.message),_("failed");return}_("connected")}};window.addEventListener("message",x),w=setInterval(()=>{u.closed&&_("closed",!0)},500)})}finally{n(null)}},[s,n]),o=g.useCallback(async l=>{n(l);try{const u=await bt(`/api/integrations/${l}`,{method:"DELETE"});if(!u.ok){const d=Qte.safeParse(await u.json().catch(()=>({}))),f=d.success?d.data:{};throw new Error(f.error||`Could not disconnect ${l}`)}await s()}finally{n(null)}},[s,n]);return{integrations:r.data??[],isLoading:r.isPending,error:r.error instanceof Error?r.error.message:null,pendingProvider:e,connect:i,disconnect:o,refetch:s}},$l=({action:t,outcome:e,provider:n,entryPoint:r,durationMs:s,failureReason:i})=>({event:`visual_editor_reference_${t==="connect"?"connection":"disconnection"}_${e}`,properties:{provider:n,entry_point:r,...s!==void 0?{duration_ms:s}:{},...i?{failure_reason:i}:{}}}),ap=async(t,e="GET",n)=>{if(window.location.pathname.startsWith("/rivet/library"))return hz(t,{method:e,body:n});const r=await bt(t.replace(/^\/profile/,"/api/reference-profiles"),{method:e,headers:{"Content-Type":"application/json"},...n!==void 0?{body:JSON.stringify(n)}:{}}),s=await r.text();let i;try{i=JSON.parse(s)}catch{throw new Error(`Reference profile request failed (${r.status})`)}if(!r.ok)throw new Error(i.error??`Request failed (${r.status})`);return i},K9=()=>ap("/profile"),rne=t=>kh({queryKey:["cosmos-profile"],queryFn:K9,enabled:t}),sne=t=>ap("/profile/discoveries","POST",{url:t}),ine=({discoveryId:t,collectionIds:e,runtime:n})=>ap("/profile/import-plans","POST",{discoveryId:t,collectionIds:e,runtime:n}),one=t=>ap("/profile","PATCH",{isEnabled:!0,runtime:t}),ane=t=>ap(`/profile/import-plans/${t.id}/imports`,"POST",{revision:t.revision,isApproved:!0}),ox=Ke().regex(/^[1-9]\d{0,15}$/).refine(t=>Number.isSafeInteger(Number(t))),lne=Ke().min(1).max(4096),Y9=t=>{const e=()=>new Error("Use an HTTPS Cosmos profile URL such as https://www.cosmos.so/username");let n;try{n=new URL(t)}catch{throw e()}const r=n.pathname.split("/").filter(Boolean);if(n.protocol!=="https:"||n.username||n.password||n.port||!["cosmos.so","www.cosmos.so"].includes(n.hostname)||r.length!==1)throw e();let s;try{s=decodeURIComponent(r[0])}catch{throw e()}if(!/^[a-zA-Z0-9_.-]{1,100}$/.test(s)||["e","login","signup","explore","search","collections","settings","api","profile"].includes(s.toLowerCase()))throw e();return{username:s,url:`https://www.cosmos.so/${encodeURIComponent(s)}`}};Ke().max(2048).transform((t,e)=>{try{return Y9(t).url}catch(n){return e.addIssue({code:we.custom,message:Rr(n,"Invalid Cosmos profile URL")}),iz}});const cne=t=>{const e=()=>new Error("Use an HTTPS Cosmos collection URL such as https://www.cosmos.so/owner/collection");let n;try{n=new URL(t)}catch{throw e()}const r=n.pathname.split("/").filter(Boolean);if(n.protocol!=="https:"||n.username||n.password||n.port||!["cosmos.so","www.cosmos.so"].includes(n.hostname)||r.length<2||r.length>3||r[0]==="e")throw e();let s;try{s=r.map(i=>decodeURIComponent(i))}catch{throw e()}if(s.some(i=>!i.length||i.length>300||/[/\\\p{Cc}]/u.test(i)))throw e();return{ownerUsername:s[0],slug:s[1],subcollectionSlug:s[2],url:`https://www.cosmos.so/${s.map(encodeURIComponent).join("/")}`}},une=Ke().url().refine(t=>{const e=new URL(t);return e.protocol==="https:"&&e.hostname==="cdn.cosmos.so"&&!e.username&&!e.password&&!e.port}),dne=yn({id:ox,title:Ke().min(1).max(500),url:Ke().url().transform(t=>cne(t).url),children:Ec(ox)}),fne=yn({id:ox,url:Ke().url(),title:Ke().max(1e3),text:Ke().max(1e5),author:Ke().nullable(),owner:Ke().nullable(),sourceUrl:Ke().url().nullable(),images:Ec(yn({url:une,representation:cr(["image","video-cover"])})).max(100),unsupportedReason:Ke().optional()}),hne=yn({collection:dne,elements:Ec(fne),total:ob().int().nonnegative(),nextCursor:lne.nullable()});sz("status",[hne.extend({status:wE("ok")}),yn({status:wE("error"),message:Ke(),reason:cr(["rate_limited","provider_unavailable","collection_unavailable"]).optional(),retryAfterMs:ob().nonnegative().optional()})]);const pne=({isOpen:t,onClose:e,onImported:n})=>{const[r,s]=g.useState(""),[i,o]=g.useState(null),[l,u]=g.useState([]),[d,f]=g.useState(""),[h,m]=g.useState(null),[v,w]=g.useState(null),[_,x]=g.useState(!1),b=g.useRef(0),k=si(),C=()=>{b.current+=1,s(""),o(null),u([]),f(""),m(null),w(null),x(!1)},P=()=>{k==null||k.capture("visual_editor_cosmos_modal_closed"),C(),e()},T=async L=>{L.preventDefault(),w(null);let j;try{j=Y9(r.trim()).url}catch(N){w(Rr(N,"Invalid Cosmos profile URL"));return}k==null||k.capture("visual_editor_cosmos_discovery_started");const F=++b.current;x(!0);try{const N=await sne(j);if(F!==b.current)return;o(N),u([]),k==null||k.capture("visual_editor_cosmos_discovery_completed",{collection_count:N.collections.length})}catch(N){if(F!==b.current)return;w(Rr(N,"Could not find Cosmos profile")),k==null||k.capture("visual_editor_cosmos_discovery_failed")}finally{F===b.current&&x(!1)}},M=async()=>{if(!i||l.length===0||!d)return;w(null),k==null||k.capture("visual_editor_cosmos_plan_started",{collection_count:l.length,runtime:d});const L=++b.current;x(!0);try{const j=await ine({discoveryId:i.id,collectionIds:l,runtime:d});if(L!==b.current)return;m(j),k==null||k.capture("visual_editor_cosmos_plan_completed",{collection_count:j.collectionCount,reference_count:j.referenceCount})}catch(j){if(L!==b.current)return;w(Rr(j,"Could not prepare import plan")),k==null||k.capture("visual_editor_cosmos_plan_failed")}finally{L===b.current&&x(!1)}},I=async()=>{if(!h||!d)return;w(null),k==null||k.capture("visual_editor_cosmos_import_started",{collection_count:h.collectionCount,reference_count:h.referenceCount});const L=++b.current;x(!0);try{if((await K9()).profile.isEnabled||await one(d),await ane(h),k==null||k.capture("visual_editor_cosmos_import_completed",{reference_count:h.referenceCount}),n(),L!==b.current)return;C(),e()}catch(j){if(k==null||k.capture("visual_editor_cosmos_import_failed"),L!==b.current)return;w(Rr(j,"Could not start Cosmos import"))}finally{L===b.current&&x(!1)}},R=L=>{u(j=>j.includes(L)?j.filter(F=>F!==L):[...j,L]),k==null||k.capture("visual_editor_cosmos_collection_toggled")};return S.jsx(dv,{open:t,onOpenChange:L=>!L&&P(),children:S.jsxs(fv,{children:[S.jsx(hv,{className:"z-max fixed inset-0 bg-black/60"}),S.jsxs(pv,{className:"z-max border-main-border bg-main font-main fixed top-1/2 left-1/2 max-h-[min(680px,calc(100vh-32px))] w-[min(440px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-lg border shadow-2xl outline-none",children:[S.jsxs("div",{className:"border-main-border bg-main-light flex items-center justify-between rounded-t-lg border-b px-4 py-2",children:[S.jsx(mv,{className:"text-content text-base font-medium",children:"Connect Cosmos"}),S.jsx(Qi,{onClick:P,title:"Close","aria-label":"Close",variant:"ghost",size:"icon-compact",children:S.jsx(Bb,{className:"h-4 w-4",weight:"bold"})})]}),S.jsxs("div",{className:"space-y-4 p-4",children:[S.jsx(gv,{className:"text-content-subtle text-sm",children:"Add public collections from a Cosmos profile to your design references."}),i?null:S.jsxs("form",{onSubmit:L=>void T(L),className:"space-y-4",children:[S.jsx("label",{className:"text-content block text-sm font-medium",htmlFor:"cosmos-profile-url",children:"Cosmos profile URL"}),S.jsx("input",{id:"cosmos-profile-url",type:"url",required:!0,autoFocus:!0,value:r,onChange:L=>s(L.target.value),placeholder:"https://www.cosmos.so/username",className:"border-main-border bg-main-input text-content placeholder:text-content-muted focus:border-secondary w-full rounded-md border px-3 py-2 text-sm outline-none"}),S.jsx("button",{type:"submit",disabled:_,className:"bg-secondary text-secondary-foreground hover:bg-accent rounded-md px-4 py-2 text-sm font-medium disabled:opacity-50",children:_?"Finding collections…":"Continue"})]}),i&&!h?S.jsxs("div",{className:"space-y-4",children:[S.jsxs("p",{className:"text-content text-sm font-medium",children:["Choose collections from"," ",i.profile.title||i.profile.username]}),S.jsx("div",{className:"border-main-border max-h-60 divide-y overflow-y-auto rounded-md border",children:i.collections.map(L=>S.jsxs("label",{className:"text-content hover:bg-main-light flex cursor-pointer items-center gap-3 px-3 py-2 text-sm",children:[S.jsx("input",{type:"checkbox",checked:l.includes(L.id),disabled:_,onChange:()=>R(L.id)}),S.jsx("span",{className:"min-w-0 flex-1 truncate",children:L.title}),S.jsx("span",{className:"text-content-muted text-xs",children:L.total??"—"})]},L.id))}),i.collections.length===0?S.jsx("p",{className:"text-content-muted text-sm",children:"No public collections found for this profile."}):null,S.jsxs("label",{className:"text-content flex items-center justify-between gap-3 text-sm",children:["Analysis runtime",S.jsxs("select",{value:d,disabled:_,onChange:L=>{const j=L.target.value;f(j),k==null||k.capture("visual_editor_cosmos_runtime_selected",{runtime:j})},className:"border-main-border bg-main-input rounded-md border px-2 py-1.5",children:[S.jsx("option",{value:"",disabled:!0,children:"Select a runtime"}),S.jsx("option",{value:"codex",children:"Codex"}),S.jsx("option",{value:"claude",children:"Claude"}),S.jsx("option",{value:"cursor",children:"Cursor"})]})]}),S.jsx("button",{type:"button",onClick:()=>void M(),disabled:_||l.length===0||!d,className:"bg-secondary text-secondary-foreground hover:bg-accent rounded-md px-4 py-2 text-sm font-medium disabled:opacity-50",children:_?"Preparing plan…":"Review import plan"}),S.jsx("button",{type:"button",onClick:()=>{k==null||k.capture("visual_editor_cosmos_profile_changed"),C()},disabled:_,className:"text-content-muted hover:text-content ml-3 text-sm",children:"Use another profile"})]}):null,h?S.jsxs("div",{className:"space-y-4 text-sm",children:[S.jsxs("p",{className:"text-content",children:[h.collectionCount," ",h.collectionCount===1?"collection":"collections"," ·"," ",h.referenceCount," ",h.referenceCount===1?"reference":"references"," ·"," ",h.imageCount," ",h.imageCount===1?"image":"images"]}),S.jsx("p",{className:"text-content-subtle",children:h.scopeDisclosure}),S.jsx("p",{className:"text-content-subtle",children:h.usageDisclosure}),S.jsxs("p",{className:"text-content-muted text-xs",children:[h.reusableCount," reusable · ",h.unsupportedCount," ","unsupported · runtime: ",d]}),S.jsx("button",{type:"button",onClick:()=>void I(),disabled:_,className:"bg-secondary text-secondary-foreground hover:bg-accent rounded-md px-4 py-2 text-sm font-medium disabled:opacity-50",children:_?"Starting import…":"Approve and import"}),S.jsx("button",{type:"button",onClick:()=>{k==null||k.capture("visual_editor_cosmos_plan_revised"),m(null)},disabled:_,className:"text-content-muted hover:text-content ml-3 text-sm",children:"Change selection"})]}):null,v?S.jsx("p",{role:"alert",className:"text-sm text-red-300",children:v}):null]})]})]})})},uA=Ls("ConnectorsModal"),mne=[{provider:"x",name:"X",iconClassName:"text-content",icon:S.jsx(oh,{provider:"x"})},{provider:"pinterest",name:"Pinterest",iconClassName:"text-[#e60023]",icon:S.jsx(oh,{provider:"pinterest"})},{provider:"arena",name:"Are.na",iconClassName:"text-content",icon:S.jsx(oh,{provider:"arena"})}],gne={name:"Cosmos",iconClassName:"text-content",icon:S.jsx(oh,{provider:"cosmos"})},dA=({meta:t,status:e,actionLabel:n,buttonLabel:r,isDisabled:s,isHighlighted:i,onAction:o})=>S.jsxs("li",{className:`flex min-h-[64px] items-center gap-3 py-3 ${i?"ring-secondary -mx-2 rounded-md px-2 ring-2":""}`,children:[S.jsx("span",{className:`grid h-7 w-7 flex-none place-items-center ${t.iconClassName}`,"aria-hidden":"true",children:t.icon}),S.jsxs("div",{className:"min-w-0 flex-1",children:[S.jsx("span",{className:"text-content block text-sm font-medium",children:t.name}),S.jsx("span",{className:"text-content-muted block truncate text-xs",children:e})]}),S.jsx("button",{type:"button","aria-label":n,onClick:o,disabled:s,className:"active-push bg-main-input text-content hover:bg-main-input/80 inline-flex min-h-8 w-24 flex-none items-center justify-center rounded-md px-3 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50",children:r})]}),ax=({isOpen:t,onClose:e,context:n="menu",highlightProvider:r=null})=>{var M;const{integrations:s,isLoading:i,error:o,pendingProvider:l,connect:u,disconnect:d}=nne(),f=si(),[h,m]=g.useState(null),[v,w]=g.useState(!1),_=rne(t),x=I=>s.find(R=>R.provider===I),b=g.useCallback(I=>{const R=Date.now(),L=$l({action:"connect",outcome:"started",provider:I,entryPoint:n});f==null||f.capture(L.event,L.properties),u(I).then(j=>{const F=Date.now()-R;if(j==="connected"){const q=$l({action:"connect",outcome:"completed",provider:I,entryPoint:n,durationMs:F});f==null||f.capture(q.event,q.properties);return}const N=$l({action:"connect",outcome:"failed",provider:I,entryPoint:n,durationMs:F,failureReason:j==="closed"?"popup_closed":"provider_failed"});f==null||f.capture(N.event,N.properties)}).catch(j=>{const F=Rr(j,"Could not connect."),N=$l({action:"connect",outcome:"failed",provider:I,entryPoint:n,durationMs:Date.now()-R,failureReason:F.includes("Popup blocked")?"popup_blocked":"request_failed"});f==null||f.capture(N.event,N.properties),uA.warn(`Connect error for ${I}:`,F),$t.error(F)})},[u,n,f]),k=g.useCallback(I=>{const R=Date.now(),L=$l({action:"disconnect",outcome:"started",provider:I,entryPoint:n});f==null||f.capture(L.event,L.properties),d(I).then(()=>{const j=$l({action:"disconnect",outcome:"completed",provider:I,entryPoint:n,durationMs:Date.now()-R});f==null||f.capture(j.event,j.properties)}).catch(j=>{const F=Rr(j,"Could not disconnect."),N=$l({action:"disconnect",outcome:"failed",provider:I,entryPoint:n,durationMs:Date.now()-R,failureReason:"request_failed"});f==null||f.capture(N.event,N.properties),uA.warn(`Disconnect error for ${I}:`,F),$t.error(F)})},[n,d,f]),C=n==="onboarding",P=(M=_.data)==null?void 0:M.sources.some(I=>I.provider==="cosmos");let T=P?"Connected":"Not connected";return _.isError&&(T="Status unavailable"),_.isPending&&(T="Checking status…"),S.jsxs(S.Fragment,{children:[S.jsx(dv,{open:t,onOpenChange:I=>!I&&e(),children:S.jsxs(fv,{children:[S.jsx(hv,{className:"z-max fixed inset-0 bg-black/40"}),S.jsx(pv,{ref:m,className:"z-max border-main-border bg-main font-main fixed top-1/2 left-1/2 w-[min(440px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 rounded-lg border shadow-2xl outline-none",children:S.jsxs(JO,{value:h,children:[S.jsxs("div",{className:"border-main-border bg-main-light flex items-center justify-between rounded-t-lg border-b px-4 py-2",children:[S.jsx(mv,{className:"text-content text-base font-medium",children:"Connect design references"}),S.jsx(Qi,{onClick:e,title:"Close","aria-label":"Close",variant:"ghost",size:"icon-compact",children:S.jsx(Bb,{className:"h-4 w-4",weight:"bold"})})]}),S.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[S.jsx(gv,{className:"text-content-subtle text-sm",children:"Connect your references to add them to your Rivet library. Rivet can use them to inspire new design directions."}),o?S.jsx("p",{className:"rounded-lg bg-red-500/10 px-4 py-3 text-[13px] font-medium text-red-300",children:o}):null,S.jsxs("ul",{className:"divide-main-border divide-y","aria-label":"Design reference services",children:[mne.map(I=>{const R=x(I.provider),L=(R==null?void 0:R.status)==="connected",j=R==null?void 0:R.externalUsername;let F=L?`Connected${j?` as @${j}`:""}`:"Not connected";i&&(F="Checking status…");const N=l===I.provider,q=L?"Disconnect":"Connect";return S.jsx(dA,{meta:I,status:F,actionLabel:`${q} ${I.name}`,buttonLabel:N?`${q}ing…`:q,isDisabled:i||N,isHighlighted:r===I.provider,onAction:()=>L?k(I.provider):b(I.provider)},I.provider)}),S.jsx(dA,{meta:gne,status:T,actionLabel:P?"Add Cosmos profile":"Connect Cosmos",buttonLabel:P?"Add profile":"Connect",isDisabled:!1,isHighlighted:!1,onAction:()=>{f==null||f.capture("visual_editor_cosmos_modal_opened"),w(!0)}})]}),C?S.jsxs("div",{className:"flex items-center justify-between gap-4",children:[S.jsx("p",{className:"text-content-subtle text-xs",children:"You can always do this later from the account menu."}),S.jsx("button",{type:"button",onClick:e,className:"active-push bg-secondary text-secondary-foreground hover:bg-accent flex-none rounded-lg px-3.5 py-2 text-[13px] font-medium transition-colors",children:"Skip for now"})]}):null]})]})})]})}),S.jsx(pne,{isOpen:v,onClose:()=>w(!1),onImported:()=>{_.refetch()}})]})},fA=({className:t=""})=>S.jsx("span",{"aria-hidden":"true",className:`rivet-skeleton block rounded ${t}`.trim()}),vne=Ls("SupportTicketModal"),hA=5e3,$_="feedback",yne=yn({error:Ke().optional(),details:rz([Ke(),yn({formErrors:Ec(Ke()).optional(),fieldErrors:BR(Ke(),Ec(Ke()).optional()).optional()})]).optional()}),_ne=t=>{var r;if(!t)return null;const e=(r=t.formErrors)==null?void 0:r[0];if(e)return e;const n=t.fieldErrors??{};for(const s of Object.values(n)){const i=s==null?void 0:s[0];if(i)return i}return null},wne=async t=>{let e;try{const n=yne.safeParse(await t.json());e=n.success?n.data:void 0}catch{e=void 0}if(t.status===400){if(typeof(e==null?void 0:e.details)=="string"&&e.details.trim())return e.details;if(typeof(e==null?void 0:e.details)=="object"&&e.details!==null){const n=_ne(e.details);if(n)return n}return"Please check your feedback and try again."}return t.status>=500?typeof(e==null?void 0:e.details)=="string"&&e.details.trim()?e.details:"Could not send feedback right now. Please try again later.":typeof(e==null?void 0:e.error)=="string"&&e.error.trim()?e.error:`HTTP ${t.status}`},xne=({isOpen:t,onClose:e,contactEmail:n})=>{const r=si(),[s,i]=g.useState(""),[o,l]=g.useState(!1),[u,d]=g.useState(null),f=g.useCallback(()=>{i("")},[]),h=g.useCallback(()=>{o||(f(),e())},[o,e,f]),m=g.useCallback(async()=>{const x=s.trim();if(!(!x||o)){l(!0);try{const b=typeof(r==null?void 0:r.get_session_id)=="function"?r.get_session_id():void 0,k=typeof(r==null?void 0:r.get_distinct_id)=="function"?r.get_distinct_id():void 0,C=n==null?void 0:n.trim(),P=await bt("/api/support/tickets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:$_,message:x,contactEmail:C||void 0,metadata:{posthogSessionId:b??void 0,posthogDistinctId:k??void 0,appVersion:"0.26.0",appEnvironment:"production",pageUrl:window.location.href,userAgent:navigator.userAgent,submittedAt:new Date().toISOString()}})});if(!P.ok){const T=await wne(P);throw new Error(T)}r==null||r.capture("support_ticket_submitted",{ticket_type:$_,has_posthog_session_id:!!b}),$t.success("Feedback sent",{description:"Thanks for sharing this."}),f(),e()}catch(b){const k=Rr(b,"Failed to send message");r==null||r.capture("support_ticket_submit_failed",{ticket_type:$_,error:k}),vne.error("Failed to submit support ticket:",k),$t.error("Could not send feedback",{description:k})}finally{l(!1)}}},[n,o,s,e,r,f]),v=g.useCallback(x=>{x.key==="Enter"&&(x.metaKey||x.ctrlKey)&&(x.preventDefault(),m())},[m]),w=hA-s.length,_=o||s.trim().length===0;return S.jsx(dv,{open:t,onOpenChange:x=>!x&&h(),children:S.jsxs(fv,{children:[S.jsx(hv,{className:"z-max fixed inset-0 bg-black/40"}),S.jsx(pv,{ref:d,className:"z-max border-main-border bg-main font-main fixed top-1/2 left-1/2 w-[440px] -translate-x-1/2 -translate-y-1/2 rounded-lg border shadow-2xl outline-none",children:S.jsxs(JO,{value:u,children:[S.jsxs("div",{className:"border-main-border bg-main-light flex items-center justify-between rounded-t-lg border-b px-4 py-2",children:[S.jsx(mv,{className:"text-content text-base font-medium",children:"Send feedback"}),S.jsx(Qi,{onClick:h,disabled:o,title:"Close","aria-label":"Close",variant:"ghost",size:"icon-compact",children:S.jsx(Bb,{className:"h-4 w-4",weight:"bold"})})]}),S.jsxs("div",{className:"flex flex-col gap-3 p-4",children:[S.jsx(gv,{className:"text-content-subtle text-sm",children:"Tell us what happened or what we can improve."}),S.jsxs("div",{className:"bg-main-input rounded-lg outline outline-1 outline-transparent transition-[outline-color] focus-within:outline-white/20",children:[S.jsx("textarea",{id:"support-ticket-message","aria-label":"Your feedback",value:s,onChange:x=>i(x.target.value),onKeyDown:v,maxLength:hA,rows:6,disabled:o,placeholder:"What happened?",className:"text-content placeholder-content-subtle max-h-64 w-full resize-none overflow-y-auto bg-transparent pt-3 pr-3 pb-1 pl-3 text-sm focus:outline-none disabled:opacity-50"}),S.jsxs("div",{className:"flex items-center justify-between px-3 pt-1 pb-3",children:[S.jsx("span",{className:"text-content-subtle text-xs",children:"Context details are included automatically."}),S.jsxs("div",{className:"flex items-center gap-2",children:[w<=500&&S.jsx("span",{className:"text-content-subtle text-xs",children:w}),S.jsx(Qi,{onClick:m,disabled:_,title:"Send feedback",shortcut:"⌘↵","aria-label":"Send feedback",size:"icon-compact",children:o?S.jsx(tv,{className:"h-5 w-5 animate-spin",weight:"bold"}):S.jsx(iY,{className:"h-5 w-5",weight:"bold"})})]})]})]})]})]})})]})})},bne=Ls("ProfileAvatar"),X9=(t,e)=>{const n=(t??"").trim();if(n)return n.split(/\s+/).filter(Boolean)[0]??"";const s=((e??"").split("@")[0]??"").split(/[._\-+]/).filter(Boolean)[0]??"";return s?s[0].toUpperCase()+s.slice(1):""},Sne=(t,e)=>X9(t,e).charAt(0).toUpperCase(),kne=({className:t="",side:e="bottom",align:n="end"})=>{var q,W,Y;const r=$te(),s=((q=r.data)==null?void 0:q.name)??null,i=((W=r.data)==null?void 0:W.email)??null,o=((Y=r.data)==null?void 0:Y.isAuthenticated)===!0,l=si(),{startLogin:u,isStartingLogin:d,loginError:f}=G9("account_menu"),[h,m]=g.useState(!1),[v,w]=g.useState(!1),[_,x]=g.useState(!1),[b,k]=g.useState(!1),{containerRef:C,onKeyDown:P,onCloseAutoFocus:T}=_9({onDismiss:()=>N(!1)}),M=Sne(s,i);if(r.isPending)return S.jsxs("span",{"data-testid":"profile-avatar-skeleton","aria-hidden":"true",className:`flex shrink-0 items-center gap-2 ${t}`.trim(),children:[S.jsx(fA,{className:"h-8 w-8 rounded-full"}),S.jsx(fA,{className:"h-3.5 w-16"})]});const I=X9(s,i),R=(s==null?void 0:s.trim())||null,L=(i==null?void 0:i.trim())||null,j=async()=>{k(!0);try{const H=await bt("/api/auth/logout",{method:"POST",credentials:"same-origin"});if(!H.ok)throw new Error(`Logout failed: ${H.status}`);window.location.pathname.startsWith("/rivet/library")&&ZR()}catch(H){bne.warn("Logout request failed",H),$t.error("Could not log out. Please try again."),k(!1);return}window.location.reload()};let F="Log in";o&&(F=I||"Account"),r.error&&!r.data&&(F="Account unavailable");const N=H=>{m(H),l==null||l.capture(`visual_editor_account_menu_${H?"opened":"closed"}`,{is_authenticated:o})};return S.jsxs(S.Fragment,{children:[S.jsxs(yS,{open:h,onOpenChange:N,children:[S.jsx(_S,{asChild:!0,children:S.jsxs("button",{type:"button","aria-label":"Account","data-rivet-private":!0,className:`ph-no-capture text-content-muted hover:text-content flex shrink-0 items-center gap-2 transition-colors select-none ${t}`,children:[S.jsx("span",{className:"border-main-border bg-main-input flex h-8 w-8 items-center justify-center rounded-full border text-xs leading-none font-semibold",children:M||S.jsx(yY,{className:"h-4 w-4",weight:"bold"})}),S.jsx("span",{className:"max-w-[8rem] truncate text-sm font-medium",children:F})]})}),S.jsx(wS,{children:S.jsxs(xS,{"data-rivet-private":!0,ref:C,onKeyDown:P,onCloseAutoFocus:T,role:"menu",className:"ph-no-capture bg-popover shadow-surface-4 z-[60] min-w-[180px] rounded-lg p-1",side:e,sideOffset:6,align:n,children:[R||L?S.jsxs("div",{className:"border-main-border border-b px-3 py-2",children:[R?S.jsx("div",{className:"text-content truncate text-sm font-medium",children:R}):null,L?S.jsx("div",{className:"text-content-muted truncate text-xs",children:L}):null]}):null,S.jsxs("button",{type:"button",role:"menuitem","data-menu-item":!0,onClick:()=>{N(!1),w(!0)},disabled:!o,className:"text-content hover:bg-hover focus-visible:bg-hover mt-1 flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors focus:outline-none disabled:cursor-not-allowed disabled:opacity-50",children:[S.jsx(w3,{className:"h-4 w-4",weight:"bold"}),"Connect design references"]}),S.jsxs("button",{type:"button",role:"menuitem","data-menu-item":!0,onClick:()=>{N(!1),x(!0)},className:"text-content hover:bg-hover focus-visible:bg-hover mt-1 flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors focus:outline-none",children:[S.jsx(lY,{className:"h-4 w-4",weight:"bold"}),"Share feedback"]}),o?S.jsxs("button",{type:"button",role:"menuitem","data-menu-item":!0,onClick:j,disabled:b,className:"text-content hover:bg-hover focus-visible:bg-hover mt-1 flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors focus:outline-none disabled:cursor-not-allowed disabled:opacity-50",children:[S.jsx(gY,{className:"h-4 w-4",weight:"bold"}),b?"Logging out…":"Log out"]}):null,!o&&!r.error?S.jsxs("button",{type:"button",role:"menuitem","data-menu-item":!0,onClick:()=>{u()},disabled:d,className:"text-content hover:bg-hover focus-visible:bg-hover mt-1 flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-sm focus:outline-none disabled:opacity-50",children:[S.jsx(mY,{className:"h-4 w-4",weight:"bold"}),d?"Logging in…":"Log in"]}):null,r.error?S.jsx("button",{type:"button",role:"menuitem","data-menu-item":!0,onClick:()=>{r.refetch()},className:"text-content mt-1 px-3 py-1.5 text-sm",children:"Retry account"}):null,f?S.jsx("p",{role:"alert",className:"max-w-64 px-3 py-2 text-sm text-red-300",children:f}):null]})})]}),v?S.jsx(ax,{isOpen:!0,onClose:()=>w(!1)}):null,S.jsx(xne,{isOpen:_,onClose:()=>x(!1),contactEmail:i??void 0})]})},Ene=({onClose:t,libraryOrigin:e})=>S.jsxs("div",{className:"bg-main font-main scrollbar-hide relative flex h-full w-full cursor-auto flex-col overflow-hidden shadow-2xl","data-cy":"element-inspector",children:[S.jsx(Dte,{onClose:t,libraryOrigin:e}),S.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:S.jsx(_te,{})}),S.jsx("div",{className:"border-main-border bg-main-light flex flex-shrink-0 items-center border-t px-2.5 py-2.5",children:S.jsx(kne,{side:"top",align:"start"})})]});async function Cne(t,e){const{delaysMs:n,shouldRetry:r,onRetry:s}=e;for(let i=1;;i++)try{return await t(i)}catch(o){const l=n[i-1];if(l===void 0||r&&!r(o))throw o;s==null||s(o,i,l),await new Promise(u=>setTimeout(u,l))}}const pA=Ls("useServerConfig"),Q9=[250,500,1e3,2e3,4e3],mA=Q9.length+1,Pne=async()=>{var n;const t=await bt("/api/health");if(!t.ok)throw new Error(`Failed to fetch config: ${t.status}`);const e=await t.json();if(!e.framework)throw new Error("Server did not return framework information");return{userPort:((n=e.ports)==null?void 0:n.userDevServer)||3e3,framework:e.framework}},Ane=()=>{const[t,e]=g.useState(null),[n,r]=g.useState(!0),[s,i]=g.useState(null),o=g.useCallback(async()=>{try{r(!0),i(null);const l=await Cne(Pne,{delaysMs:Q9,onRetry:(u,d,f)=>{pA.warn(`Server config fetch failed (attempt ${d}); retrying in ${f}ms`,u)}});return e(l),l}catch(l){throw i(Rr(l,"Failed to fetch server config")),pA.warn("Error fetching server config:",l),l}finally{r(!1)}},[]);return{config:t,fetchConfig:o,isLoading:n,error:s}},Tne="#1C1C20",Co=[118,118,124],gA=.85,Rne=3,Ine=.15,q0=36,Mne=4.4,One=.7,Lne=3.5,Nne=.8,vA=9,Dne=11,jne=[1.35,1.12,.95,.85],$ne=[0,1.1,2.3,3.1],Fne=[0,.35,.16,.13],Vne=[.9,.5,.4,.35],Fl=3,F_=[[{x1:.1,y1:.08,x2:.9,y2:.92,level:0},{x1:.14,y1:.13,x2:.86,y2:.23,level:1},{x1:.14,y1:.28,x2:.3,y2:.87,level:1},{x1:.34,y1:.28,x2:.86,y2:.87,level:1},{x1:.165,y1:.155,x2:.225,y2:.205,level:2},{x1:.7,y1:.155,x2:.755,y2:.205,level:2},{x1:.775,y1:.155,x2:.83,y2:.205,level:2},{x1:.165,y1:.32,x2:.275,y2:.375,level:2},{x1:.165,y1:.415,x2:.275,y2:.47,level:2},{x1:.165,y1:.51,x2:.275,y2:.565,level:2},{x1:.37,y1:.32,x2:.585,y2:.56,level:2},{x1:.615,y1:.32,x2:.83,y2:.56,level:2},{x1:.37,y1:.61,x2:.83,y2:.83,level:2},{hline:!0,x1:.39,x2:.81,y:.685,level:3},{hline:!0,x1:.39,x2:.75,y:.755,level:3}],[{x1:.1,y1:.08,x2:.9,y2:.92,level:0},{x1:.16,y1:.17,x2:.52,y2:.45,level:1},{x1:.58,y1:.17,x2:.685,y2:.29,level:1},{x1:.715,y1:.17,x2:.84,y2:.29,level:1},{x1:.58,y1:.33,x2:.685,y2:.45,level:1},{x1:.715,y1:.33,x2:.84,y2:.45,level:1},{x1:.16,y1:.55,x2:.84,y2:.85,level:1},{x1:.19,y1:.21,x2:.36,y2:.33,level:2},{hline:!0,x1:.19,x2:.48,y:.37,level:3},{hline:!0,x1:.19,x2:.42,y:.42,level:3},{x1:.19,y1:.6,x2:.49,y2:.8,level:2},{hline:!0,x1:.53,x2:.8,y:.63,level:3},{hline:!0,x1:.53,x2:.76,y:.7,level:3},{hline:!0,x1:.53,x2:.79,y:.77,level:3}],[{x1:.1,y1:.08,x2:.9,y2:.92,level:0},{x1:.14,y1:.13,x2:.86,y2:.22,level:1},{x1:.14,y1:.28,x2:.36,y2:.87,level:1},{x1:.39,y1:.28,x2:.61,y2:.87,level:1},{x1:.64,y1:.28,x2:.86,y2:.87,level:1},{x1:.165,y1:.15,x2:.225,y2:.2,level:2},{x1:.165,y1:.32,x2:.335,y2:.52,level:2},{x1:.415,y1:.32,x2:.585,y2:.52,level:2},{x1:.665,y1:.32,x2:.835,y2:.52,level:2},{hline:!0,x1:.165,x2:.335,y:.6,level:3},{hline:!0,x1:.165,x2:.3,y:.67,level:3},{hline:!0,x1:.415,x2:.585,y:.6,level:3},{hline:!0,x1:.415,x2:.55,y:.67,level:3},{hline:!0,x1:.665,x2:.835,y:.6,level:3},{hline:!0,x1:.665,x2:.8,y:.67,level:3}],[{x1:.1,y1:.08,x2:.9,y2:.92,level:0},{x1:.3,y1:.22,x2:.7,y2:.74,level:1},{x1:.34,y1:.27,x2:.55,y2:.34,level:2},{hline:!0,x1:.36,x2:.64,y:.42,level:3},{hline:!0,x1:.36,x2:.6,y:.49,level:3},{hline:!0,x1:.36,x2:.62,y:.56,level:3},{x1:.5,y1:.63,x2:.575,y2:.69,level:2},{x1:.595,y1:.63,x2:.66,y2:.69,level:2}]],G0=t=>{let e=t|0;return e=Math.imul(e^e>>>16,73244475),e=Math.imul(e^e>>>16,73244475),e^=e>>>16,(e>>>0)/4294967296},km=t=>{const e=Math.min(1,Math.max(0,t));return e*e*(3-2*e)},Vl=(t,e)=>(Math.round(t/e-.5)+.5)*e,Hne=Math.sin(Math.PI/3),yA=(t,e,n,r,s)=>{if(t.beginPath(),e===0)t.arc(n,r,s,0,Math.PI*2);else if(e===1){const i=s*Hne;t.moveTo(n,r-s),t.lineTo(n+i,r+s/2),t.lineTo(n-i,r+s/2),t.closePath()}else{const i=s*.85;t.rect(n-i,r-i,i*2,i*2)}t.fill()},zne=(t,e,n)=>{let r;if(n.hline){const s=Math.max(n.x1-t,t-n.x2,0),i=Math.abs(e-n.y1);r=Math.hypot(s,i)-vA}else{const s=Math.max(n.x1-t,t-n.x2,0),i=Math.max(n.y1-e,e-n.y2,0);s===0&&i===0?r=-Math.min(t-n.x1,n.x2-t,e-n.y1,n.y2-e):r=Math.hypot(s,i),r=Math.abs(r)-vA}return km(.5-r/(2*Dne))},J9=({className:t="",trackGlobalLoaderCount:e=!0})=>{const n=yt(S9),r=g.useRef(null),s=g.useCallback(i=>{var j;if((j=r.current)==null||j.call(r),r.current=null,!i)return;const o=i.getContext("2d");if(!o)return;e&&n(F=>F+1);const l=window.matchMedia("(prefers-reduced-motion: reduce)").matches;let u=[],d=0,f=0,h=q0,m=q0,v=null,w=null,_=0,x=-1;const b=new Array(33),k=F=>{const N=Math.round(F*32);let q=b[N];if(!q){const W=N/32,Y=Math.round(Co[0]+(255-Co[0])*W),H=Math.round(Co[1]+(255-Co[1])*W),J=Math.round(Co[2]+(255-Co[2])*W);q=`rgba(${Y}, ${H}, ${J}, ${gA})`,b[N]=q}return q},C=F=>{const N=1-.35*F,q=Math.round(Co[0]*N),W=Math.round(Co[1]*N),Y=Math.round(Co[2]*N);return`rgba(${q}, ${W}, ${Y}, ${gA})`},P=F=>{let N=Math.floor(Math.random()*F_.length);N===x&&(N=(N+1)%F_.length),x=N;const q=[0,0,0,0],W=F_[N].map((D,G)=>{const le=D.level,re=q[le]++,ie=$ne[le]+re*Fne[le],ue=Vne[le]+G0(N*131+G*17+5)*.2;if(D.hline){const ne=Vl((D.y??0)*f,m);return{hline:!0,x1:Vl(D.x1*d,h),x2:Vl(D.x2*d,h),y1:ne,y2:ne,level:le,start:ie,dur:ue}}const fe=Vl(D.x1*d,h),de=Vl((D.y1??0)*f,m);return{hline:!1,x1:fe,y1:de,x2:Math.max(Vl(D.x2*d,h),fe+h),y2:Math.max(Vl((D.y2??0)*f,m),de+m),level:le,start:ie,dur:ue}}),Y=W.reduce((D,G)=>Math.max(D,G.start+G.dur),0),H=u.length,J=new Float32Array(H*Fl),B=new Int16Array(H*Fl).fill(-1),Q=new Uint8Array(H),V=W[0];for(let D=0;D<H;D++){const G=u[D];G.x>V.x1&&G.x<V.x2&&G.y>V.y1&&G.y<V.y2&&(Q[D]=1);const le=D*Fl;for(let re=0;re<W.length;re++){const ie=zne(G.x,G.y,W[re]);if(ie<=.02)continue;let ue=le;for(let fe=le;fe<le+Fl;fe++){if(B[fe]===-1){ue=fe;break}J[fe]<J[ue]&&(ue=fe)}(B[ue]===-1||ie>J[ue])&&(J[ue]=ie,B[ue]=re)}}return{startT:F,buildEnd:Y,els:W,frame:V,cellQ:J,cellEl:B,inFrame:Q}},T=()=>{const F=i.getBoundingClientRect();d=Math.max(1,F.width),f=Math.max(1,F.height);const N=Math.min(2,window.devicePixelRatio||1);i.width=Math.round(d*N),i.height=Math.round(f*N),o.setTransform(N,0,0,N,0,0);const q=Math.max(8,Math.round(d/q0)),W=Math.max(6,Math.round(f/q0));h=d/q,m=f/W,u=[];for(let Y=0;Y<W;Y++){const H=W>1?Y/(W-1):.5,J=Mne*(1+One*.4*(H*2-1));for(let B=0;B<q;B++){const Q=Y*8191+B*131+1,V={x:(B+.5)*h,y:(Y+.5)*m,size:J,seed:Q,phase:G0(Q),kind:0};V.kind=Math.floor(G0(Q*97)*3),u.push(V)}}w=null,v=null},M=new Float32Array(32),I=F=>{o.fillStyle=Tne,o.fillRect(0,0,d,f),v||(v=P(F+.2)),F>=v.startT+v.buildEnd+Lne&&(w=v,_=F,v=P(F+.2));let N=0;w&&(N=1-km((F-_)/Nne),N<=0&&(w=null));const q=v;for(let V=0;V<q.els.length;V++){const D=q.els[V];M[V]=km(Math.min(1,Math.max(0,(F-q.startT-D.start)/D.dur)))}const W=M[0],Y=C(0),H=C(W),J=N>0?C(N):Y,B=N>0?C(Math.max(W,N)):H,Q=u.length;for(let V=0;V<Q;V++){const D=u[V];let G=0,le=0;const re=V*Fl;for(let De=re;De<re+Fl;De++){const Ee=q.cellEl[De];if(Ee<0)break;const ft=q.cellQ[De]*M[Ee];ft>G&&(G=ft,le=q.els[Ee].level)}if(w)for(let De=re;De<re+Fl;De++){const Ee=w.cellEl[De];if(Ee<0)break;const ft=w.cellQ[De]*N;ft>G&&(G=ft,le=w.els[Ee].level)}const ie=F/Rne+D.phase,ue=Math.floor(ie),fe=ie-ue,de=km(Math.min(fe,1-fe)/Ine),ne=Math.floor(G0(D.seed*97+ue*7919)*3);ne!==D.kind&&G<.02&&de<.05&&(D.kind=ne);const Ce=Math.max(de*(1-G),G);if(!(Ce<.01))if(G<.02){const De=q.inFrame[V]===1,Ee=w?w.inFrame[V]===1:!1;De?o.fillStyle=Ee?B:H:o.fillStyle=Ee?J:Y;const ft=Math.max(De?W:0,Ee?N:0);yA(o,D.kind,D.x,D.y,D.size*Ce*(1-.2*ft))}else{o.fillStyle=k(G);const De=1+(jne[le]-1)*G;yA(o,D.kind,D.x,D.y,D.size*Ce*De)}}};T();let R=0;if(l)v=P(-100),I(0);else{const F=performance.now(),N=q=>{I((q-F)/1e3),R=requestAnimationFrame(N)};R=requestAnimationFrame(N)}const L=new ResizeObserver(()=>{T(),l&&(v=P(-100),I(0))});L.observe(i),r.current=()=>{cancelAnimationFrame(R),L.disconnect(),e&&n(F=>F-1)}},[e,n]);return S.jsx("canvas",{ref:s,"aria-hidden":"true",className:`h-full w-full ${t}`.trim()})},_A={kind:"base"};function wA(t){return t.kind==="base"?"base":`variant:${t.sessionId}:${t.variantId}`}const Une=async(t=null)=>{if(t)return Bne(t);let e;try{e=await bt("/api/mcp/status")}catch{return{isOk:!1,unavailableReason:"rivet_unreachable",upstreamStatus:null}}if(e.status===404||!(e.headers.get("content-type")??"").toLowerCase().includes("application/json"))return K0();if(!e.ok)return{isOk:!1,unavailableReason:"rivet_unreachable",upstreamStatus:null};let r;try{r=await e.json()}catch{return K0()}const s=r.devServerHealth;return s?s.ownership==="none"?{isOk:!1,unavailableReason:"upstream_unreachable",upstreamStatus:null}:s.isReachable===!0?{isOk:!0,unavailableReason:"upstream_unreachable",upstreamStatus:null}:{isOk:!1,unavailableReason:s.reason==="rivet_unreachable"?"rivet_unreachable":"upstream_unreachable",upstreamStatus:null}:K0()},eL=async t=>{try{const e=await fetch(t);return{isOk:e.status!==502&&e.status!==503,unavailableReason:"upstream_unreachable",upstreamStatus:e.status}}catch{return{isOk:!1,unavailableReason:"rivet_unreachable",upstreamStatus:null}}},Bne=t=>eL(t),K0=()=>eL("/"),V_=Ls("usePreviewUpstreamHealth"),Wne=500,Zne=4e3,qne=15e3,Gne=3,Kne=(t,e={})=>{const n=g.useRef(null),r=g.useRef(null),s=e.probeMsWhileDown??Wne,i=e.probeMsWhileUp??Zne,o=e.firstUnreachableCaptureAfterMs??qne,l=e.rerunProbeImmediatelyOnVersion,u=e.probePath??null,d=e.skip??!1,f=g.useRef(e.onPersistentUpstreamServerErrors);f.current=e.onPersistentUpstreamServerErrors;const[h,m]=g.useState(t==="static"),[v,w]=g.useState(0),[_,x]=g.useState(null),[b,k]=g.useState(0),[C,P]=g.useState(!1),[T,M]=g.useState(!1),[I,R]=g.useState(t==="static"?null:"upstream_unreachable");return g.useEffect(()=>{if(t==="static"){m(!0),x(null),k(0),P(!1),M(!0),R(null);return}if(d){m(!1),x(null),k(0),P(!1),M(!0),R("upstream_unreachable"),n.current=null;return}let L=!0;const j=Date.now();x(j),k(0),P(!1),m(!1),M(!1),R("upstream_unreachable");const F={current:!1},N={current:!1},q={current:!1},W={current:null},Y={current:!1},H={current:!1},J={current:0},B={current:!1},Q={current:null};let V=null;const D=()=>{q.current||(q.current=!0,L&&M(!0))},G=()=>{V!==null&&(clearTimeout(V),V=null)},le=(ie,ue)=>{G(),V=setTimeout(ue,ie)},re=async()=>{var ft;if(!L)return;k(At=>At+1);const{isOk:ie,unavailableReason:ue,upstreamStatus:fe}=await Une(u);if(!L)return;D(),Q.current=fe;const de=ie&&fe!==null&&fe>=500;de&&H.current?J.current+=1:ie&&!de&&(J.current=0);const ne=J.current>=Gne;if(ne&&!B.current&&fe!==null&&(B.current=!0,$e==null||$e.capture("preview_upstream_error_responses",{framework:t,upstream_status:fe,consecutive_count:J.current}),V_.warn(`Preview upstream is listening but has served ${J.current} consecutive ${fe} responses`),(ft=f.current)==null||ft.call(f,{upstreamStatus:fe,consecutiveCount:J.current})),ie&&!ne){de||(H.current=!0,B.current=!1);const At=!Y.current;Y.current=!0,m(!0),R(null),W.current=null,N.current=!1,P(!1),F.current?At&&($e==null||$e.capture("preview_upstream_restored",{framework:t})):(F.current=!0,$e==null||$e.capture("preview_dev_server_ready",{framework:t,ready_after_ms:Date.now()-j})),le(i,re);return}const De=Y.current;Y.current=!1,m(!1),R(ue),W.current===null&&(W.current=Date.now(),N.current=!1,P(!1)),De&&($e==null||$e.capture("preview_upstream_lost",{framework:t,upstream_status:fe}),w(At=>At+1),V_.warn("Preview upstream became unavailable after it was ready"));const Ee=Date.now()-W.current;Ee>=o&&!N.current&&(N.current=!0,P(!0),$e==null||$e.capture("preview_dev_server_unreachable",{framework:t,elapsed_ms:Ee,upstream_status:Q.current}),V_.warn("Dev server did not become ready within timeout window")),le(s,re)};return n.current=()=>le(0,re),le(0,re),()=>{L=!1,n.current=null,G()}},[t,s,i,o,u,d]),g.useEffect(()=>{var j;if(t==="static"||l===void 0)return;const L=r.current;r.current=l,L!==null&&L!==l&&((j=n.current)==null||j.call(n))},[t,l]),{isUpstreamReady:h,iframeRemountKey:v,probeStartedAt:_,probeAttemptCount:b,isFirstUnreachableWindowExceeded:C,initialProbeComplete:T,unavailableReason:I}};function Yne(t){return t.enteringSplit&&t.isExistingSession&&t.hasActiveVariantProxy}const tL=t=>{var r;if(typeof window>"u")return"";const e=(r=window.__RIVET_BOOTSTRAP__)==null?void 0:r.previewOrigin;if(e)return e;const n=new URL(window.location.origin);return n.hostname="localhost",n.origin},lx=({agentApplyMode:t,url:e})=>e.startsWith("/")?`${tL()}${e}`:e,Xne="allow-scripts allow-same-origin allow-forms allow-popups allow-modals",Qne=t=>Xne,Jne=Ls("PreviewSurface"),Rf=(t,e)=>t==="about:blank"?"blank":t.includes("/api/variants/")?"static_artifact":e.kind==="variant"?"dev_server":"original",cx=({target:t,src:e,framework:n,remountKey:r,isActive:s=!0})=>{dt(wv);const i=si(),o=g.useRef(!1),l=g.useRef(s),u=g.useCallback(f=>{t.kind==="variant"&&(i==null||i.capture("variants_panel.preview_displayed",{sessionId:t.sessionId,variantId:t.variantId,renderedTarget:"variant",iframeSrcKind:Rf(e,t),framework:n,isReused:f}))},[n,i,e,t]),d=g.useCallback(f=>{f&&(s&&!l.current&&o.current&&u(!0),l.current=s)},[u,s]);return S.jsx("div",{ref:d,className:"relative h-full w-full",children:S.jsx("iframe",{src:e,className:"h-full w-full border-none",title:s?"Project Preview":"Retained Project Preview",tabIndex:s?void 0:-1,sandbox:Qne(),onLoad:()=>{o.current=!0,i==null||i.capture("preview_iframe_loaded",{framework:n,src_kind:Rf(e,t)}),s&&u(!1)},onError:()=>{i==null||i.capture("preview_iframe_load_failed",{framework:n,src_kind:Rf(e,t)}),s&&t.kind==="variant"&&(i==null||i.capture("variants_panel.preview_display_failed",{sessionId:t.sessionId,variantId:t.variantId,renderedTarget:"variant",iframeSrcKind:Rf(e,t),framework:n})),Jne.warn("Preview iframe failed to load",{framework:n,src_kind:Rf(e,t)})}},r)})},ere=7,tre=t=>{const e=wA(t.target),n=`${e}:${t.src}`,r=t.src==="about:blank",[s,i]=g.useState(()=>({selectedKey:n,remountKey:t.remountKey,selection:0,frames:r?[]:[{key:n,props:t,lastSelected:0}]}));if(s.selectedKey!==n||s.remountKey!==t.remountKey){const o=s.selection+1,l=s.remountKey!==t.remountKey;let u=s.frames.filter(d=>!l||wA(d.props.target)!==e);if(!r){const d=u.find(f=>f.key===n);if(d?u=u.map(f=>f===d?{...f,lastSelected:o}:f):u=[...u,{key:n,props:t,lastSelected:o}],u.length>ere){const f=u.reduce((h,m)=>m.lastSelected<h.lastSelected?m:h);u=u.filter(h=>h!==f)}}i({selectedKey:n,remountKey:t.remountKey,selection:o,frames:u})}return S.jsxs("div",{className:"relative h-full w-full",children:[s.frames.map(o=>{const l=!r&&o.key===n;return S.jsx("div",{className:"absolute inset-0",style:{visibility:l?"visible":"hidden",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:S.jsx(cx,{...o.props,isActive:l})},`${o.key}:${o.props.remountKey??""}`)}),r?S.jsx(cx,{...t}):null]})},nre=g.lazy(()=>h5(()=>Promise.resolve().then(()=>jse),void 0)),rre={surface:"relative flex h-full w-full items-center justify-center bg-main px-6",overlay:"absolute inset-0 z-10 flex items-center justify-center bg-main/90 px-6",page:"relative flex h-screen w-full items-center justify-center bg-main px-6"},sre={sm:"text-lg font-semibold text-content",md:"text-2xl font-semibold text-content",lg:"text-3xl font-semibold text-content"},ire={neutral:"rounded-md border border-divider bg-transparent px-5 py-2 text-sm font-medium text-content transition-colors hover:bg-surface-3",ghost:"rounded-md px-5 py-2 text-sm font-medium text-content-muted transition-colors hover:text-content"},mc=({backdrop:t,media:e,title:n,description:r,actions:s,tone:i="neutral",fill:o="surface",size:l="md",children:u,state:d,role:f="status",busy:h=!1,className:m=""})=>{const v=g.useCallback(_=>{_&&d&&($e==null||$e.capture("status_surface_shown",{state:d,tone:i,fill:o}))},[d,i,o]),w=!!(e||n||r||u||s!=null&&s.length);return S.jsxs("div",{ref:v,className:`${rre[o]} ${m}`.trim(),role:f,"aria-live":"polite","aria-busy":h||void 0,"data-state":d,children:[t?S.jsx("div",{className:"absolute inset-0",children:t}):null,w?S.jsxs("div",{className:"relative z-10 flex max-w-sm flex-col items-center gap-5 text-center",children:[e,n?S.jsx("h2",{className:sre[l],children:n}):null,r?S.jsx("p",{className:"text-content-muted text-base leading-relaxed",children:r}):null,u,s!=null&&s.length?S.jsx("div",{className:"flex flex-row items-center gap-3",children:s.map(_=>S.jsx("button",{type:"button",onClick:_.onClick,className:ire[_.variant??"neutral"],children:_.label},_.label))}):null]}):null]})},ux=({loader:t="coalesce",trackGlobalLoaderCount:e,size:n="lg",...r})=>t==="coalesce"?S.jsx(mc,{...r,size:n,busy:!0,backdrop:S.jsx(J9,{trackGlobalLoaderCount:e})}):t==="logo"?S.jsx(mc,{...r,size:n,busy:!0,backdrop:S.jsx(g.Suspense,{fallback:null,children:S.jsx(nre,{className:"absolute inset-0"})})}):S.jsx(mc,{...r,size:n,busy:!0,media:S.jsx(tv,{"aria-hidden":!0,className:"text-content h-8 w-8 shrink-0 animate-spin",weight:"bold"})}),nL=({icon:t,...e})=>S.jsx(mc,{...e,tone:"neutral",media:t?S.jsx("div",{className:"text-content-muted",children:t}):void 0}),CS=t=>S.jsx(mc,{...t,tone:"error",role:"alert"}),xA="/static/",ore=t=>{try{return new URL(t,"http://localhost").pathname.endsWith(xA)}catch{return t.endsWith(xA)}},are=t=>t==="spawn_error"?"The direction is saved, but its preview process didn’t start.":t==="exited"?"The direction is saved, but its preview stopped before it was ready.":t==="timeout"?"The direction is saved, but its preview took too long to become ready.":t==="dependency_install_failed"?"The direction is saved, but its dependencies couldn’t be prepared. Fix the installation error, then retry the preview.":t==="compile_error"?"The direction is saved, but its app couldn’t compile. Fix the app error, then retry the preview.":t==="missing_dev_script"?"The direction is saved, but Rivet couldn’t find a dev script to preview it.":t==="missing_static_entry"?"The direction is saved, but Rivet couldn’t find an HTML entry to preview it.":"The direction is saved, but Rivet couldn’t prepare its preview.",lre=t=>{if(t.status==="failed"&&t.errorCode==="VARIANT_VERIFICATION_UNAVAILABLE")return{state:"variant_verification_unavailable",title:"Rivet couldn’t verify this direction",description:"The worker completed, but Rivet couldn’t inspect its generated files.",detail:t.errorMessage??t.errorCode,isError:!0};if(t.status==="failed"&&t.errorCode==="VARIANT_QA_FAILED")return{state:"variant_output_integrity_failed",title:"This direction couldn’t be verified",description:"The worker completed, but Rivet found a structural problem in the generated files.",detail:t.errorMessage??t.errorCode,isError:!0};if(t.status==="failed")return{state:"variant_worker_failed",title:"This direction didn’t complete",description:"The worker stopped before producing a usable result.",detail:t.errorMessage??t.errorCode,isError:!0};if(t.status==="cancelled")return{state:"variant_cancelled",title:"Direction was cancelled",description:"Rivet stopped before a preview was ready. Your other directions are unchanged.",isError:!1};if(t.status==="succeeded"&&t.previewUnavailable&&t.previewUnavailable.reason!=="idle_timeout"){const e=t.previewUnavailable.portInUse?"The preview port was already in use.":void 0;return{state:"preview_unavailable",title:"Rivet couldn’t preview this direction",description:are(t.previewUnavailable.reason),detail:t.previewUnavailable.detail??e,isError:!0}}return null},cre=({issue:t,retryTarget:e})=>{const n=si(),r=g.useRef(!1),[s,i]=g.useState(!1),[o,l]=g.useState(null),u=async()=>{if(!(!e||r.current)){r.current=!0,i(!0),l(null),n==null||n.capture("preview_retry_clicked",{session_id:e.sessionId,variant_id:e.variantId});try{const d=await bt(`/api/variants/${encodeURIComponent(e.sessionId)}/preview-port`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({variantId:e.variantId,retry:!0})});if(!d.ok){const f=yn({message:Ke().optional()}).safeParse(await d.json().catch(()=>({}))),h=f.success?f.data:{};throw new Error(h.message??"The preview could not restart. Try again.")}}catch(d){l(Rr(d,"The preview could not restart. Try again."))}finally{r.current=!1,i(!1)}}};return S.jsxs(mc,{fill:"overlay",size:"sm",state:t.state,role:t.isError?"alert":"status",tone:t.isError?"error":"neutral",title:t.title,description:t.description,busy:s,actions:e&&!s?[{label:"Retry preview",onClick:()=>void u()}]:void 0,children:[s?S.jsx("p",{className:"text-content-subtle text-xs",children:"Starting preview…"}):null,o?S.jsx("p",{className:"text-content-subtle text-xs",children:o}):null,t.detail?S.jsx("p",{"data-rivet-private":!0,className:"ph-no-capture text-content-subtle max-h-40 overflow-auto text-xs leading-relaxed break-words whitespace-pre-wrap",children:t.detail}):null]})},ure=({isInteractionDisabled:t=!1,framework:e,userPort:n})=>{var sn;const r=dt(yv),s=dt(Xw),i=yt(Xw),o=dt(Tg),l=yt(Tg),u=dt(op),d=dt(wv),f=dt(Qw),h=dt(Jw),m=dt(k9),v=dt(E9),w=yt(Jw),_=dt(rl),x=dt(Sm),b=yt(Qw),k=u.active&&u.projectContext.kind==="fresh",C=dt(ex),P=u.active?u.variants.find(Re=>Re.workItemId===C&&(Re.status==="pending"||Re.status==="running"||Re.status==="succeeded"&&!Re.preview&&typeof Re.port!="number"&&(!Re.previewUnavailable||Re.previewUnavailable.reason==="idle_timeout")))??null:null,T=u.active&&u.variants.some(Re=>Re.status==="pending"||Re.status==="running"),M=k||T,I=u.active?u.variants.find(Re=>Re.workItemId===C)??null:null,R=I?lre(I):null,L=e==="static"&&o!==null&&ore(o);g.useEffect(()=>{u.active||b(!1)},[u.active,b]);const j=g.useRef(!1);g.useEffect(()=>{const Re=!!(_!=null&&_.left||_!=null&&_.right),it=Re&&!j.current;j.current=Re;const Fe=u.active?u.sessionId:null;!Fe||!Yne({enteringSplit:it,isExistingSession:u.active&&u.projectContext.kind==="existing",hasActiveVariantProxy:f&&h!==null})||(b(!1),w(null),i(Qe=>Qe+1),bt(`/api/variants/${encodeURIComponent(Fe)}/preview-port`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({variantId:null})}).catch(()=>{}))},[_,u,f,h,b,w,i]);const N=g.useMemo(()=>{var ut;if(f||o&&!L||!u.active)return null;const{stage:Re,variants:it}=u,Fe=Re==="ready"||Re==="degraded",Qe=it.some(Ot=>{var Dn,Ie;return((Dn=Ot.refinement)==null?void 0:Dn.status)==="pending"||((Ie=Ot.refinement)==null?void 0:Ie.status)==="running"});if(!Fe&&!Qe)return null;const Ye=it.find(Ot=>{var Dn;return Ot.status==="succeeded"&&((Dn=Ot.preview)==null?void 0:Dn.kind)==="static_artifact"});return((ut=Ye==null?void 0:Ye.preview)==null?void 0:ut.kind)==="static_artifact"?pc({sessionId:u.sessionId,variant:Ye,projectContext:u.projectContext}):null},[L,o,f,u])??o,q=g.useMemo(()=>!u.active||!N?null:u.variants.find(Re=>{var it;return((it=Re.preview)==null?void 0:it.kind)==="static_artifact"&&N.startsWith(Re.preview.url)})??null,[N,u]),W=g.useMemo(()=>{if((x==null?void 0:x.previewKind)==="static"||(x==null?void 0:x.previewKind)==="dev_server"&&x.previewError||(x==null?void 0:x.previewKind)==="dev_server"&&N&&GP(N))return{kind:"variant",sessionId:x.sessionId,variantId:x.variantId};if(!u.active)return _A;if(q)return{kind:"variant",sessionId:u.sessionId,variantId:q.workItemId};if(N){const it=N.match(/\/__rivet\/preview\/variant\/([^/]+)\/([^/?#]+)/),Fe=it!=null&&it[1]?decodeURIComponent(it[1]):null,Qe=it!=null&&it[2]?decodeURIComponent(it[2]):null;if(Fe===u.sessionId&&Qe&&u.variants.some(Ot=>Ot.workItemId===Qe))return{kind:"variant",sessionId:u.sessionId,variantId:Qe};const Ye=N.match(/\/api\/variants\/[^/]+\/static\/([^/?#]+)/),ut=Ye!=null&&Ye[1]?decodeURIComponent(Ye[1]):null;if(ut&&u.variants.some(Ot=>Ot.workItemId===ut))return{kind:"variant",sessionId:u.sessionId,variantId:ut}}const Re=!!(_!=null&&_.left||_!=null&&_.right);return(!Re||k)&&!N&&f&&h&&u.variants.some(it=>it.workItemId===h)?{kind:"variant",sessionId:u.sessionId,variantId:h}:(!Re||k)&&!N&&C&&u.variants.some(it=>it.workItemId===C)?{kind:"variant",sessionId:u.sessionId,variantId:C}:_A},[x,q,u,f,h,N,_,k,C]),Y=g.useRef(null);g.useEffect(()=>{var Qe,Ye,ut;if(!q||((Qe=q.preview)==null?void 0:Qe.kind)!=="static_artifact"||((Ye=q.refinement)==null?void 0:Ye.status)!=="succeeded")return;const Re=`${q.workItemId}:${q.refinement.workItemId}`;if(Y.current===Re)return;if(Y.current=Re,(ut=q.previewRoutes)!=null&&ut.length){i(Ot=>Ot+1);return}const it=q.preview.url.includes("?")?"&":"?",Fe=`${q.preview.url}${it}refinement=${encodeURIComponent(q.refinement.workItemId)}`;N!==Fe&&(l(Fe),i(Ot=>Ot+1))},[N,q,i,l,u]);const H=N!==null&&GP(N),J=N!==null&&!H||k&&!f&&!H,{isUpstreamReady:B,iframeRemountKey:Q,probeAttemptCount:V,initialProbeComplete:D}=Kne(e,{rerunProbeImmediatelyOnVersion:s,probePath:H?N:null,skip:J}),[G,le]=g.useState(()=>m&&B?s:null),re=g.useRef(null);g.useEffect(()=>{if(!m){re.current=null,le(null);return}if(G===s){re.current=null;return}const Re=re.current;if(!Re||Re.remountKey!==s){re.current={remountKey:s,probeAttemptCount:V};return}B&&V>Re.probeAttemptCount&&(re.current=null,le(s))},[G,s,m,V,B]);const ue=N!==null&&!H||B,de=v||m&&!H&&G!==s||m&&!ue,ne=`${Q}:${s}`,Ce=N9(window.location.pathname),De=e==="static"?`/static${Ce??"/"}`:Ce??"/",Ee=tL();let ft=null;N&&(ft=lx({agentApplyMode:d,url:N}));const At=H&&!ue?"about:blank":ft,zt=P||R||x!=null&&x.previewError||de?"about:blank":At??(ue?`${Ee}${De}`:"about:blank"),wt=!!P||!!R||!ue&&D;let Tt=null;if(x!=null&&x.previewError)Tt=S.jsx(mc,{fill:"overlay",size:"sm",state:"preview_replay_failed",role:"alert",tone:"error",title:"Rivet couldn’t preview this direction",description:"Select the direction again to retry.",children:S.jsx("p",{className:"text-content-subtle text-xs leading-relaxed break-words",children:x.previewError})});else if(de)Tt=S.jsx(ux,{fill:"overlay",loader:"coalesce",trackGlobalLoaderCount:!1,state:"preview_replay_boot"});else if(P)Tt=S.jsx(ux,{fill:"overlay",loader:"coalesce",trackGlobalLoaderCount:!1,state:"variant_building",children:S.jsx("span",{className:"sr-only",children:"Building your direction"})});else if(R){const Re=u.active&&I&&R.state==="preview_unavailable"&&((sn=I.previewUnavailable)==null?void 0:sn.reason)!=="missing_static_entry"?{sessionId:u.sessionId,variantId:I.workItemId}:void 0;Tt=S.jsx(cre,{issue:R,retryTarget:Re},I==null?void 0:I.workItemId)}else wt&&(Tt=M?S.jsx(nL,{fill:"overlay",state:"preview_no_selection",title:"Nothing to preview yet",description:"Pick a direction from the panel."}):S.jsx(CS,{fill:"overlay",state:"preview_offline",title:"Preview isn't connected",description:"Rivet lost connection to your project.",actions:[{label:"Reload",onClick:()=>window.location.reload()}]}));return S.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-col",children:S.jsxs("div",{className:"relative min-h-0 flex-1",children:[Tt,S.jsx(tre,{target:W,src:zt,framework:e,remountKey:ne},r)]})})};function bA({side:t,sessionId:e,variantId:n,url:r,label:s,source:i,isFallback:o=!1}){var C;const l=dt(rl),u=yt(rl),d=si(),f=dt(op),h=dt(wv),m=g.useRef(!1),v=g.useCallback(()=>{m.current||(m.current=!0,vd({source:i,sessionId:e,variantId:n}))},[i,e,n]),w=g.useCallback(()=>{if(o){u(null);const I=Rg("ended",l);d==null||d.capture(I.event,I.properties);return}v();const P={...l};delete P[t];const T=P.left||P.right?P:null;u(T);const M=Rg(T?"updated":"ended",T??l);d==null||d.capture(M.event,M.properties)},[o,d,u,t,l,v]),_=g.useMemo(()=>({kind:"variant",sessionId:e,variantId:n}),[e,n]),x=g.useMemo(()=>!f.active||f.sessionId!==e?null:f.variants.find(P=>P.workItemId===n)??null,[e,n,f]),b=g.useMemo(()=>{var T,M,I;let P=r;if(((T=x==null?void 0:x.preview)==null?void 0:T.kind)==="static_artifact"&&((M=x.refinement)==null?void 0:M.status)==="succeeded"){if((I=x.previewRoutes)!=null&&I.length)return lx({agentApplyMode:h,url:pc({sessionId:e,variant:x,projectContext:null})??r});const R=x.preview.url.includes("?")?"&":"?";P=`${x.preview.url}${R}refinement=${encodeURIComponent(x.refinement.workItemId)}`}return lx({agentApplyMode:h,url:P})},[h,x,e,r]),k=((C=x==null?void 0:x.refinement)==null?void 0:C.status)==="succeeded"?`${n}:${x.refinement.workItemId}`:n;return S.jsxs("div",{className:"variant-split-secondary","data-cy":"variant-split-pane","data-variant-id":n,children:[S.jsxs("div",{className:"variant-split-secondary-toolbar",children:[S.jsx("span",{className:"variant-split-secondary-label",title:s,children:s}),S.jsx(Tc,{label:"Collapse",children:S.jsx("button",{type:"button",className:"variant-split-secondary-close",onClick:w,"aria-label":"Collapse split view",children:S.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12","aria-hidden":"true",focusable:"false",children:S.jsx("path",{d:"M2.5 2.5 L9.5 9.5 M9.5 2.5 L2.5 9.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})})})]}),S.jsx("div",{className:"variant-split-secondary-body relative min-h-0 flex-1",children:S.jsx(cx,{target:_,src:b,framework:"static",remountKey:k})})]})}function dre(){const t=dt(gd),e=dt(SS);return!t||!e?null:np.createPortal(S.jsx("div",{"aria-hidden":"true",className:"border-main-border bg-main pointer-events-none fixed top-0 left-0 z-[70] flex max-w-60 items-center gap-2 rounded-md border px-3 py-1.5 shadow-lg",style:{transform:`translate3d(${e.x+12}px, ${e.y+12}px, 0)`},children:S.jsx("span",{className:"text-content truncate text-sm font-medium",children:t.label})}),document.body)}function fre(){const t=dt(gd),e=dt(SS),n=dt(rl),r=yt(gd),s=yt(rl),i=si(),o=g.useRef(null),[l,u]=g.useState(null),[d,f]=g.useState("hidden");g.useEffect(()=>{t||(f("hidden"),u(null))},[t]);const h=g.useCallback((v,w)=>{const _=o.current;if(!_)return null;const x=_.getBoundingClientRect();return v<x.left||v>x.right||w<x.top||w>x.bottom?null:v<(x.left+x.right)/2?"left":"right"},[]);if(g.useEffect(()=>{if(!t||!e)return;const v=h(e.x,e.y);u(w=>w===v?w:v),f(w=>{if(w==="exiting")return w;const _=v!==null?"visible":"hidden";return w===_?w:_})},[t,e,h]),g.useEffect(()=>{if(!t)return;const v=w=>{const _=h(w.clientX,w.clientY);if(_&&t.url){const x={sessionId:t.sessionId,variantId:t.variantId,label:t.label,url:t.url,source:t.source},b=n==null?void 0:n[_];b&&(b.sessionId!==x.sessionId||b.variantId!==x.variantId)&&vd(b);const k={...n??{},[_]:x};s(k);const C=Rg(n?"updated":"started",k);i==null||i.capture(C.event,C.properties),f("exiting"),window.setTimeout(()=>r(null),220)}else vd(t),f("exiting"),window.setTimeout(()=>r(null),220)};return window.addEventListener("pointerup",v),window.addEventListener("pointercancel",v),()=>{window.removeEventListener("pointerup",v),window.removeEventListener("pointercancel",v)}},[t,h,i,r,s,n]),!t)return null;const m=["variant-drop-zones",d==="visible"&&"is-visible",d==="exiting"&&"is-exiting"].filter(Boolean).join(" ");return S.jsxs("div",{ref:o,className:m,"aria-hidden":"true",children:[S.jsx(SA,{side:"left",hovered:l==="left",canDrop:!!t.url,label:t.label}),S.jsx(SA,{side:"right",hovered:l==="right",canDrop:!!t.url,label:t.label})]})}function SA({side:t,hovered:e,canDrop:n,label:r}){return S.jsxs("div",{className:["variant-drop-zone",`is-${t}`,e&&"is-hover",!n&&"is-disabled"].filter(Boolean).join(" "),children:[S.jsxs("div",{className:"variant-drop-zone-inner",children:[S.jsx("div",{className:`variant-drop-zone-icon is-${t}`}),S.jsx("div",{className:"variant-drop-zone-caption",children:n?`Add ${t} split`:"Split unavailable for this direction"})]}),S.jsx("div",{className:"variant-drop-zone-preview","aria-hidden":"true",children:S.jsx("div",{className:"variant-drop-zone-preview-label",children:r})}),S.jsx("div",{className:"variant-drop-zone-border"})]})}const rL=(t,e,n)=>{var i,o,l;if(!t.active||t.sessionId!==e)return null;const r=t.variants.find(u=>u.workItemId===n);if(((i=r==null?void 0:r.preview)==null?void 0:i.kind)!=="static_artifact")return null;if((o=r.previewRoutes)!=null&&o.length)return pc({sessionId:e,variant:r,projectContext:t.projectContext});if(((l=r.refinement)==null?void 0:l.status)!=="succeeded")return r.preview.url;const s=r.preview.url.includes("?")?"&":"?";return`${r.preview.url}${s}refinement=${encodeURIComponent(r.refinement.workItemId)}`},kA=(t,e)=>{if(!t)return;const n=rL(e,t.sessionId,t.variantId);return!n||n===t.url?t:{...t,url:n}},hre=()=>S.jsx("div",{"data-testid":"preview-boot-skeleton",role:"status","aria-busy":"true","aria-label":"Loading preview",className:"bg-main flex h-full min-h-0 w-full flex-1 flex-col p-3",children:S.jsx("div",{className:"border-main-border relative min-h-0 flex-1 overflow-hidden rounded-lg border",children:S.jsx(J9,{trackGlobalLoaderCount:!1})})}),pre=({isLoading:t=!1,isInteractionDisabled:e=!1})=>{const{config:n,fetchConfig:r,isLoading:s,error:i}=Ane();return g.useEffect(()=>{r().catch(o=>{$e==null||$e.capture("preview_config_load_failed",{message:Rr(o,"unknown_error"),attempts:mA})})},[r]),s?S.jsx(hre,{}):i||!n?S.jsx(CS,{fill:"surface",size:"sm",state:"preview_config_error",title:"Couldn't load preview",description:"We couldn't load the preview configuration.",actions:[{label:"Retry",onClick:()=>{$e==null||$e.capture("preview_config_retry_clicked"),r().catch(o=>{$e==null||$e.capture("preview_config_load_failed",{message:Rr(o,"unknown_error"),attempts:mA})})}}]}):S.jsx(mre,{isLoading:t,isInteractionDisabled:e,framework:n.framework,userPort:n.userPort})};function mre(t){const e=dt(rl),n=dt(gd),r=dt(op),s=dt(Tg),i=e==null?void 0:e.left,o=e==null?void 0:e.right,l=g.useMemo(()=>{var T,M;if(!r.active||r.projectContext.kind!=="fresh"||!(!!i!=!!o))return;const _=(T=i??o)==null?void 0:T.variantId,x=r.variants.filter(I=>{var R;return I.status==="succeeded"&&((R=I.preview)==null?void 0:R.kind)==="static_artifact"&&I.workItemId!==_}),b=s==null?void 0:s.replace(/[?&]refinement=[^&]*$/,""),C=x.find(I=>{var R;return((R=I.preview)==null?void 0:R.kind)==="static_artifact"&&(I.preview.url===b||pc({sessionId:r.sessionId,variant:I,projectContext:r.projectContext})===s)})??x[0];if(((M=C==null?void 0:C.preview)==null?void 0:M.kind)!=="static_artifact")return;const P=rL(r,r.sessionId,C.workItemId);if(P)return{sessionId:r.sessionId,variantId:C.workItemId,label:C.label,url:P,source:"live"}},[r,i,o,s]),u=kA(i,r)??(o?l:void 0),d=kA(o,r)??(i?l:void 0),f=!i&&!!u,h=!o&&!!d,m=!!(u||d),v=S.jsx(ure,{isInteractionDisabled:t.isInteractionDisabled,framework:t.framework,userPort:t.userPort});return S.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 flex-col",children:S.jsxs("div",{className:`variant-preview-region relative flex h-full min-h-0 w-full flex-1 flex-col ${n?"is-dragging":""} ${m?"is-split":""}`,children:[S.jsxs("div",{className:"variant-preview-row flex h-full min-h-0 w-full flex-1",children:[u&&S.jsx(bA,{side:"left",sessionId:u.sessionId,variantId:u.variantId,url:u.url,label:u.label,source:u.source,isFallback:f},`left-${u.sessionId}:${u.variantId}:${u.url}`),S.jsx("div",{className:"variant-preview-primary flex h-full min-h-0 flex-1 flex-col",style:{display:u&&d?"none":void 0},"aria-hidden":!!(u&&d),children:v}),d&&S.jsx(bA,{side:"right",sessionId:d.sessionId,variantId:d.variantId,url:d.url,label:d.label,source:d.source,isFallback:h},`right-${d.sessionId}:${d.variantId}:${d.url}`)]}),S.jsx("div",{className:"variant-preview-atmosphere","aria-hidden":"true"}),S.jsx(fre,{}),S.jsx(dre,{})]})})}function Lo(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function sL(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}/*!
|
|
141
|
+
</html>`,Ute=yn({success:Za(),authUrl:Ke().optional(),sessionId:Ke().optional(),pollSecret:Ke().optional(),error:Ke().optional(),message:Ke().optional()}),Bte=yn({success:Za(),token:Ke().optional(),refreshToken:Ke().optional(),user:yn({id:Ke().optional(),email:Ke().optional()}).optional(),error:Ke().optional(),message:Ke().optional()}),Wte="/api/auth/install-ref",Zte=yn({installRef:Ke().nullable()}),qte=async()=>{try{const t=await fetch(Wte);if(!t.ok)return;const e=Zte.safeParse(await t.json());return e.success?e.data.installRef??void 0:void 0}catch{return}},G9=(t="editor_gate",e)=>{const n=si(),[r,s]=g.useState(!1),[i,o]=g.useState(null);return{startLogin:g.useCallback(async()=>{var m;const u=globalThis.crypto.randomUUID(),d=Date.now();s(!0),o(null);const f=D_({outcome:"started",authAttemptId:u,entryPoint:t,startedAt:d,now:d});n==null||n.capture(f.event,f.properties);let h=null;try{if(h=window.open("","_blank"),!h)throw new Error("Pop-up blocked. Please allow pop-ups and try again.");try{h.document.open(),h.document.write(zte),h.document.close()}catch(b){aA.warn("Failed to render loading state in auth popup:",b)}const v=await qte(),w=await fetch(`${ix}/api/auth/google/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"core",...v?{ref:v}:{}})}),_=Ute.safeParse(await w.json());if(!_.success)throw new Error("Invalid Google login response");const x=_.data;if(!w.ok||!x.success||!x.authUrl||!x.sessionId||!x.pollSecret)throw new Error(x.error||x.message||"Failed to start Google login");if(h.closed)throw new Error("Sign-in window was closed before Google login started.");h.location.href=x.authUrl;for(let b=0;b<Hte;b+=1){if(h.closed)throw new Error("Sign-in window was closed before authentication completed.");const k=await fetch(`${ix}/api/auth/google/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session:x.sessionId,pollSecret:x.pollSecret})}),C=Bte.safeParse(await k.json());if(!C.success)throw new Error("Invalid Google token response");const P=C.data;if(P.success&&P.token&&((m=P.user)!=null&&m.email)){const T={email:P.user.email,token:P.token,refreshToken:P.refreshToken,userId:P.user.id,...v?{installRef:v}:{}};if(e)await e(T);else if(!(await bt("/api/auth/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(T)})).ok)throw new Error("Signed in, but failed to store session locally.");h.close(),window.sessionStorage.setItem(Ig,"1");const M=D_({outcome:"completed",authAttemptId:u,entryPoint:t,startedAt:d,now:Date.now()});n==null||n.capture(M.event,M.properties),window.location.reload();return}if(P.error&&P.error!=="Pending")throw new Error(P.error||"Google login failed");await new Promise(T=>setTimeout(T,Vte))}throw new Error("Authentication timed out. Please try again.")}catch(v){h&&!h.closed&&h.close();const w=Rr(v,"Failed to start login flow");aA.warn("Login failed:",w);const _=D_({outcome:"failed",authAttemptId:u,entryPoint:t,startedAt:d,now:Date.now(),failureReason:Fte(w)});n==null||n.capture(_.event,_.properties),o(w),s(!1)}},[n,t,e]),isStartingLogin:r,loginError:i}},Gte=Ls("useIntegrations"),Kte=yn({provider:Ke(),status:Ke(),externalUsername:Ke().nullable(),connectedAt:Ke()}),Yte=yn({integrations:Ec(Kte).optional()}),Xte=yn({authUrl:Ke().min(1).optional(),error:Ke().optional()}),Qte=yn({error:Ke().optional()}),j_=["integrations"],Jte="rivet:connect-result",ene=t=>typeof t=="object"&&t!==null&&t.type===Jte,tne=qt(null),cA=async()=>{const t=await bt("/api/integrations");if(!t.ok)throw new Error(`Failed to load integrations (${t.status})`);return Yte.parse(await t.json()).integrations??[]},nne=()=>{const t=YR(),[e,n]=mI(tne),r=kh({queryKey:j_,queryFn:cA,staleTime:1e4}),s=g.useCallback(async()=>(await t.invalidateQueries({queryKey:j_,refetchType:"none"}),t.fetchQuery({queryKey:j_,queryFn:cA})),[t]),i=g.useCallback(async l=>{const u=window.open("","_blank","width=560,height=720");if(!u)throw new Error("Popup blocked. Allow popups to connect.");n(l);try{const d=await bt(`/api/integrations/${l}/connect`,{method:"POST"}),f=Xte.safeParse(await d.json().catch(()=>({}))),h=f.success?f.data:{};if(!d.ok||!h.authUrl)throw u.close(),new Error(h.error||`Could not connect ${l}`);return u.location.href=h.authUrl,await new Promise(m=>{let v=!1,w=null;const _=async(b,k=!1)=>{if(!v){v=!0,window.removeEventListener("message",x),w&&clearInterval(w);try{const P=(await s()).some(T=>T.provider===l&&T.status==="connected");m(k&&P?"connected":b)}catch{m(b)}}},x=b=>{if(ene(b.data)&&b.data.provider===l){if(b.data.status==="error"){Gte.warn(`Connect failed for ${l}:`,b.data.message),_("failed");return}_("connected")}};window.addEventListener("message",x),w=setInterval(()=>{u.closed&&_("closed",!0)},500)})}finally{n(null)}},[s,n]),o=g.useCallback(async l=>{n(l);try{const u=await bt(`/api/integrations/${l}`,{method:"DELETE"});if(!u.ok){const d=Qte.safeParse(await u.json().catch(()=>({}))),f=d.success?d.data:{};throw new Error(f.error||`Could not disconnect ${l}`)}await s()}finally{n(null)}},[s,n]);return{integrations:r.data??[],isLoading:r.isPending,error:r.error instanceof Error?r.error.message:null,pendingProvider:e,connect:i,disconnect:o,refetch:s}},$l=({action:t,outcome:e,provider:n,entryPoint:r,durationMs:s,failureReason:i})=>({event:`visual_editor_reference_${t==="connect"?"connection":"disconnection"}_${e}`,properties:{provider:n,entry_point:r,...s!==void 0?{duration_ms:s}:{},...i?{failure_reason:i}:{}}}),ap=async(t,e="GET",n)=>{if(window.location.pathname.startsWith("/rivet/library"))return hz(t,{method:e,body:n});const r=await bt(t.replace(/^\/profile/,"/api/reference-profiles"),{method:e,headers:{"Content-Type":"application/json"},...n!==void 0?{body:JSON.stringify(n)}:{}}),s=await r.text();let i;try{i=JSON.parse(s)}catch{throw new Error(`Reference profile request failed (${r.status})`)}if(!r.ok)throw new Error(i.error??`Request failed (${r.status})`);return i},K9=()=>ap("/profile"),rne=t=>kh({queryKey:["cosmos-profile"],queryFn:K9,enabled:t}),sne=t=>ap("/profile/discoveries","POST",{url:t}),ine=({discoveryId:t,collectionIds:e,runtime:n})=>ap("/profile/import-plans","POST",{discoveryId:t,collectionIds:e,runtime:n}),one=t=>ap("/profile","PATCH",{isEnabled:!0,runtime:t}),ane=t=>ap(`/profile/import-plans/${t.id}/imports`,"POST",{revision:t.revision,isApproved:!0}),ox=Ke().regex(/^[1-9]\d{0,15}$/).refine(t=>Number.isSafeInteger(Number(t))),lne=Ke().min(1).max(4096),Y9=t=>{const e=()=>new Error("Use an HTTPS Cosmos profile URL such as https://www.cosmos.so/username");let n;try{n=new URL(t)}catch{throw e()}const r=n.pathname.split("/").filter(Boolean);if(n.protocol!=="https:"||n.username||n.password||n.port||!["cosmos.so","www.cosmos.so"].includes(n.hostname)||r.length!==1)throw e();let s;try{s=decodeURIComponent(r[0])}catch{throw e()}if(!/^[a-zA-Z0-9_.-]{1,100}$/.test(s)||["e","login","signup","explore","search","collections","settings","api","profile"].includes(s.toLowerCase()))throw e();return{username:s,url:`https://www.cosmos.so/${encodeURIComponent(s)}`}};Ke().max(2048).transform((t,e)=>{try{return Y9(t).url}catch(n){return e.addIssue({code:we.custom,message:Rr(n,"Invalid Cosmos profile URL")}),iz}});const cne=t=>{const e=()=>new Error("Use an HTTPS Cosmos collection URL such as https://www.cosmos.so/owner/collection");let n;try{n=new URL(t)}catch{throw e()}const r=n.pathname.split("/").filter(Boolean);if(n.protocol!=="https:"||n.username||n.password||n.port||!["cosmos.so","www.cosmos.so"].includes(n.hostname)||r.length<2||r.length>3||r[0]==="e")throw e();let s;try{s=r.map(i=>decodeURIComponent(i))}catch{throw e()}if(s.some(i=>!i.length||i.length>300||/[/\\\p{Cc}]/u.test(i)))throw e();return{ownerUsername:s[0],slug:s[1],subcollectionSlug:s[2],url:`https://www.cosmos.so/${s.map(encodeURIComponent).join("/")}`}},une=Ke().url().refine(t=>{const e=new URL(t);return e.protocol==="https:"&&e.hostname==="cdn.cosmos.so"&&!e.username&&!e.password&&!e.port}),dne=yn({id:ox,title:Ke().min(1).max(500),url:Ke().url().transform(t=>cne(t).url),children:Ec(ox)}),fne=yn({id:ox,url:Ke().url(),title:Ke().max(1e3),text:Ke().max(1e5),author:Ke().nullable(),owner:Ke().nullable(),sourceUrl:Ke().url().nullable(),images:Ec(yn({url:une,representation:cr(["image","video-cover"])})).max(100),unsupportedReason:Ke().optional()}),hne=yn({collection:dne,elements:Ec(fne),total:ob().int().nonnegative(),nextCursor:lne.nullable()});sz("status",[hne.extend({status:wE("ok")}),yn({status:wE("error"),message:Ke(),reason:cr(["rate_limited","provider_unavailable","collection_unavailable"]).optional(),retryAfterMs:ob().nonnegative().optional()})]);const pne=({isOpen:t,onClose:e,onImported:n})=>{const[r,s]=g.useState(""),[i,o]=g.useState(null),[l,u]=g.useState([]),[d,f]=g.useState(""),[h,m]=g.useState(null),[v,w]=g.useState(null),[_,x]=g.useState(!1),b=g.useRef(0),k=si(),C=()=>{b.current+=1,s(""),o(null),u([]),f(""),m(null),w(null),x(!1)},P=()=>{k==null||k.capture("visual_editor_cosmos_modal_closed"),C(),e()},T=async L=>{L.preventDefault(),w(null);let j;try{j=Y9(r.trim()).url}catch(N){w(Rr(N,"Invalid Cosmos profile URL"));return}k==null||k.capture("visual_editor_cosmos_discovery_started");const F=++b.current;x(!0);try{const N=await sne(j);if(F!==b.current)return;o(N),u([]),k==null||k.capture("visual_editor_cosmos_discovery_completed",{collection_count:N.collections.length})}catch(N){if(F!==b.current)return;w(Rr(N,"Could not find Cosmos profile")),k==null||k.capture("visual_editor_cosmos_discovery_failed")}finally{F===b.current&&x(!1)}},M=async()=>{if(!i||l.length===0||!d)return;w(null),k==null||k.capture("visual_editor_cosmos_plan_started",{collection_count:l.length,runtime:d});const L=++b.current;x(!0);try{const j=await ine({discoveryId:i.id,collectionIds:l,runtime:d});if(L!==b.current)return;m(j),k==null||k.capture("visual_editor_cosmos_plan_completed",{collection_count:j.collectionCount,reference_count:j.referenceCount})}catch(j){if(L!==b.current)return;w(Rr(j,"Could not prepare import plan")),k==null||k.capture("visual_editor_cosmos_plan_failed")}finally{L===b.current&&x(!1)}},I=async()=>{if(!h||!d)return;w(null),k==null||k.capture("visual_editor_cosmos_import_started",{collection_count:h.collectionCount,reference_count:h.referenceCount});const L=++b.current;x(!0);try{if((await K9()).profile.isEnabled||await one(d),await ane(h),k==null||k.capture("visual_editor_cosmos_import_completed",{reference_count:h.referenceCount}),n(),L!==b.current)return;C(),e()}catch(j){if(k==null||k.capture("visual_editor_cosmos_import_failed"),L!==b.current)return;w(Rr(j,"Could not start Cosmos import"))}finally{L===b.current&&x(!1)}},R=L=>{u(j=>j.includes(L)?j.filter(F=>F!==L):[...j,L]),k==null||k.capture("visual_editor_cosmos_collection_toggled")};return S.jsx(dv,{open:t,onOpenChange:L=>!L&&P(),children:S.jsxs(fv,{children:[S.jsx(hv,{className:"z-max fixed inset-0 bg-black/60"}),S.jsxs(pv,{className:"z-max border-main-border bg-main font-main fixed top-1/2 left-1/2 max-h-[min(680px,calc(100vh-32px))] w-[min(440px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-lg border shadow-2xl outline-none",children:[S.jsxs("div",{className:"border-main-border bg-main-light flex items-center justify-between rounded-t-lg border-b px-4 py-2",children:[S.jsx(mv,{className:"text-content text-base font-medium",children:"Connect Cosmos"}),S.jsx(Qi,{onClick:P,title:"Close","aria-label":"Close",variant:"ghost",size:"icon-compact",children:S.jsx(Bb,{className:"h-4 w-4",weight:"bold"})})]}),S.jsxs("div",{className:"space-y-4 p-4",children:[S.jsx(gv,{className:"text-content-subtle text-sm",children:"Add public collections from a Cosmos profile to your design references."}),i?null:S.jsxs("form",{onSubmit:L=>void T(L),className:"space-y-4",children:[S.jsx("label",{className:"text-content block text-sm font-medium",htmlFor:"cosmos-profile-url",children:"Cosmos profile URL"}),S.jsx("input",{id:"cosmos-profile-url",type:"url",required:!0,autoFocus:!0,value:r,onChange:L=>s(L.target.value),placeholder:"https://www.cosmos.so/username",className:"border-main-border bg-main-input text-content placeholder:text-content-muted focus:border-secondary w-full rounded-md border px-3 py-2 text-sm outline-none"}),S.jsx("button",{type:"submit",disabled:_,className:"bg-secondary text-secondary-foreground hover:bg-accent rounded-md px-4 py-2 text-sm font-medium disabled:opacity-50",children:_?"Finding collections…":"Continue"})]}),i&&!h?S.jsxs("div",{className:"space-y-4",children:[S.jsxs("p",{className:"text-content text-sm font-medium",children:["Choose collections from"," ",i.profile.title||i.profile.username]}),S.jsx("div",{className:"border-main-border max-h-60 divide-y overflow-y-auto rounded-md border",children:i.collections.map(L=>S.jsxs("label",{className:"text-content hover:bg-main-light flex cursor-pointer items-center gap-3 px-3 py-2 text-sm",children:[S.jsx("input",{type:"checkbox",checked:l.includes(L.id),disabled:_,onChange:()=>R(L.id)}),S.jsx("span",{className:"min-w-0 flex-1 truncate",children:L.title}),S.jsx("span",{className:"text-content-muted text-xs",children:L.total??"—"})]},L.id))}),i.collections.length===0?S.jsx("p",{className:"text-content-muted text-sm",children:"No public collections found for this profile."}):null,S.jsxs("label",{className:"text-content flex items-center justify-between gap-3 text-sm",children:["Analysis runtime",S.jsxs("select",{value:d,disabled:_,onChange:L=>{const j=L.target.value;f(j),k==null||k.capture("visual_editor_cosmos_runtime_selected",{runtime:j})},className:"border-main-border bg-main-input rounded-md border px-2 py-1.5",children:[S.jsx("option",{value:"",disabled:!0,children:"Select a runtime"}),S.jsx("option",{value:"codex",children:"Codex"}),S.jsx("option",{value:"claude",children:"Claude"}),S.jsx("option",{value:"cursor",children:"Cursor"})]})]}),S.jsx("button",{type:"button",onClick:()=>void M(),disabled:_||l.length===0||!d,className:"bg-secondary text-secondary-foreground hover:bg-accent rounded-md px-4 py-2 text-sm font-medium disabled:opacity-50",children:_?"Preparing plan…":"Review import plan"}),S.jsx("button",{type:"button",onClick:()=>{k==null||k.capture("visual_editor_cosmos_profile_changed"),C()},disabled:_,className:"text-content-muted hover:text-content ml-3 text-sm",children:"Use another profile"})]}):null,h?S.jsxs("div",{className:"space-y-4 text-sm",children:[S.jsxs("p",{className:"text-content",children:[h.collectionCount," ",h.collectionCount===1?"collection":"collections"," ·"," ",h.referenceCount," ",h.referenceCount===1?"reference":"references"," ·"," ",h.imageCount," ",h.imageCount===1?"image":"images"]}),S.jsx("p",{className:"text-content-subtle",children:h.scopeDisclosure}),S.jsx("p",{className:"text-content-subtle",children:h.usageDisclosure}),S.jsxs("p",{className:"text-content-muted text-xs",children:[h.reusableCount," reusable · ",h.unsupportedCount," ","unsupported · runtime: ",d]}),S.jsx("button",{type:"button",onClick:()=>void I(),disabled:_,className:"bg-secondary text-secondary-foreground hover:bg-accent rounded-md px-4 py-2 text-sm font-medium disabled:opacity-50",children:_?"Starting import…":"Approve and import"}),S.jsx("button",{type:"button",onClick:()=>{k==null||k.capture("visual_editor_cosmos_plan_revised"),m(null)},disabled:_,className:"text-content-muted hover:text-content ml-3 text-sm",children:"Change selection"})]}):null,v?S.jsx("p",{role:"alert",className:"text-sm text-red-300",children:v}):null]})]})]})})},uA=Ls("ConnectorsModal"),mne=[{provider:"x",name:"X",iconClassName:"text-content",icon:S.jsx(oh,{provider:"x"})},{provider:"pinterest",name:"Pinterest",iconClassName:"text-[#e60023]",icon:S.jsx(oh,{provider:"pinterest"})},{provider:"arena",name:"Are.na",iconClassName:"text-content",icon:S.jsx(oh,{provider:"arena"})}],gne={name:"Cosmos",iconClassName:"text-content",icon:S.jsx(oh,{provider:"cosmos"})},dA=({meta:t,status:e,actionLabel:n,buttonLabel:r,isDisabled:s,isHighlighted:i,onAction:o})=>S.jsxs("li",{className:`flex min-h-[64px] items-center gap-3 py-3 ${i?"ring-secondary -mx-2 rounded-md px-2 ring-2":""}`,children:[S.jsx("span",{className:`grid h-7 w-7 flex-none place-items-center ${t.iconClassName}`,"aria-hidden":"true",children:t.icon}),S.jsxs("div",{className:"min-w-0 flex-1",children:[S.jsx("span",{className:"text-content block text-sm font-medium",children:t.name}),S.jsx("span",{className:"text-content-muted block truncate text-xs",children:e})]}),S.jsx("button",{type:"button","aria-label":n,onClick:o,disabled:s,className:"active-push bg-main-input text-content hover:bg-main-input/80 inline-flex min-h-8 w-24 flex-none items-center justify-center rounded-md px-3 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50",children:r})]}),ax=({isOpen:t,onClose:e,context:n="menu",highlightProvider:r=null})=>{var M;const{integrations:s,isLoading:i,error:o,pendingProvider:l,connect:u,disconnect:d}=nne(),f=si(),[h,m]=g.useState(null),[v,w]=g.useState(!1),_=rne(t),x=I=>s.find(R=>R.provider===I),b=g.useCallback(I=>{const R=Date.now(),L=$l({action:"connect",outcome:"started",provider:I,entryPoint:n});f==null||f.capture(L.event,L.properties),u(I).then(j=>{const F=Date.now()-R;if(j==="connected"){const q=$l({action:"connect",outcome:"completed",provider:I,entryPoint:n,durationMs:F});f==null||f.capture(q.event,q.properties);return}const N=$l({action:"connect",outcome:"failed",provider:I,entryPoint:n,durationMs:F,failureReason:j==="closed"?"popup_closed":"provider_failed"});f==null||f.capture(N.event,N.properties)}).catch(j=>{const F=Rr(j,"Could not connect."),N=$l({action:"connect",outcome:"failed",provider:I,entryPoint:n,durationMs:Date.now()-R,failureReason:F.includes("Popup blocked")?"popup_blocked":"request_failed"});f==null||f.capture(N.event,N.properties),uA.warn(`Connect error for ${I}:`,F),$t.error(F)})},[u,n,f]),k=g.useCallback(I=>{const R=Date.now(),L=$l({action:"disconnect",outcome:"started",provider:I,entryPoint:n});f==null||f.capture(L.event,L.properties),d(I).then(()=>{const j=$l({action:"disconnect",outcome:"completed",provider:I,entryPoint:n,durationMs:Date.now()-R});f==null||f.capture(j.event,j.properties)}).catch(j=>{const F=Rr(j,"Could not disconnect."),N=$l({action:"disconnect",outcome:"failed",provider:I,entryPoint:n,durationMs:Date.now()-R,failureReason:"request_failed"});f==null||f.capture(N.event,N.properties),uA.warn(`Disconnect error for ${I}:`,F),$t.error(F)})},[n,d,f]),C=n==="onboarding",P=(M=_.data)==null?void 0:M.sources.some(I=>I.provider==="cosmos");let T=P?"Connected":"Not connected";return _.isError&&(T="Status unavailable"),_.isPending&&(T="Checking status…"),S.jsxs(S.Fragment,{children:[S.jsx(dv,{open:t,onOpenChange:I=>!I&&e(),children:S.jsxs(fv,{children:[S.jsx(hv,{className:"z-max fixed inset-0 bg-black/40"}),S.jsx(pv,{ref:m,className:"z-max border-main-border bg-main font-main fixed top-1/2 left-1/2 w-[min(440px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 rounded-lg border shadow-2xl outline-none",children:S.jsxs(JO,{value:h,children:[S.jsxs("div",{className:"border-main-border bg-main-light flex items-center justify-between rounded-t-lg border-b px-4 py-2",children:[S.jsx(mv,{className:"text-content text-base font-medium",children:"Connect design references"}),S.jsx(Qi,{onClick:e,title:"Close","aria-label":"Close",variant:"ghost",size:"icon-compact",children:S.jsx(Bb,{className:"h-4 w-4",weight:"bold"})})]}),S.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[S.jsx(gv,{className:"text-content-subtle text-sm",children:"Connect your references to add them to your Rivet library. Rivet can use them to inspire new design directions."}),o?S.jsx("p",{className:"rounded-lg bg-red-500/10 px-4 py-3 text-[13px] font-medium text-red-300",children:o}):null,S.jsxs("ul",{className:"divide-main-border divide-y","aria-label":"Design reference services",children:[mne.map(I=>{const R=x(I.provider),L=(R==null?void 0:R.status)==="connected",j=R==null?void 0:R.externalUsername;let F=L?`Connected${j?` as @${j}`:""}`:"Not connected";i&&(F="Checking status…");const N=l===I.provider,q=L?"Disconnect":"Connect";return S.jsx(dA,{meta:I,status:F,actionLabel:`${q} ${I.name}`,buttonLabel:N?`${q}ing…`:q,isDisabled:i||N,isHighlighted:r===I.provider,onAction:()=>L?k(I.provider):b(I.provider)},I.provider)}),S.jsx(dA,{meta:gne,status:T,actionLabel:P?"Add Cosmos profile":"Connect Cosmos",buttonLabel:P?"Add profile":"Connect",isDisabled:!1,isHighlighted:!1,onAction:()=>{f==null||f.capture("visual_editor_cosmos_modal_opened"),w(!0)}})]}),C?S.jsxs("div",{className:"flex items-center justify-between gap-4",children:[S.jsx("p",{className:"text-content-subtle text-xs",children:"You can always do this later from the account menu."}),S.jsx("button",{type:"button",onClick:e,className:"active-push bg-secondary text-secondary-foreground hover:bg-accent flex-none rounded-lg px-3.5 py-2 text-[13px] font-medium transition-colors",children:"Skip for now"})]}):null]})]})})]})}),S.jsx(pne,{isOpen:v,onClose:()=>w(!1),onImported:()=>{_.refetch()}})]})},fA=({className:t=""})=>S.jsx("span",{"aria-hidden":"true",className:`rivet-skeleton block rounded ${t}`.trim()}),vne=Ls("SupportTicketModal"),hA=5e3,$_="feedback",yne=yn({error:Ke().optional(),details:rz([Ke(),yn({formErrors:Ec(Ke()).optional(),fieldErrors:BR(Ke(),Ec(Ke()).optional()).optional()})]).optional()}),_ne=t=>{var r;if(!t)return null;const e=(r=t.formErrors)==null?void 0:r[0];if(e)return e;const n=t.fieldErrors??{};for(const s of Object.values(n)){const i=s==null?void 0:s[0];if(i)return i}return null},wne=async t=>{let e;try{const n=yne.safeParse(await t.json());e=n.success?n.data:void 0}catch{e=void 0}if(t.status===400){if(typeof(e==null?void 0:e.details)=="string"&&e.details.trim())return e.details;if(typeof(e==null?void 0:e.details)=="object"&&e.details!==null){const n=_ne(e.details);if(n)return n}return"Please check your feedback and try again."}return t.status>=500?typeof(e==null?void 0:e.details)=="string"&&e.details.trim()?e.details:"Could not send feedback right now. Please try again later.":typeof(e==null?void 0:e.error)=="string"&&e.error.trim()?e.error:`HTTP ${t.status}`},xne=({isOpen:t,onClose:e,contactEmail:n})=>{const r=si(),[s,i]=g.useState(""),[o,l]=g.useState(!1),[u,d]=g.useState(null),f=g.useCallback(()=>{i("")},[]),h=g.useCallback(()=>{o||(f(),e())},[o,e,f]),m=g.useCallback(async()=>{const x=s.trim();if(!(!x||o)){l(!0);try{const b=typeof(r==null?void 0:r.get_session_id)=="function"?r.get_session_id():void 0,k=typeof(r==null?void 0:r.get_distinct_id)=="function"?r.get_distinct_id():void 0,C=n==null?void 0:n.trim(),P=await bt("/api/support/tickets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:$_,message:x,contactEmail:C||void 0,metadata:{posthogSessionId:b??void 0,posthogDistinctId:k??void 0,appVersion:"0.26.1",appEnvironment:"production",pageUrl:window.location.href,userAgent:navigator.userAgent,submittedAt:new Date().toISOString()}})});if(!P.ok){const T=await wne(P);throw new Error(T)}r==null||r.capture("support_ticket_submitted",{ticket_type:$_,has_posthog_session_id:!!b}),$t.success("Feedback sent",{description:"Thanks for sharing this."}),f(),e()}catch(b){const k=Rr(b,"Failed to send message");r==null||r.capture("support_ticket_submit_failed",{ticket_type:$_,error:k}),vne.error("Failed to submit support ticket:",k),$t.error("Could not send feedback",{description:k})}finally{l(!1)}}},[n,o,s,e,r,f]),v=g.useCallback(x=>{x.key==="Enter"&&(x.metaKey||x.ctrlKey)&&(x.preventDefault(),m())},[m]),w=hA-s.length,_=o||s.trim().length===0;return S.jsx(dv,{open:t,onOpenChange:x=>!x&&h(),children:S.jsxs(fv,{children:[S.jsx(hv,{className:"z-max fixed inset-0 bg-black/40"}),S.jsx(pv,{ref:d,className:"z-max border-main-border bg-main font-main fixed top-1/2 left-1/2 w-[440px] -translate-x-1/2 -translate-y-1/2 rounded-lg border shadow-2xl outline-none",children:S.jsxs(JO,{value:u,children:[S.jsxs("div",{className:"border-main-border bg-main-light flex items-center justify-between rounded-t-lg border-b px-4 py-2",children:[S.jsx(mv,{className:"text-content text-base font-medium",children:"Send feedback"}),S.jsx(Qi,{onClick:h,disabled:o,title:"Close","aria-label":"Close",variant:"ghost",size:"icon-compact",children:S.jsx(Bb,{className:"h-4 w-4",weight:"bold"})})]}),S.jsxs("div",{className:"flex flex-col gap-3 p-4",children:[S.jsx(gv,{className:"text-content-subtle text-sm",children:"Tell us what happened or what we can improve."}),S.jsxs("div",{className:"bg-main-input rounded-lg outline outline-1 outline-transparent transition-[outline-color] focus-within:outline-white/20",children:[S.jsx("textarea",{id:"support-ticket-message","aria-label":"Your feedback",value:s,onChange:x=>i(x.target.value),onKeyDown:v,maxLength:hA,rows:6,disabled:o,placeholder:"What happened?",className:"text-content placeholder-content-subtle max-h-64 w-full resize-none overflow-y-auto bg-transparent pt-3 pr-3 pb-1 pl-3 text-sm focus:outline-none disabled:opacity-50"}),S.jsxs("div",{className:"flex items-center justify-between px-3 pt-1 pb-3",children:[S.jsx("span",{className:"text-content-subtle text-xs",children:"Context details are included automatically."}),S.jsxs("div",{className:"flex items-center gap-2",children:[w<=500&&S.jsx("span",{className:"text-content-subtle text-xs",children:w}),S.jsx(Qi,{onClick:m,disabled:_,title:"Send feedback",shortcut:"⌘↵","aria-label":"Send feedback",size:"icon-compact",children:o?S.jsx(tv,{className:"h-5 w-5 animate-spin",weight:"bold"}):S.jsx(iY,{className:"h-5 w-5",weight:"bold"})})]})]})]})]})]})})]})})},bne=Ls("ProfileAvatar"),X9=(t,e)=>{const n=(t??"").trim();if(n)return n.split(/\s+/).filter(Boolean)[0]??"";const s=((e??"").split("@")[0]??"").split(/[._\-+]/).filter(Boolean)[0]??"";return s?s[0].toUpperCase()+s.slice(1):""},Sne=(t,e)=>X9(t,e).charAt(0).toUpperCase(),kne=({className:t="",side:e="bottom",align:n="end"})=>{var q,W,Y;const r=$te(),s=((q=r.data)==null?void 0:q.name)??null,i=((W=r.data)==null?void 0:W.email)??null,o=((Y=r.data)==null?void 0:Y.isAuthenticated)===!0,l=si(),{startLogin:u,isStartingLogin:d,loginError:f}=G9("account_menu"),[h,m]=g.useState(!1),[v,w]=g.useState(!1),[_,x]=g.useState(!1),[b,k]=g.useState(!1),{containerRef:C,onKeyDown:P,onCloseAutoFocus:T}=_9({onDismiss:()=>N(!1)}),M=Sne(s,i);if(r.isPending)return S.jsxs("span",{"data-testid":"profile-avatar-skeleton","aria-hidden":"true",className:`flex shrink-0 items-center gap-2 ${t}`.trim(),children:[S.jsx(fA,{className:"h-8 w-8 rounded-full"}),S.jsx(fA,{className:"h-3.5 w-16"})]});const I=X9(s,i),R=(s==null?void 0:s.trim())||null,L=(i==null?void 0:i.trim())||null,j=async()=>{k(!0);try{const H=await bt("/api/auth/logout",{method:"POST",credentials:"same-origin"});if(!H.ok)throw new Error(`Logout failed: ${H.status}`);window.location.pathname.startsWith("/rivet/library")&&ZR()}catch(H){bne.warn("Logout request failed",H),$t.error("Could not log out. Please try again."),k(!1);return}window.location.reload()};let F="Log in";o&&(F=I||"Account"),r.error&&!r.data&&(F="Account unavailable");const N=H=>{m(H),l==null||l.capture(`visual_editor_account_menu_${H?"opened":"closed"}`,{is_authenticated:o})};return S.jsxs(S.Fragment,{children:[S.jsxs(yS,{open:h,onOpenChange:N,children:[S.jsx(_S,{asChild:!0,children:S.jsxs("button",{type:"button","aria-label":"Account","data-rivet-private":!0,className:`ph-no-capture text-content-muted hover:text-content flex shrink-0 items-center gap-2 transition-colors select-none ${t}`,children:[S.jsx("span",{className:"border-main-border bg-main-input flex h-8 w-8 items-center justify-center rounded-full border text-xs leading-none font-semibold",children:M||S.jsx(yY,{className:"h-4 w-4",weight:"bold"})}),S.jsx("span",{className:"max-w-[8rem] truncate text-sm font-medium",children:F})]})}),S.jsx(wS,{children:S.jsxs(xS,{"data-rivet-private":!0,ref:C,onKeyDown:P,onCloseAutoFocus:T,role:"menu",className:"ph-no-capture bg-popover shadow-surface-4 z-[60] min-w-[180px] rounded-lg p-1",side:e,sideOffset:6,align:n,children:[R||L?S.jsxs("div",{className:"border-main-border border-b px-3 py-2",children:[R?S.jsx("div",{className:"text-content truncate text-sm font-medium",children:R}):null,L?S.jsx("div",{className:"text-content-muted truncate text-xs",children:L}):null]}):null,S.jsxs("button",{type:"button",role:"menuitem","data-menu-item":!0,onClick:()=>{N(!1),w(!0)},disabled:!o,className:"text-content hover:bg-hover focus-visible:bg-hover mt-1 flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors focus:outline-none disabled:cursor-not-allowed disabled:opacity-50",children:[S.jsx(w3,{className:"h-4 w-4",weight:"bold"}),"Connect design references"]}),S.jsxs("button",{type:"button",role:"menuitem","data-menu-item":!0,onClick:()=>{N(!1),x(!0)},className:"text-content hover:bg-hover focus-visible:bg-hover mt-1 flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors focus:outline-none",children:[S.jsx(lY,{className:"h-4 w-4",weight:"bold"}),"Share feedback"]}),o?S.jsxs("button",{type:"button",role:"menuitem","data-menu-item":!0,onClick:j,disabled:b,className:"text-content hover:bg-hover focus-visible:bg-hover mt-1 flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors focus:outline-none disabled:cursor-not-allowed disabled:opacity-50",children:[S.jsx(gY,{className:"h-4 w-4",weight:"bold"}),b?"Logging out…":"Log out"]}):null,!o&&!r.error?S.jsxs("button",{type:"button",role:"menuitem","data-menu-item":!0,onClick:()=>{u()},disabled:d,className:"text-content hover:bg-hover focus-visible:bg-hover mt-1 flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-sm focus:outline-none disabled:opacity-50",children:[S.jsx(mY,{className:"h-4 w-4",weight:"bold"}),d?"Logging in…":"Log in"]}):null,r.error?S.jsx("button",{type:"button",role:"menuitem","data-menu-item":!0,onClick:()=>{r.refetch()},className:"text-content mt-1 px-3 py-1.5 text-sm",children:"Retry account"}):null,f?S.jsx("p",{role:"alert",className:"max-w-64 px-3 py-2 text-sm text-red-300",children:f}):null]})})]}),v?S.jsx(ax,{isOpen:!0,onClose:()=>w(!1)}):null,S.jsx(xne,{isOpen:_,onClose:()=>x(!1),contactEmail:i??void 0})]})},Ene=({onClose:t,libraryOrigin:e})=>S.jsxs("div",{className:"bg-main font-main scrollbar-hide relative flex h-full w-full cursor-auto flex-col overflow-hidden shadow-2xl","data-cy":"element-inspector",children:[S.jsx(Dte,{onClose:t,libraryOrigin:e}),S.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:S.jsx(_te,{})}),S.jsx("div",{className:"border-main-border bg-main-light flex flex-shrink-0 items-center border-t px-2.5 py-2.5",children:S.jsx(kne,{side:"top",align:"start"})})]});async function Cne(t,e){const{delaysMs:n,shouldRetry:r,onRetry:s}=e;for(let i=1;;i++)try{return await t(i)}catch(o){const l=n[i-1];if(l===void 0||r&&!r(o))throw o;s==null||s(o,i,l),await new Promise(u=>setTimeout(u,l))}}const pA=Ls("useServerConfig"),Q9=[250,500,1e3,2e3,4e3],mA=Q9.length+1,Pne=async()=>{var n;const t=await bt("/api/health");if(!t.ok)throw new Error(`Failed to fetch config: ${t.status}`);const e=await t.json();if(!e.framework)throw new Error("Server did not return framework information");return{userPort:((n=e.ports)==null?void 0:n.userDevServer)||3e3,framework:e.framework}},Ane=()=>{const[t,e]=g.useState(null),[n,r]=g.useState(!0),[s,i]=g.useState(null),o=g.useCallback(async()=>{try{r(!0),i(null);const l=await Cne(Pne,{delaysMs:Q9,onRetry:(u,d,f)=>{pA.warn(`Server config fetch failed (attempt ${d}); retrying in ${f}ms`,u)}});return e(l),l}catch(l){throw i(Rr(l,"Failed to fetch server config")),pA.warn("Error fetching server config:",l),l}finally{r(!1)}},[]);return{config:t,fetchConfig:o,isLoading:n,error:s}},Tne="#1C1C20",Co=[118,118,124],gA=.85,Rne=3,Ine=.15,q0=36,Mne=4.4,One=.7,Lne=3.5,Nne=.8,vA=9,Dne=11,jne=[1.35,1.12,.95,.85],$ne=[0,1.1,2.3,3.1],Fne=[0,.35,.16,.13],Vne=[.9,.5,.4,.35],Fl=3,F_=[[{x1:.1,y1:.08,x2:.9,y2:.92,level:0},{x1:.14,y1:.13,x2:.86,y2:.23,level:1},{x1:.14,y1:.28,x2:.3,y2:.87,level:1},{x1:.34,y1:.28,x2:.86,y2:.87,level:1},{x1:.165,y1:.155,x2:.225,y2:.205,level:2},{x1:.7,y1:.155,x2:.755,y2:.205,level:2},{x1:.775,y1:.155,x2:.83,y2:.205,level:2},{x1:.165,y1:.32,x2:.275,y2:.375,level:2},{x1:.165,y1:.415,x2:.275,y2:.47,level:2},{x1:.165,y1:.51,x2:.275,y2:.565,level:2},{x1:.37,y1:.32,x2:.585,y2:.56,level:2},{x1:.615,y1:.32,x2:.83,y2:.56,level:2},{x1:.37,y1:.61,x2:.83,y2:.83,level:2},{hline:!0,x1:.39,x2:.81,y:.685,level:3},{hline:!0,x1:.39,x2:.75,y:.755,level:3}],[{x1:.1,y1:.08,x2:.9,y2:.92,level:0},{x1:.16,y1:.17,x2:.52,y2:.45,level:1},{x1:.58,y1:.17,x2:.685,y2:.29,level:1},{x1:.715,y1:.17,x2:.84,y2:.29,level:1},{x1:.58,y1:.33,x2:.685,y2:.45,level:1},{x1:.715,y1:.33,x2:.84,y2:.45,level:1},{x1:.16,y1:.55,x2:.84,y2:.85,level:1},{x1:.19,y1:.21,x2:.36,y2:.33,level:2},{hline:!0,x1:.19,x2:.48,y:.37,level:3},{hline:!0,x1:.19,x2:.42,y:.42,level:3},{x1:.19,y1:.6,x2:.49,y2:.8,level:2},{hline:!0,x1:.53,x2:.8,y:.63,level:3},{hline:!0,x1:.53,x2:.76,y:.7,level:3},{hline:!0,x1:.53,x2:.79,y:.77,level:3}],[{x1:.1,y1:.08,x2:.9,y2:.92,level:0},{x1:.14,y1:.13,x2:.86,y2:.22,level:1},{x1:.14,y1:.28,x2:.36,y2:.87,level:1},{x1:.39,y1:.28,x2:.61,y2:.87,level:1},{x1:.64,y1:.28,x2:.86,y2:.87,level:1},{x1:.165,y1:.15,x2:.225,y2:.2,level:2},{x1:.165,y1:.32,x2:.335,y2:.52,level:2},{x1:.415,y1:.32,x2:.585,y2:.52,level:2},{x1:.665,y1:.32,x2:.835,y2:.52,level:2},{hline:!0,x1:.165,x2:.335,y:.6,level:3},{hline:!0,x1:.165,x2:.3,y:.67,level:3},{hline:!0,x1:.415,x2:.585,y:.6,level:3},{hline:!0,x1:.415,x2:.55,y:.67,level:3},{hline:!0,x1:.665,x2:.835,y:.6,level:3},{hline:!0,x1:.665,x2:.8,y:.67,level:3}],[{x1:.1,y1:.08,x2:.9,y2:.92,level:0},{x1:.3,y1:.22,x2:.7,y2:.74,level:1},{x1:.34,y1:.27,x2:.55,y2:.34,level:2},{hline:!0,x1:.36,x2:.64,y:.42,level:3},{hline:!0,x1:.36,x2:.6,y:.49,level:3},{hline:!0,x1:.36,x2:.62,y:.56,level:3},{x1:.5,y1:.63,x2:.575,y2:.69,level:2},{x1:.595,y1:.63,x2:.66,y2:.69,level:2}]],G0=t=>{let e=t|0;return e=Math.imul(e^e>>>16,73244475),e=Math.imul(e^e>>>16,73244475),e^=e>>>16,(e>>>0)/4294967296},km=t=>{const e=Math.min(1,Math.max(0,t));return e*e*(3-2*e)},Vl=(t,e)=>(Math.round(t/e-.5)+.5)*e,Hne=Math.sin(Math.PI/3),yA=(t,e,n,r,s)=>{if(t.beginPath(),e===0)t.arc(n,r,s,0,Math.PI*2);else if(e===1){const i=s*Hne;t.moveTo(n,r-s),t.lineTo(n+i,r+s/2),t.lineTo(n-i,r+s/2),t.closePath()}else{const i=s*.85;t.rect(n-i,r-i,i*2,i*2)}t.fill()},zne=(t,e,n)=>{let r;if(n.hline){const s=Math.max(n.x1-t,t-n.x2,0),i=Math.abs(e-n.y1);r=Math.hypot(s,i)-vA}else{const s=Math.max(n.x1-t,t-n.x2,0),i=Math.max(n.y1-e,e-n.y2,0);s===0&&i===0?r=-Math.min(t-n.x1,n.x2-t,e-n.y1,n.y2-e):r=Math.hypot(s,i),r=Math.abs(r)-vA}return km(.5-r/(2*Dne))},J9=({className:t="",trackGlobalLoaderCount:e=!0})=>{const n=yt(S9),r=g.useRef(null),s=g.useCallback(i=>{var j;if((j=r.current)==null||j.call(r),r.current=null,!i)return;const o=i.getContext("2d");if(!o)return;e&&n(F=>F+1);const l=window.matchMedia("(prefers-reduced-motion: reduce)").matches;let u=[],d=0,f=0,h=q0,m=q0,v=null,w=null,_=0,x=-1;const b=new Array(33),k=F=>{const N=Math.round(F*32);let q=b[N];if(!q){const W=N/32,Y=Math.round(Co[0]+(255-Co[0])*W),H=Math.round(Co[1]+(255-Co[1])*W),J=Math.round(Co[2]+(255-Co[2])*W);q=`rgba(${Y}, ${H}, ${J}, ${gA})`,b[N]=q}return q},C=F=>{const N=1-.35*F,q=Math.round(Co[0]*N),W=Math.round(Co[1]*N),Y=Math.round(Co[2]*N);return`rgba(${q}, ${W}, ${Y}, ${gA})`},P=F=>{let N=Math.floor(Math.random()*F_.length);N===x&&(N=(N+1)%F_.length),x=N;const q=[0,0,0,0],W=F_[N].map((D,G)=>{const le=D.level,re=q[le]++,ie=$ne[le]+re*Fne[le],ue=Vne[le]+G0(N*131+G*17+5)*.2;if(D.hline){const ne=Vl((D.y??0)*f,m);return{hline:!0,x1:Vl(D.x1*d,h),x2:Vl(D.x2*d,h),y1:ne,y2:ne,level:le,start:ie,dur:ue}}const fe=Vl(D.x1*d,h),de=Vl((D.y1??0)*f,m);return{hline:!1,x1:fe,y1:de,x2:Math.max(Vl(D.x2*d,h),fe+h),y2:Math.max(Vl((D.y2??0)*f,m),de+m),level:le,start:ie,dur:ue}}),Y=W.reduce((D,G)=>Math.max(D,G.start+G.dur),0),H=u.length,J=new Float32Array(H*Fl),B=new Int16Array(H*Fl).fill(-1),Q=new Uint8Array(H),V=W[0];for(let D=0;D<H;D++){const G=u[D];G.x>V.x1&&G.x<V.x2&&G.y>V.y1&&G.y<V.y2&&(Q[D]=1);const le=D*Fl;for(let re=0;re<W.length;re++){const ie=zne(G.x,G.y,W[re]);if(ie<=.02)continue;let ue=le;for(let fe=le;fe<le+Fl;fe++){if(B[fe]===-1){ue=fe;break}J[fe]<J[ue]&&(ue=fe)}(B[ue]===-1||ie>J[ue])&&(J[ue]=ie,B[ue]=re)}}return{startT:F,buildEnd:Y,els:W,frame:V,cellQ:J,cellEl:B,inFrame:Q}},T=()=>{const F=i.getBoundingClientRect();d=Math.max(1,F.width),f=Math.max(1,F.height);const N=Math.min(2,window.devicePixelRatio||1);i.width=Math.round(d*N),i.height=Math.round(f*N),o.setTransform(N,0,0,N,0,0);const q=Math.max(8,Math.round(d/q0)),W=Math.max(6,Math.round(f/q0));h=d/q,m=f/W,u=[];for(let Y=0;Y<W;Y++){const H=W>1?Y/(W-1):.5,J=Mne*(1+One*.4*(H*2-1));for(let B=0;B<q;B++){const Q=Y*8191+B*131+1,V={x:(B+.5)*h,y:(Y+.5)*m,size:J,seed:Q,phase:G0(Q),kind:0};V.kind=Math.floor(G0(Q*97)*3),u.push(V)}}w=null,v=null},M=new Float32Array(32),I=F=>{o.fillStyle=Tne,o.fillRect(0,0,d,f),v||(v=P(F+.2)),F>=v.startT+v.buildEnd+Lne&&(w=v,_=F,v=P(F+.2));let N=0;w&&(N=1-km((F-_)/Nne),N<=0&&(w=null));const q=v;for(let V=0;V<q.els.length;V++){const D=q.els[V];M[V]=km(Math.min(1,Math.max(0,(F-q.startT-D.start)/D.dur)))}const W=M[0],Y=C(0),H=C(W),J=N>0?C(N):Y,B=N>0?C(Math.max(W,N)):H,Q=u.length;for(let V=0;V<Q;V++){const D=u[V];let G=0,le=0;const re=V*Fl;for(let De=re;De<re+Fl;De++){const Ee=q.cellEl[De];if(Ee<0)break;const ft=q.cellQ[De]*M[Ee];ft>G&&(G=ft,le=q.els[Ee].level)}if(w)for(let De=re;De<re+Fl;De++){const Ee=w.cellEl[De];if(Ee<0)break;const ft=w.cellQ[De]*N;ft>G&&(G=ft,le=w.els[Ee].level)}const ie=F/Rne+D.phase,ue=Math.floor(ie),fe=ie-ue,de=km(Math.min(fe,1-fe)/Ine),ne=Math.floor(G0(D.seed*97+ue*7919)*3);ne!==D.kind&&G<.02&&de<.05&&(D.kind=ne);const Ce=Math.max(de*(1-G),G);if(!(Ce<.01))if(G<.02){const De=q.inFrame[V]===1,Ee=w?w.inFrame[V]===1:!1;De?o.fillStyle=Ee?B:H:o.fillStyle=Ee?J:Y;const ft=Math.max(De?W:0,Ee?N:0);yA(o,D.kind,D.x,D.y,D.size*Ce*(1-.2*ft))}else{o.fillStyle=k(G);const De=1+(jne[le]-1)*G;yA(o,D.kind,D.x,D.y,D.size*Ce*De)}}};T();let R=0;if(l)v=P(-100),I(0);else{const F=performance.now(),N=q=>{I((q-F)/1e3),R=requestAnimationFrame(N)};R=requestAnimationFrame(N)}const L=new ResizeObserver(()=>{T(),l&&(v=P(-100),I(0))});L.observe(i),r.current=()=>{cancelAnimationFrame(R),L.disconnect(),e&&n(F=>F-1)}},[e,n]);return S.jsx("canvas",{ref:s,"aria-hidden":"true",className:`h-full w-full ${t}`.trim()})},_A={kind:"base"};function wA(t){return t.kind==="base"?"base":`variant:${t.sessionId}:${t.variantId}`}const Une=async(t=null)=>{if(t)return Bne(t);let e;try{e=await bt("/api/mcp/status")}catch{return{isOk:!1,unavailableReason:"rivet_unreachable",upstreamStatus:null}}if(e.status===404||!(e.headers.get("content-type")??"").toLowerCase().includes("application/json"))return K0();if(!e.ok)return{isOk:!1,unavailableReason:"rivet_unreachable",upstreamStatus:null};let r;try{r=await e.json()}catch{return K0()}const s=r.devServerHealth;return s?s.ownership==="none"?{isOk:!1,unavailableReason:"upstream_unreachable",upstreamStatus:null}:s.isReachable===!0?{isOk:!0,unavailableReason:"upstream_unreachable",upstreamStatus:null}:{isOk:!1,unavailableReason:s.reason==="rivet_unreachable"?"rivet_unreachable":"upstream_unreachable",upstreamStatus:null}:K0()},eL=async t=>{try{const e=await fetch(t);return{isOk:e.status!==502&&e.status!==503,unavailableReason:"upstream_unreachable",upstreamStatus:e.status}}catch{return{isOk:!1,unavailableReason:"rivet_unreachable",upstreamStatus:null}}},Bne=t=>eL(t),K0=()=>eL("/"),V_=Ls("usePreviewUpstreamHealth"),Wne=500,Zne=4e3,qne=15e3,Gne=3,Kne=(t,e={})=>{const n=g.useRef(null),r=g.useRef(null),s=e.probeMsWhileDown??Wne,i=e.probeMsWhileUp??Zne,o=e.firstUnreachableCaptureAfterMs??qne,l=e.rerunProbeImmediatelyOnVersion,u=e.probePath??null,d=e.skip??!1,f=g.useRef(e.onPersistentUpstreamServerErrors);f.current=e.onPersistentUpstreamServerErrors;const[h,m]=g.useState(t==="static"),[v,w]=g.useState(0),[_,x]=g.useState(null),[b,k]=g.useState(0),[C,P]=g.useState(!1),[T,M]=g.useState(!1),[I,R]=g.useState(t==="static"?null:"upstream_unreachable");return g.useEffect(()=>{if(t==="static"){m(!0),x(null),k(0),P(!1),M(!0),R(null);return}if(d){m(!1),x(null),k(0),P(!1),M(!0),R("upstream_unreachable"),n.current=null;return}let L=!0;const j=Date.now();x(j),k(0),P(!1),m(!1),M(!1),R("upstream_unreachable");const F={current:!1},N={current:!1},q={current:!1},W={current:null},Y={current:!1},H={current:!1},J={current:0},B={current:!1},Q={current:null};let V=null;const D=()=>{q.current||(q.current=!0,L&&M(!0))},G=()=>{V!==null&&(clearTimeout(V),V=null)},le=(ie,ue)=>{G(),V=setTimeout(ue,ie)},re=async()=>{var ft;if(!L)return;k(At=>At+1);const{isOk:ie,unavailableReason:ue,upstreamStatus:fe}=await Une(u);if(!L)return;D(),Q.current=fe;const de=ie&&fe!==null&&fe>=500;de&&H.current?J.current+=1:ie&&!de&&(J.current=0);const ne=J.current>=Gne;if(ne&&!B.current&&fe!==null&&(B.current=!0,$e==null||$e.capture("preview_upstream_error_responses",{framework:t,upstream_status:fe,consecutive_count:J.current}),V_.warn(`Preview upstream is listening but has served ${J.current} consecutive ${fe} responses`),(ft=f.current)==null||ft.call(f,{upstreamStatus:fe,consecutiveCount:J.current})),ie&&!ne){de||(H.current=!0,B.current=!1);const At=!Y.current;Y.current=!0,m(!0),R(null),W.current=null,N.current=!1,P(!1),F.current?At&&($e==null||$e.capture("preview_upstream_restored",{framework:t})):(F.current=!0,$e==null||$e.capture("preview_dev_server_ready",{framework:t,ready_after_ms:Date.now()-j})),le(i,re);return}const De=Y.current;Y.current=!1,m(!1),R(ue),W.current===null&&(W.current=Date.now(),N.current=!1,P(!1)),De&&($e==null||$e.capture("preview_upstream_lost",{framework:t,upstream_status:fe}),w(At=>At+1),V_.warn("Preview upstream became unavailable after it was ready"));const Ee=Date.now()-W.current;Ee>=o&&!N.current&&(N.current=!0,P(!0),$e==null||$e.capture("preview_dev_server_unreachable",{framework:t,elapsed_ms:Ee,upstream_status:Q.current}),V_.warn("Dev server did not become ready within timeout window")),le(s,re)};return n.current=()=>le(0,re),le(0,re),()=>{L=!1,n.current=null,G()}},[t,s,i,o,u,d]),g.useEffect(()=>{var j;if(t==="static"||l===void 0)return;const L=r.current;r.current=l,L!==null&&L!==l&&((j=n.current)==null||j.call(n))},[t,l]),{isUpstreamReady:h,iframeRemountKey:v,probeStartedAt:_,probeAttemptCount:b,isFirstUnreachableWindowExceeded:C,initialProbeComplete:T,unavailableReason:I}};function Yne(t){return t.enteringSplit&&t.isExistingSession&&t.hasActiveVariantProxy}const tL=t=>{var r;if(typeof window>"u")return"";const e=(r=window.__RIVET_BOOTSTRAP__)==null?void 0:r.previewOrigin;if(e)return e;const n=new URL(window.location.origin);return n.hostname="localhost",n.origin},lx=({agentApplyMode:t,url:e})=>e.startsWith("/")?`${tL()}${e}`:e,Xne="allow-scripts allow-same-origin allow-forms allow-popups allow-modals",Qne=t=>Xne,Jne=Ls("PreviewSurface"),Rf=(t,e)=>t==="about:blank"?"blank":t.includes("/api/variants/")?"static_artifact":e.kind==="variant"?"dev_server":"original",cx=({target:t,src:e,framework:n,remountKey:r,isActive:s=!0})=>{dt(wv);const i=si(),o=g.useRef(!1),l=g.useRef(s),u=g.useCallback(f=>{t.kind==="variant"&&(i==null||i.capture("variants_panel.preview_displayed",{sessionId:t.sessionId,variantId:t.variantId,renderedTarget:"variant",iframeSrcKind:Rf(e,t),framework:n,isReused:f}))},[n,i,e,t]),d=g.useCallback(f=>{f&&(s&&!l.current&&o.current&&u(!0),l.current=s)},[u,s]);return S.jsx("div",{ref:d,className:"relative h-full w-full",children:S.jsx("iframe",{src:e,className:"h-full w-full border-none",title:s?"Project Preview":"Retained Project Preview",tabIndex:s?void 0:-1,sandbox:Qne(),onLoad:()=>{o.current=!0,i==null||i.capture("preview_iframe_loaded",{framework:n,src_kind:Rf(e,t)}),s&&u(!1)},onError:()=>{i==null||i.capture("preview_iframe_load_failed",{framework:n,src_kind:Rf(e,t)}),s&&t.kind==="variant"&&(i==null||i.capture("variants_panel.preview_display_failed",{sessionId:t.sessionId,variantId:t.variantId,renderedTarget:"variant",iframeSrcKind:Rf(e,t),framework:n})),Jne.warn("Preview iframe failed to load",{framework:n,src_kind:Rf(e,t)})}},r)})},ere=7,tre=t=>{const e=wA(t.target),n=`${e}:${t.src}`,r=t.src==="about:blank",[s,i]=g.useState(()=>({selectedKey:n,remountKey:t.remountKey,selection:0,frames:r?[]:[{key:n,props:t,lastSelected:0}]}));if(s.selectedKey!==n||s.remountKey!==t.remountKey){const o=s.selection+1,l=s.remountKey!==t.remountKey;let u=s.frames.filter(d=>!l||wA(d.props.target)!==e);if(!r){const d=u.find(f=>f.key===n);if(d?u=u.map(f=>f===d?{...f,lastSelected:o}:f):u=[...u,{key:n,props:t,lastSelected:o}],u.length>ere){const f=u.reduce((h,m)=>m.lastSelected<h.lastSelected?m:h);u=u.filter(h=>h!==f)}}i({selectedKey:n,remountKey:t.remountKey,selection:o,frames:u})}return S.jsxs("div",{className:"relative h-full w-full",children:[s.frames.map(o=>{const l=!r&&o.key===n;return S.jsx("div",{className:"absolute inset-0",style:{visibility:l?"visible":"hidden",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:S.jsx(cx,{...o.props,isActive:l})},`${o.key}:${o.props.remountKey??""}`)}),r?S.jsx(cx,{...t}):null]})},nre=g.lazy(()=>h5(()=>Promise.resolve().then(()=>jse),void 0)),rre={surface:"relative flex h-full w-full items-center justify-center bg-main px-6",overlay:"absolute inset-0 z-10 flex items-center justify-center bg-main/90 px-6",page:"relative flex h-screen w-full items-center justify-center bg-main px-6"},sre={sm:"text-lg font-semibold text-content",md:"text-2xl font-semibold text-content",lg:"text-3xl font-semibold text-content"},ire={neutral:"rounded-md border border-divider bg-transparent px-5 py-2 text-sm font-medium text-content transition-colors hover:bg-surface-3",ghost:"rounded-md px-5 py-2 text-sm font-medium text-content-muted transition-colors hover:text-content"},mc=({backdrop:t,media:e,title:n,description:r,actions:s,tone:i="neutral",fill:o="surface",size:l="md",children:u,state:d,role:f="status",busy:h=!1,className:m=""})=>{const v=g.useCallback(_=>{_&&d&&($e==null||$e.capture("status_surface_shown",{state:d,tone:i,fill:o}))},[d,i,o]),w=!!(e||n||r||u||s!=null&&s.length);return S.jsxs("div",{ref:v,className:`${rre[o]} ${m}`.trim(),role:f,"aria-live":"polite","aria-busy":h||void 0,"data-state":d,children:[t?S.jsx("div",{className:"absolute inset-0",children:t}):null,w?S.jsxs("div",{className:"relative z-10 flex max-w-sm flex-col items-center gap-5 text-center",children:[e,n?S.jsx("h2",{className:sre[l],children:n}):null,r?S.jsx("p",{className:"text-content-muted text-base leading-relaxed",children:r}):null,u,s!=null&&s.length?S.jsx("div",{className:"flex flex-row items-center gap-3",children:s.map(_=>S.jsx("button",{type:"button",onClick:_.onClick,className:ire[_.variant??"neutral"],children:_.label},_.label))}):null]}):null]})},ux=({loader:t="coalesce",trackGlobalLoaderCount:e,size:n="lg",...r})=>t==="coalesce"?S.jsx(mc,{...r,size:n,busy:!0,backdrop:S.jsx(J9,{trackGlobalLoaderCount:e})}):t==="logo"?S.jsx(mc,{...r,size:n,busy:!0,backdrop:S.jsx(g.Suspense,{fallback:null,children:S.jsx(nre,{className:"absolute inset-0"})})}):S.jsx(mc,{...r,size:n,busy:!0,media:S.jsx(tv,{"aria-hidden":!0,className:"text-content h-8 w-8 shrink-0 animate-spin",weight:"bold"})}),nL=({icon:t,...e})=>S.jsx(mc,{...e,tone:"neutral",media:t?S.jsx("div",{className:"text-content-muted",children:t}):void 0}),CS=t=>S.jsx(mc,{...t,tone:"error",role:"alert"}),xA="/static/",ore=t=>{try{return new URL(t,"http://localhost").pathname.endsWith(xA)}catch{return t.endsWith(xA)}},are=t=>t==="spawn_error"?"The direction is saved, but its preview process didn’t start.":t==="exited"?"The direction is saved, but its preview stopped before it was ready.":t==="timeout"?"The direction is saved, but its preview took too long to become ready.":t==="dependency_install_failed"?"The direction is saved, but its dependencies couldn’t be prepared. Fix the installation error, then retry the preview.":t==="compile_error"?"The direction is saved, but its app couldn’t compile. Fix the app error, then retry the preview.":t==="missing_dev_script"?"The direction is saved, but Rivet couldn’t find a dev script to preview it.":t==="missing_static_entry"?"The direction is saved, but Rivet couldn’t find an HTML entry to preview it.":"The direction is saved, but Rivet couldn’t prepare its preview.",lre=t=>{if(t.status==="failed"&&t.errorCode==="VARIANT_VERIFICATION_UNAVAILABLE")return{state:"variant_verification_unavailable",title:"Rivet couldn’t verify this direction",description:"The worker completed, but Rivet couldn’t inspect its generated files.",detail:t.errorMessage??t.errorCode,isError:!0};if(t.status==="failed"&&t.errorCode==="VARIANT_QA_FAILED")return{state:"variant_output_integrity_failed",title:"This direction couldn’t be verified",description:"The worker completed, but Rivet found a structural problem in the generated files.",detail:t.errorMessage??t.errorCode,isError:!0};if(t.status==="failed")return{state:"variant_worker_failed",title:"This direction didn’t complete",description:"The worker stopped before producing a usable result.",detail:t.errorMessage??t.errorCode,isError:!0};if(t.status==="cancelled")return{state:"variant_cancelled",title:"Direction was cancelled",description:"Rivet stopped before a preview was ready. Your other directions are unchanged.",isError:!1};if(t.status==="succeeded"&&t.previewUnavailable&&t.previewUnavailable.reason!=="idle_timeout"){const e=t.previewUnavailable.portInUse?"The preview port was already in use.":void 0;return{state:"preview_unavailable",title:"Rivet couldn’t preview this direction",description:are(t.previewUnavailable.reason),detail:t.previewUnavailable.detail??e,isError:!0}}return null},cre=({issue:t,retryTarget:e})=>{const n=si(),r=g.useRef(!1),[s,i]=g.useState(!1),[o,l]=g.useState(null),u=async()=>{if(!(!e||r.current)){r.current=!0,i(!0),l(null),n==null||n.capture("preview_retry_clicked",{session_id:e.sessionId,variant_id:e.variantId});try{const d=await bt(`/api/variants/${encodeURIComponent(e.sessionId)}/preview-port`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({variantId:e.variantId,retry:!0})});if(!d.ok){const f=yn({message:Ke().optional()}).safeParse(await d.json().catch(()=>({}))),h=f.success?f.data:{};throw new Error(h.message??"The preview could not restart. Try again.")}}catch(d){l(Rr(d,"The preview could not restart. Try again."))}finally{r.current=!1,i(!1)}}};return S.jsxs(mc,{fill:"overlay",size:"sm",state:t.state,role:t.isError?"alert":"status",tone:t.isError?"error":"neutral",title:t.title,description:t.description,busy:s,actions:e&&!s?[{label:"Retry preview",onClick:()=>void u()}]:void 0,children:[s?S.jsx("p",{className:"text-content-subtle text-xs",children:"Starting preview…"}):null,o?S.jsx("p",{className:"text-content-subtle text-xs",children:o}):null,t.detail?S.jsx("p",{"data-rivet-private":!0,className:"ph-no-capture text-content-subtle max-h-40 overflow-auto text-xs leading-relaxed break-words whitespace-pre-wrap",children:t.detail}):null]})},ure=({isInteractionDisabled:t=!1,framework:e,userPort:n})=>{var sn;const r=dt(yv),s=dt(Xw),i=yt(Xw),o=dt(Tg),l=yt(Tg),u=dt(op),d=dt(wv),f=dt(Qw),h=dt(Jw),m=dt(k9),v=dt(E9),w=yt(Jw),_=dt(rl),x=dt(Sm),b=yt(Qw),k=u.active&&u.projectContext.kind==="fresh",C=dt(ex),P=u.active?u.variants.find(Re=>Re.workItemId===C&&(Re.status==="pending"||Re.status==="running"||Re.status==="succeeded"&&!Re.preview&&typeof Re.port!="number"&&(!Re.previewUnavailable||Re.previewUnavailable.reason==="idle_timeout")))??null:null,T=u.active&&u.variants.some(Re=>Re.status==="pending"||Re.status==="running"),M=k||T,I=u.active?u.variants.find(Re=>Re.workItemId===C)??null:null,R=I?lre(I):null,L=e==="static"&&o!==null&&ore(o);g.useEffect(()=>{u.active||b(!1)},[u.active,b]);const j=g.useRef(!1);g.useEffect(()=>{const Re=!!(_!=null&&_.left||_!=null&&_.right),it=Re&&!j.current;j.current=Re;const Fe=u.active?u.sessionId:null;!Fe||!Yne({enteringSplit:it,isExistingSession:u.active&&u.projectContext.kind==="existing",hasActiveVariantProxy:f&&h!==null})||(b(!1),w(null),i(Qe=>Qe+1),bt(`/api/variants/${encodeURIComponent(Fe)}/preview-port`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({variantId:null})}).catch(()=>{}))},[_,u,f,h,b,w,i]);const N=g.useMemo(()=>{var ut;if(f||o&&!L||!u.active)return null;const{stage:Re,variants:it}=u,Fe=Re==="ready"||Re==="degraded",Qe=it.some(Ot=>{var Dn,Ie;return((Dn=Ot.refinement)==null?void 0:Dn.status)==="pending"||((Ie=Ot.refinement)==null?void 0:Ie.status)==="running"});if(!Fe&&!Qe)return null;const Ye=it.find(Ot=>{var Dn;return Ot.status==="succeeded"&&((Dn=Ot.preview)==null?void 0:Dn.kind)==="static_artifact"});return((ut=Ye==null?void 0:Ye.preview)==null?void 0:ut.kind)==="static_artifact"?pc({sessionId:u.sessionId,variant:Ye,projectContext:u.projectContext}):null},[L,o,f,u])??o,q=g.useMemo(()=>!u.active||!N?null:u.variants.find(Re=>{var it;return((it=Re.preview)==null?void 0:it.kind)==="static_artifact"&&N.startsWith(Re.preview.url)})??null,[N,u]),W=g.useMemo(()=>{if((x==null?void 0:x.previewKind)==="static"||(x==null?void 0:x.previewKind)==="dev_server"&&x.previewError||(x==null?void 0:x.previewKind)==="dev_server"&&N&&GP(N))return{kind:"variant",sessionId:x.sessionId,variantId:x.variantId};if(!u.active)return _A;if(q)return{kind:"variant",sessionId:u.sessionId,variantId:q.workItemId};if(N){const it=N.match(/\/__rivet\/preview\/variant\/([^/]+)\/([^/?#]+)/),Fe=it!=null&&it[1]?decodeURIComponent(it[1]):null,Qe=it!=null&&it[2]?decodeURIComponent(it[2]):null;if(Fe===u.sessionId&&Qe&&u.variants.some(Ot=>Ot.workItemId===Qe))return{kind:"variant",sessionId:u.sessionId,variantId:Qe};const Ye=N.match(/\/api\/variants\/[^/]+\/static\/([^/?#]+)/),ut=Ye!=null&&Ye[1]?decodeURIComponent(Ye[1]):null;if(ut&&u.variants.some(Ot=>Ot.workItemId===ut))return{kind:"variant",sessionId:u.sessionId,variantId:ut}}const Re=!!(_!=null&&_.left||_!=null&&_.right);return(!Re||k)&&!N&&f&&h&&u.variants.some(it=>it.workItemId===h)?{kind:"variant",sessionId:u.sessionId,variantId:h}:(!Re||k)&&!N&&C&&u.variants.some(it=>it.workItemId===C)?{kind:"variant",sessionId:u.sessionId,variantId:C}:_A},[x,q,u,f,h,N,_,k,C]),Y=g.useRef(null);g.useEffect(()=>{var Qe,Ye,ut;if(!q||((Qe=q.preview)==null?void 0:Qe.kind)!=="static_artifact"||((Ye=q.refinement)==null?void 0:Ye.status)!=="succeeded")return;const Re=`${q.workItemId}:${q.refinement.workItemId}`;if(Y.current===Re)return;if(Y.current=Re,(ut=q.previewRoutes)!=null&&ut.length){i(Ot=>Ot+1);return}const it=q.preview.url.includes("?")?"&":"?",Fe=`${q.preview.url}${it}refinement=${encodeURIComponent(q.refinement.workItemId)}`;N!==Fe&&(l(Fe),i(Ot=>Ot+1))},[N,q,i,l,u]);const H=N!==null&&GP(N),J=N!==null&&!H||k&&!f&&!H,{isUpstreamReady:B,iframeRemountKey:Q,probeAttemptCount:V,initialProbeComplete:D}=Kne(e,{rerunProbeImmediatelyOnVersion:s,probePath:H?N:null,skip:J}),[G,le]=g.useState(()=>m&&B?s:null),re=g.useRef(null);g.useEffect(()=>{if(!m){re.current=null,le(null);return}if(G===s){re.current=null;return}const Re=re.current;if(!Re||Re.remountKey!==s){re.current={remountKey:s,probeAttemptCount:V};return}B&&V>Re.probeAttemptCount&&(re.current=null,le(s))},[G,s,m,V,B]);const ue=N!==null&&!H||B,de=v||m&&!H&&G!==s||m&&!ue,ne=`${Q}:${s}`,Ce=N9(window.location.pathname),De=e==="static"?`/static${Ce??"/"}`:Ce??"/",Ee=tL();let ft=null;N&&(ft=lx({agentApplyMode:d,url:N}));const At=H&&!ue?"about:blank":ft,zt=P||R||x!=null&&x.previewError||de?"about:blank":At??(ue?`${Ee}${De}`:"about:blank"),wt=!!P||!!R||!ue&&D;let Tt=null;if(x!=null&&x.previewError)Tt=S.jsx(mc,{fill:"overlay",size:"sm",state:"preview_replay_failed",role:"alert",tone:"error",title:"Rivet couldn’t preview this direction",description:"Select the direction again to retry.",children:S.jsx("p",{className:"text-content-subtle text-xs leading-relaxed break-words",children:x.previewError})});else if(de)Tt=S.jsx(ux,{fill:"overlay",loader:"coalesce",trackGlobalLoaderCount:!1,state:"preview_replay_boot"});else if(P)Tt=S.jsx(ux,{fill:"overlay",loader:"coalesce",trackGlobalLoaderCount:!1,state:"variant_building",children:S.jsx("span",{className:"sr-only",children:"Building your direction"})});else if(R){const Re=u.active&&I&&R.state==="preview_unavailable"&&((sn=I.previewUnavailable)==null?void 0:sn.reason)!=="missing_static_entry"?{sessionId:u.sessionId,variantId:I.workItemId}:void 0;Tt=S.jsx(cre,{issue:R,retryTarget:Re},I==null?void 0:I.workItemId)}else wt&&(Tt=M?S.jsx(nL,{fill:"overlay",state:"preview_no_selection",title:"Nothing to preview yet",description:"Pick a direction from the panel."}):S.jsx(CS,{fill:"overlay",state:"preview_offline",title:"Preview isn't connected",description:"Rivet lost connection to your project.",actions:[{label:"Reload",onClick:()=>window.location.reload()}]}));return S.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-col",children:S.jsxs("div",{className:"relative min-h-0 flex-1",children:[Tt,S.jsx(tre,{target:W,src:zt,framework:e,remountKey:ne},r)]})})};function bA({side:t,sessionId:e,variantId:n,url:r,label:s,source:i,isFallback:o=!1}){var C;const l=dt(rl),u=yt(rl),d=si(),f=dt(op),h=dt(wv),m=g.useRef(!1),v=g.useCallback(()=>{m.current||(m.current=!0,vd({source:i,sessionId:e,variantId:n}))},[i,e,n]),w=g.useCallback(()=>{if(o){u(null);const I=Rg("ended",l);d==null||d.capture(I.event,I.properties);return}v();const P={...l};delete P[t];const T=P.left||P.right?P:null;u(T);const M=Rg(T?"updated":"ended",T??l);d==null||d.capture(M.event,M.properties)},[o,d,u,t,l,v]),_=g.useMemo(()=>({kind:"variant",sessionId:e,variantId:n}),[e,n]),x=g.useMemo(()=>!f.active||f.sessionId!==e?null:f.variants.find(P=>P.workItemId===n)??null,[e,n,f]),b=g.useMemo(()=>{var T,M,I;let P=r;if(((T=x==null?void 0:x.preview)==null?void 0:T.kind)==="static_artifact"&&((M=x.refinement)==null?void 0:M.status)==="succeeded"){if((I=x.previewRoutes)!=null&&I.length)return lx({agentApplyMode:h,url:pc({sessionId:e,variant:x,projectContext:null})??r});const R=x.preview.url.includes("?")?"&":"?";P=`${x.preview.url}${R}refinement=${encodeURIComponent(x.refinement.workItemId)}`}return lx({agentApplyMode:h,url:P})},[h,x,e,r]),k=((C=x==null?void 0:x.refinement)==null?void 0:C.status)==="succeeded"?`${n}:${x.refinement.workItemId}`:n;return S.jsxs("div",{className:"variant-split-secondary","data-cy":"variant-split-pane","data-variant-id":n,children:[S.jsxs("div",{className:"variant-split-secondary-toolbar",children:[S.jsx("span",{className:"variant-split-secondary-label",title:s,children:s}),S.jsx(Tc,{label:"Collapse",children:S.jsx("button",{type:"button",className:"variant-split-secondary-close",onClick:w,"aria-label":"Collapse split view",children:S.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12","aria-hidden":"true",focusable:"false",children:S.jsx("path",{d:"M2.5 2.5 L9.5 9.5 M9.5 2.5 L2.5 9.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})})})]}),S.jsx("div",{className:"variant-split-secondary-body relative min-h-0 flex-1",children:S.jsx(cx,{target:_,src:b,framework:"static",remountKey:k})})]})}function dre(){const t=dt(gd),e=dt(SS);return!t||!e?null:np.createPortal(S.jsx("div",{"aria-hidden":"true",className:"border-main-border bg-main pointer-events-none fixed top-0 left-0 z-[70] flex max-w-60 items-center gap-2 rounded-md border px-3 py-1.5 shadow-lg",style:{transform:`translate3d(${e.x+12}px, ${e.y+12}px, 0)`},children:S.jsx("span",{className:"text-content truncate text-sm font-medium",children:t.label})}),document.body)}function fre(){const t=dt(gd),e=dt(SS),n=dt(rl),r=yt(gd),s=yt(rl),i=si(),o=g.useRef(null),[l,u]=g.useState(null),[d,f]=g.useState("hidden");g.useEffect(()=>{t||(f("hidden"),u(null))},[t]);const h=g.useCallback((v,w)=>{const _=o.current;if(!_)return null;const x=_.getBoundingClientRect();return v<x.left||v>x.right||w<x.top||w>x.bottom?null:v<(x.left+x.right)/2?"left":"right"},[]);if(g.useEffect(()=>{if(!t||!e)return;const v=h(e.x,e.y);u(w=>w===v?w:v),f(w=>{if(w==="exiting")return w;const _=v!==null?"visible":"hidden";return w===_?w:_})},[t,e,h]),g.useEffect(()=>{if(!t)return;const v=w=>{const _=h(w.clientX,w.clientY);if(_&&t.url){const x={sessionId:t.sessionId,variantId:t.variantId,label:t.label,url:t.url,source:t.source},b=n==null?void 0:n[_];b&&(b.sessionId!==x.sessionId||b.variantId!==x.variantId)&&vd(b);const k={...n??{},[_]:x};s(k);const C=Rg(n?"updated":"started",k);i==null||i.capture(C.event,C.properties),f("exiting"),window.setTimeout(()=>r(null),220)}else vd(t),f("exiting"),window.setTimeout(()=>r(null),220)};return window.addEventListener("pointerup",v),window.addEventListener("pointercancel",v),()=>{window.removeEventListener("pointerup",v),window.removeEventListener("pointercancel",v)}},[t,h,i,r,s,n]),!t)return null;const m=["variant-drop-zones",d==="visible"&&"is-visible",d==="exiting"&&"is-exiting"].filter(Boolean).join(" ");return S.jsxs("div",{ref:o,className:m,"aria-hidden":"true",children:[S.jsx(SA,{side:"left",hovered:l==="left",canDrop:!!t.url,label:t.label}),S.jsx(SA,{side:"right",hovered:l==="right",canDrop:!!t.url,label:t.label})]})}function SA({side:t,hovered:e,canDrop:n,label:r}){return S.jsxs("div",{className:["variant-drop-zone",`is-${t}`,e&&"is-hover",!n&&"is-disabled"].filter(Boolean).join(" "),children:[S.jsxs("div",{className:"variant-drop-zone-inner",children:[S.jsx("div",{className:`variant-drop-zone-icon is-${t}`}),S.jsx("div",{className:"variant-drop-zone-caption",children:n?`Add ${t} split`:"Split unavailable for this direction"})]}),S.jsx("div",{className:"variant-drop-zone-preview","aria-hidden":"true",children:S.jsx("div",{className:"variant-drop-zone-preview-label",children:r})}),S.jsx("div",{className:"variant-drop-zone-border"})]})}const rL=(t,e,n)=>{var i,o,l;if(!t.active||t.sessionId!==e)return null;const r=t.variants.find(u=>u.workItemId===n);if(((i=r==null?void 0:r.preview)==null?void 0:i.kind)!=="static_artifact")return null;if((o=r.previewRoutes)!=null&&o.length)return pc({sessionId:e,variant:r,projectContext:t.projectContext});if(((l=r.refinement)==null?void 0:l.status)!=="succeeded")return r.preview.url;const s=r.preview.url.includes("?")?"&":"?";return`${r.preview.url}${s}refinement=${encodeURIComponent(r.refinement.workItemId)}`},kA=(t,e)=>{if(!t)return;const n=rL(e,t.sessionId,t.variantId);return!n||n===t.url?t:{...t,url:n}},hre=()=>S.jsx("div",{"data-testid":"preview-boot-skeleton",role:"status","aria-busy":"true","aria-label":"Loading preview",className:"bg-main flex h-full min-h-0 w-full flex-1 flex-col p-3",children:S.jsx("div",{className:"border-main-border relative min-h-0 flex-1 overflow-hidden rounded-lg border",children:S.jsx(J9,{trackGlobalLoaderCount:!1})})}),pre=({isLoading:t=!1,isInteractionDisabled:e=!1})=>{const{config:n,fetchConfig:r,isLoading:s,error:i}=Ane();return g.useEffect(()=>{r().catch(o=>{$e==null||$e.capture("preview_config_load_failed",{message:Rr(o,"unknown_error"),attempts:mA})})},[r]),s?S.jsx(hre,{}):i||!n?S.jsx(CS,{fill:"surface",size:"sm",state:"preview_config_error",title:"Couldn't load preview",description:"We couldn't load the preview configuration.",actions:[{label:"Retry",onClick:()=>{$e==null||$e.capture("preview_config_retry_clicked"),r().catch(o=>{$e==null||$e.capture("preview_config_load_failed",{message:Rr(o,"unknown_error"),attempts:mA})})}}]}):S.jsx(mre,{isLoading:t,isInteractionDisabled:e,framework:n.framework,userPort:n.userPort})};function mre(t){const e=dt(rl),n=dt(gd),r=dt(op),s=dt(Tg),i=e==null?void 0:e.left,o=e==null?void 0:e.right,l=g.useMemo(()=>{var T,M;if(!r.active||r.projectContext.kind!=="fresh"||!(!!i!=!!o))return;const _=(T=i??o)==null?void 0:T.variantId,x=r.variants.filter(I=>{var R;return I.status==="succeeded"&&((R=I.preview)==null?void 0:R.kind)==="static_artifact"&&I.workItemId!==_}),b=s==null?void 0:s.replace(/[?&]refinement=[^&]*$/,""),C=x.find(I=>{var R;return((R=I.preview)==null?void 0:R.kind)==="static_artifact"&&(I.preview.url===b||pc({sessionId:r.sessionId,variant:I,projectContext:r.projectContext})===s)})??x[0];if(((M=C==null?void 0:C.preview)==null?void 0:M.kind)!=="static_artifact")return;const P=rL(r,r.sessionId,C.workItemId);if(P)return{sessionId:r.sessionId,variantId:C.workItemId,label:C.label,url:P,source:"live"}},[r,i,o,s]),u=kA(i,r)??(o?l:void 0),d=kA(o,r)??(i?l:void 0),f=!i&&!!u,h=!o&&!!d,m=!!(u||d),v=S.jsx(ure,{isInteractionDisabled:t.isInteractionDisabled,framework:t.framework,userPort:t.userPort});return S.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 flex-col",children:S.jsxs("div",{className:`variant-preview-region relative flex h-full min-h-0 w-full flex-1 flex-col ${n?"is-dragging":""} ${m?"is-split":""}`,children:[S.jsxs("div",{className:"variant-preview-row flex h-full min-h-0 w-full flex-1",children:[u&&S.jsx(bA,{side:"left",sessionId:u.sessionId,variantId:u.variantId,url:u.url,label:u.label,source:u.source,isFallback:f},`left-${u.sessionId}:${u.variantId}:${u.url}`),S.jsx("div",{className:"variant-preview-primary flex h-full min-h-0 flex-1 flex-col",style:{display:u&&d?"none":void 0},"aria-hidden":!!(u&&d),children:v}),d&&S.jsx(bA,{side:"right",sessionId:d.sessionId,variantId:d.variantId,url:d.url,label:d.label,source:d.source,isFallback:h},`right-${d.sessionId}:${d.variantId}:${d.url}`)]}),S.jsx("div",{className:"variant-preview-atmosphere","aria-hidden":"true"}),S.jsx(fre,{}),S.jsx(dre,{})]})})}function Lo(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function sL(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}/*!
|
|
142
142
|
* GSAP 3.15.0
|
|
143
143
|
* https://gsap.com
|
|
144
144
|
*
|
|
@@ -435,5 +435,5 @@ function useAtomValueWithDelay<Value>(
|
|
|
435
435
|
*
|
|
436
436
|
* This source code is licensed under the ISC license.
|
|
437
437
|
* See the LICENSE file in the root directory of this source tree.
|
|
438
|
-
*/const iD={name:"x",size:24,node:[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]};iD.node;const Yoe=ct(iD),Xoe={"chevron-right":foe,"chevron-down":doe,pipette:Noe,x:Yoe,copy:moe,menu:Poe,dot:goe,monitor:Toe,sun:qoe,moon:Roe,"rectangle-horizontal":$oe,circle:hoe,"square-library":Woe,clock:poe,star:Zoe,settings:zoe,plus:joe,"arrow-left":ioe,"arrow-right":ooe,"arrow-up":aoe,search:Hoe,loader:koe,users:Koe,lock:Eoe,mail:Coe,bell:loe,shield:Uoe,palette:Moe,lightbulb:boe,rocket:Foe,heart:yoe,paintbrush:Ioe,brain:coe,globe:voe,user:Goe,image:woe,link:Soe,check:uoe,"rotate-ccw":Voe,play:Doe,pause:Ooe,home:_oe,"message-circle":Aoe,inbox:xoe,pencil:Loe,"skip-forward":Boe},KA={lucide:Xoe},oD=g.createContext(null);function Qoe(t){const e=g.useContext(oD);return e?KA[e.iconLibrary][t]:KA.lucide[t]}function Joe({children:t,defaultLibrary:e="lucide"}){const[n,r]=g.useState(e),s=g.useCallback(i=>{r(i)},[]);return S.jsx(oD.Provider,{value:{iconLibrary:n,setIconLibrary:s},children:t})}const aD=g.createContext(null);function e6(){return g.useContext(aD)}const lD=g.createContext(null);function cD(){const t=g.useContext(lD);if(!t)throw new Error("AccordionTrigger/AccordionContent must be used within an AccordionItem");return t}const eae=g.forwardRef((t,e)=>{const{children:n,type:r="single",className:s,...i}=t,o=g.useRef(null),l=g.useRef(new Map),[u,d]=g.useState(new Map),{activeIndex:f,setActiveIndex:h,itemRects:m,sessionRef:v,handlers:w,registerItem:_,measureItems:x}=y9(o),b=g.useCallback((de,ne)=>{ne?l.current.set(de,ne):l.current.delete(de)},[]),k=g.useCallback(()=>{if(!o.current)return;const de=new Map;l.current.forEach((ne,Ce)=>{de.set(Ce,{top:ne.offsetTop,left:ne.offsetLeft,width:ne.offsetWidth,height:ne.offsetHeight})}),d(de)},[]),[C,P]=g.useState(()=>r==="single"?t.defaultValue??"":""),[T,M]=g.useState(()=>r==="multiple"?t.defaultValue??[]:[]),I=t.onValueChange,R=t.onValueChange,L=t.value,j=new Set(r==="multiple"?t.value??T:(()=>{const de=t.value??C;return de?[de]:[]})()),F=g.useCallback(de=>{const ne=t;ne.onValueChange?ne.onValueChange(de):P(de)},[I]),N=g.useCallback(de=>{const ne=t;ne.onValueChange?ne.onValueChange(de):M(de)},[R]),q=g.useCallback(de=>{if(r==="multiple"){const ne=t.value??T;N(ne.filter(Ce=>Ce!==de))}else F("")},[r,F,N,T,L]);g.useEffect(()=>{x(),k()},[x,k,n]);const W=[...j].join(",");g.useEffect(()=>{x(),k()},[x,k,W]);const[Y,H]=g.useState(null),J=f!==null?m[f]:null,B=Y!==null?m[Y]:null,Q=f!==null&&!u.has(f),V=rp(),{value:D,defaultValue:G,onValueChange:le,collapsible:re,type:ie,...ue}=i,fe=r==="multiple"?{type:"multiple",value:t.value??T,onValueChange:N}:{type:"single",collapsible:t.collapsible??!0,value:t.value??C,onValueChange:F};return S.jsx(aD.Provider,{value:{registerItem:_,registerFullItem:b,activeIndex:f,grouped:!0,remeasure:()=>{x(),k()},openValues:j,openItemRects:u,toggleValue:q},children:S.jsx(uN,{...fe,asChild:!0,children:S.jsxs("div",{ref:de=>{o.current=de,typeof e=="function"?e(de):e&&(e.current=de)},onMouseEnter:w.onMouseEnter,onMouseMove:de=>{const ne=o.current;if(ne){const Ce=ne.getBoundingClientRect(),De=ne.offsetHeight,Ee=Ce.height,ft=De>0?Ee/De:1,At=(de.clientY-Ce.top)/ft+ne.scrollTop;for(const[zt,wt]of u){const Tt=m[zt];if(!Tt)continue;const sn=Tt.top+Tt.height,Re=wt.top+wt.height;if(At>=sn&&At<=Re){h(null);return}}}w.onMouseMove(de)},onMouseLeave:w.onMouseLeave,onFocus:de=>{var Ce;const ne=(Ce=de.target.closest("[data-proximity-index]"))==null?void 0:Ce.getAttribute("data-proximity-index");if(ne!=null){const De=Number(ne);h(De),H(de.target.matches(":focus-visible")?De:null)}},onBlur:de=>{var ne;(ne=o.current)!=null&&ne.contains(de.relatedTarget)||(H(null),h(null))},className:Zt("relative flex flex-col gap-0.5 w-72 max-w-full",s),...ue,children:[S.jsx(As,{children:[...u.entries()].map(([de,ne])=>S.jsx(Bo.div,{className:`absolute ${V.bg} bg-accent/20 dark:bg-accent/12 pointer-events-none`,initial:!1,animate:{top:ne.top,left:ne.left,width:ne.width,height:ne.height,opacity:Q?.7:1},exit:{opacity:0,transition:{duration:.12}},transition:{top:{duration:0},left:{duration:0},width:{duration:0},height:{duration:0},opacity:{duration:.08}}},`expanded-${de}`))}),S.jsx(As,{children:J&&S.jsx(Bo.div,{className:`absolute ${V.bg} bg-hover pointer-events-none`,initial:{opacity:0,top:J.top,left:J.left,width:J.width,height:J.height},animate:{opacity:1,top:J.top,left:J.left,width:J.width,height:J.height},exit:{opacity:0,transition:{duration:.06}},transition:{...Dh.fast,opacity:{duration:.08}}},v.current)}),S.jsx(As,{children:B&&S.jsx(Bo.div,{className:`absolute ${V.focusRing} pointer-events-none z-20 border border-[#6B97FF]`,initial:!1,animate:{left:B.left-2,top:B.top-2,width:B.width+4,height:B.height+4},exit:{opacity:0,transition:{duration:.06}},transition:{...Dh.fast,opacity:{duration:.08}}})}),n]})})})});eae.displayName="AccordionGroup";const uD=g.forwardRef(({children:t,type:e="single",collapsible:n=!0,defaultValue:r,value:s,onValueChange:i,className:o,...l},u)=>{const[d,f]=g.useState(()=>e==="single"?r??"":""),[h,m]=g.useState(()=>e==="multiple"?r??[]:[]),v=new Set(e==="multiple"?s??h:(()=>{const k=s??d;return k?[k]:[]})()),w=g.useCallback(k=>{i?i(k):f(k)},[i]),_=g.useCallback(k=>{i?i(k):m(k)},[i]),x=g.useCallback(k=>{e==="multiple"?_((s??h).filter(P=>P!==k)):w("")},[e,s,h,w,_]),b=e==="multiple"?{type:"multiple",value:s??h,defaultValue:r,onValueChange:_}:{type:"single",collapsible:n,value:s??d,defaultValue:r,onValueChange:w};return S.jsx(uN,{...b,asChild:!0,children:S.jsx("div",{ref:u,className:Zt("w-72 max-w-full flex flex-col gap-0.5",o),...l,children:S.jsx(dD.Provider,{value:v,children:S.jsx(fD.Provider,{value:x,children:t})})})})});uD.displayName="Accordion";const dD=g.createContext(new Set),fD=g.createContext(()=>{}),hD=g.forwardRef(({value:t,index:e,disabled:n,children:r,className:s,...i},o)=>{const l=g.useRef(null),u=e6(),d=g.useContext(dD),f=g.useContext(fD),h=rp(),m=u!=null&&u.grouped?u.openValues.has(t):d.has(t),v=g.useRef(null),w=g.useCallback(()=>{u!=null&&u.grouped?u.toggleValue(t):f(t)},[u,f,t]);return g.useEffect(()=>{if(u!=null&&u.grouped&&e!==void 0)return u.registerItem(e,v.current),()=>u.registerItem(e,null)},[e,u]),g.useEffect(()=>{if(u!=null&&u.grouped&&e!==void 0)return m?u.registerFullItem(e,l.current):u.registerFullItem(e,null),()=>u.registerFullItem(e,null)},[e,u,m]),S.jsx(lD.Provider,{value:{index:e,value:t,isOpen:m,onToggle:w,triggerRef:v},children:S.jsxs(Uie,{ref:_=>{l.current=_,typeof o=="function"?o(_):o&&(o.current=_)},value:t,disabled:n,"data-proximity-index":e,className:Zt(!(u!=null&&u.grouped)&&"relative",s),...i,children:[!(u!=null&&u.grouped)&&S.jsx(As,{children:m&&S.jsx(Bo.div,{className:`absolute inset-0 ${h.bg} bg-accent/20 dark:bg-accent/12 pointer-events-none`,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0,transition:{duration:.06}},transition:{duration:.08}})}),r]})})});hD.displayName="AccordionItem";const pD=g.forwardRef(({children:t,className:e,...n},r)=>{const s=Qoe("chevron-right"),i=e6(),{index:o,isOpen:l,triggerRef:u}=cD(),d=rp(),[f,h]=g.useState(!1),m=i!=null&&i.grouped?i.activeIndex===o:f,v=S.jsx(Wie,{asChild:!0,children:S.jsx("div",{children:S.jsxs(Zie,{ref:r,className:Zt(`relative z-10 flex items-center gap-2.5 ${d.item} px-3 py-2 w-full cursor-pointer outline-none select-none`,!(i!=null&&i.grouped)&&"focus-visible:ring-1 focus-visible:ring-[#6B97FF] focus-visible:ring-offset-0",e),...n,children:[S.jsxs("span",{className:"inline-grid text-[13px] flex-1 text-left",children:[S.jsx("span",{className:"col-start-1 row-start-1 invisible",style:{fontVariationSettings:ah.semibold},"aria-hidden":"true",children:t}),S.jsx("span",{className:Zt("col-start-1 row-start-1 transition-[color,font-variation-settings] duration-80",l||m?"text-foreground":"text-muted-foreground"),style:{fontVariationSettings:l?ah.semibold:ah.normal},children:t})]}),S.jsx(Bo.span,{className:"shrink-0 inline-flex items-center justify-center",animate:{rotate:l?90:0},transition:Dh.fast,children:S.jsx(s,{size:16,strokeWidth:l||m?2:1.5,className:Zt("transition-[color,stroke-width] duration-80",l||m?"text-foreground":"text-muted-foreground")})})]})})});return i!=null&&i.grouped?S.jsx("div",{ref:u,children:v}):S.jsxs("div",{className:"relative",onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),children:[S.jsx(As,{children:f&&S.jsx(Bo.div,{className:`absolute inset-0 ${d.bg} bg-hover pointer-events-none`,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0,transition:{duration:.06}},transition:{duration:.08}})}),v]})});pD.displayName="AccordionTrigger";const mD=g.forwardRef(({children:t,className:e,...n},r)=>{const s=e6(),{isOpen:i}=cD();return S.jsx(As,{initial:!1,children:i&&S.jsx(Gie,{forceMount:!0,asChild:!0,...n,children:S.jsx(Bo.div,{ref:r,className:Zt("overflow-hidden",e),initial:{height:0},animate:{height:"auto"},exit:{height:0},transition:{...Dh.moderate,bounce:0},onUpdate:()=>{s==null||s.remeasure()},onAnimationComplete:()=>{s==null||s.remeasure()},children:S.jsx("div",{className:"px-3 pb-3 pt-1 text-[13px] text-muted-foreground",children:t})})})})});mD.displayName="AccordionContent";const Im=({children:t,defaultValue:e=[],className:n=""})=>S.jsx(uD,{type:"multiple",defaultValue:e,className:Zt("w-full",n),children:t}),tae=({value:t,title:e,description:n,dataCy:r,icon:s,children:i,className:o=""})=>{const l=o.includes("first-item");return S.jsxs(hD,{value:t,className:Zt("w-full",!l&&"border-t border-main-border"),children:[S.jsxs(pD,{"data-cy":r,children:[s?S.jsx("span",{className:"mr-1 inline-flex items-center",children:s}):null,e]}),S.jsxs(mD,{children:[n?S.jsx("p",{className:"pb-2 text-sm text-content-subtle",children:n}):null,i]})]})};Im.Item=tae;const nae=({message:t,isLoading:e=!0})=>S.jsxs("div",{className:"flex items-center gap-2 text-sm text-content",children:[e?S.jsx(tv,{className:"h-4 w-4 shrink-0 animate-spin text-primary",weight:"bold"}):null,S.jsx("span",{className:"whitespace-pre-wrap font-sans",children:t})]}),rae=()=>{const t=g.useRef(Date.now()),[e,n]=g.useState(0);return g.useEffect(()=>{const r=()=>n(Math.max(0,Math.floor((Date.now()-t.current)/1e3)));r();const s=setInterval(r,1e3);return()=>clearInterval(s)},[]),e},sae=t=>{const e=Math.floor(t/60),n=t%60;return`${e}:${n.toString().padStart(2,"0")}`},YA="M 12 8 C 14.21 8 16 9.79 16 12 C 16 14.21 14.21 16 12 16 C 9.79 16 8 14.21 8 12 C 8 9.79 9.79 8 12 8 Z",XA="M 12 12 C 14 8.5 19 8.5 19 12 C 19 15.5 14 15.5 12 12 C 10 8.5 5 8.5 5 12 C 5 15.5 10 15.5 12 12 Z",iae="M 12 16 C 14.21 16 16 14.21 16 12 C 16 9.79 14.21 8 12 8 C 9.79 8 8 9.79 8 12 C 8 14.21 9.79 16 12 16 Z",Mm=["Applying","Thinking","Planning","Crafting"],oae=Mm.reduce((t,e)=>t.length>=e.length?t:e),aae=20,lae="Still working — runs can take a few minutes.",cae=({hint:t,showElapsed:e=!0})=>{const[n,r]=g.useState(0),s=rae();g.useEffect(()=>{const o=setInterval(()=>{r(l=>(l+1)%Mm.length)},4e3);return()=>clearInterval(o)},[]);const i=t??(e&&s>=aae?lae:null);return S.jsxs("div",{role:"status",className:"flex items-center gap-2 px-3 py-1","data-cy":"thinking-indicator",children:[S.jsx(ki.svg,{"aria-hidden":!0,width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0 text-muted-foreground",children:S.jsx(ki.path,{animate:{d:[YA,XA,iae,XA,YA]},transition:{d:{duration:6,ease:"easeInOut",repeat:1/0,times:[0,.25,.5,.75,1]}}})}),S.jsxs("span",{className:"inline-grid overflow-hidden text-sm font-medium",style:{fontVariationSettings:ah.medium},children:[S.jsx("span",{className:"shimmer-text invisible col-start-1 row-start-1","aria-hidden":"true",children:oae}),S.jsx(As,{mode:"popLayout",initial:!1,children:S.jsx(ki.span,{className:"shimmer-text col-start-1 row-start-1",initial:{y:"80%",opacity:0},animate:{y:0,opacity:1,transition:{duration:.24,ease:[.4,0,.2,1]}},exit:{y:"-80%",opacity:0,transition:{duration:.16,ease:[.4,0,.2,1]}},children:Mm[n]},Mm[n])})]}),e?S.jsx("span",{className:"text-xs tabular-nums text-content-subtle","data-cy":"thinking-elapsed",children:sae(s)}):null,i?S.jsx("span",{className:"text-xs text-content-subtle",children:i}):null]})};var uae=Object.defineProperty,dae=(t,e)=>uae(t,"name",{value:e,configurable:!0});function Vg(t,[e,n]){return Math.min(n,Math.max(e,t))}dae(Vg,"clamp");var fae=Object.defineProperty,It=(t,e)=>fae(t,"name",{value:e,configurable:!0}),QA={Horizontal:"horizontal"},hae={LTR:"ltr"},gD=["PageUp","PageDown"],vD=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],yD={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},up="Slider",[Ax,pae,mae]=tN(up),[t6,ale]=so(up,[mae]),[gae,Od]=t6(up),vae=g.forwardRef(It(function(e,n){const{name:r,min:s=0,max:i=100,step:o=1,orientation:l=QA.Horizontal,disabled:u=!1,minStepsBetweenThumbs:d=0,preserveThumbOrder:f=!1,defaultValue:h=[s],value:m,onValueChange:v=It(()=>{},"onValueChange"),onValueCommit:w=It(()=>{},"onValueCommit"),inverted:_=!1,form:x,...b}=e,k=g.useRef(new Set),C=g.useRef(0),P=g.useRef(!1),[T,M]=g.useState(null),R=l===QA.Horizontal?yae:_ae,[L,j]=g.useState(null),F=Xt(n,j),[N=[],q]=dl({prop:m,defaultProp:h,onChange:It(V=>{var G;(G=[...k.current][C.current])==null||G.focus({preventScroll:!0,focusVisible:P.current}),P.current=!1,v(V)},"onChange")}),W=g.useRef(N),Y=g.useRef(N);g.useEffect(()=>{const V=x?L==null?void 0:L.ownerDocument.getElementById(x):L==null?void 0:L.closest("form");if(V instanceof HTMLFormElement){const D=It(()=>q(Y.current),"reset");return V.addEventListener("reset",D),()=>V.removeEventListener("reset",D)}},[L,x,q]);function H(V){const D=CD(N,V);Q(V,D)}It(H,"handleSlideStart");function J(V){Q(V,C.current)}It(J,"handleSlideMove");function B(){String(N)!==String(W.current)&&w(N)}It(B,"handleSlideEnd");function Q(V,D,{commit:G}={commit:!1}){const le=r6(o),re=fh(Math.round((V-s)/o)*o+s,le),ie=Vg(re,[s,i]),ue=d*o;function fe(ne){const Ce=f?Vg(ie,[ne[D-1]===void 0?s:ne[D-1]+ue,ne[D+1]===void 0?i:ne[D+1]-ue]):ie,De=kD(ne,Ce,D);return TD(De,ue)?{nextValues:De,changedIndex:f?D:De.indexOf(Ce),hasChanged:String(De)!==String(ne)}:null}It(fe,"getNextValues");const de=fe(N);de!=null&&de.hasChanged&&M(de.nextValues),q((ne=[])=>{const Ce=fe(ne);return Ce?(C.current=Ce.changedIndex,Ce.hasChanged&&G&&w(Ce.nextValues),Ce.hasChanged?Ce.nextValues:ne):ne})}return It(Q,"updateValues"),S.jsx(gae,{scope:e.__scopeSlider,name:r,disabled:u,min:s,max:i,valueIndexToChangeRef:C,thumbs:k.current,values:N,orientation:l,form:x,userRequestedValues:T,children:S.jsx(Ax.Provider,{scope:e.__scopeSlider,children:S.jsx(Ax.Slot,{scope:e.__scopeSlider,children:S.jsx(R,{"aria-disabled":u,"data-disabled":u?"":void 0,...b,ref:F,onPointerDown:Yt(b.onPointerDown,()=>{u||(W.current=N,P.current=!1)}),min:s,max:i,inverted:_,onSlideStart:u?void 0:H,onSlideMove:u?void 0:J,onSlideEnd:u?void 0:B,onHomeKeyDown:()=>{u||(P.current=!0,Q(s,0,{commit:!0}))},onEndKeyDown:()=>{u||(P.current=!0,Q(i,N.length-1,{commit:!0}))},onStepKeyDown:({event:V,direction:D})=>{if(!u){P.current=!0;const re=gD.includes(V.key)||V.shiftKey&&vD.includes(V.key)?10:1,ie=C.current,ue=N[ie],fe=RD(ue,{min:s,step:o,direction:D,multiplier:re});Q(fe,ie,{commit:!0})}}})})})})},"Slider")),[_D,wD]=t6(up,{startEdge:"left",endEdge:"right",size:"width",direction:1}),yae=g.forwardRef(It(function(e,n){const{min:r,max:s,dir:i,inverted:o,onSlideStart:l,onSlideMove:u,onSlideEnd:d,onStepKeyDown:f,...h}=e,[m,v]=g.useState(null),w=Xt(n,v),_=g.useRef(void 0),x=KS(i),b=x===hae.LTR,k=b&&!o||!b&&o;function C(P){const T=_.current||m.getBoundingClientRect(),M=[0,T.width],R=Av(M,k?[r,s]:[s,r]);return _.current=T,R(P-T.left)}return It(C,"getValueFromPointer"),S.jsx(_D,{scope:e.__scopeSlider,startEdge:k?"left":"right",endEdge:k?"right":"left",direction:k?1:-1,size:"width",children:S.jsx(xD,{dir:x,"data-orientation":"horizontal",...h,ref:w,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:P=>{const T=C(P.clientX);l==null||l(T)},onSlideMove:P=>{const T=C(P.clientX);u==null||u(T)},onSlideEnd:()=>{_.current=void 0,d==null||d()},onStepKeyDown:P=>{const M=yD[k?"from-left":"from-right"].includes(P.key);f==null||f({event:P,direction:M?-1:1})}})})},"SliderHorizontal")),_ae=g.forwardRef(It(function(e,n){const{min:r,max:s,inverted:i,onSlideStart:o,onSlideMove:l,onSlideEnd:u,onStepKeyDown:d,...f}=e,h=g.useRef(null),m=Xt(n,h),v=g.useRef(void 0),w=!i;function _(x){const b=v.current||h.current.getBoundingClientRect(),k=[0,b.height],P=Av(k,w?[s,r]:[r,s]);return v.current=b,P(x-b.top)}return It(_,"getValueFromPointer"),S.jsx(_D,{scope:e.__scopeSlider,startEdge:w?"bottom":"top",endEdge:w?"top":"bottom",size:"height",direction:w?1:-1,children:S.jsx(xD,{"data-orientation":"vertical",...f,ref:m,style:{...f.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:x=>{const b=_(x.clientY);o==null||o(b)},onSlideMove:x=>{const b=_(x.clientY);l==null||l(b)},onSlideEnd:()=>{v.current=void 0,u==null||u()},onStepKeyDown:x=>{const k=yD[w?"from-bottom":"from-top"].includes(x.key);d==null||d({event:x,direction:k?-1:1})}})})},"SliderVertical")),xD=g.forwardRef(It(function(e,n){const{__scopeSlider:r,onSlideStart:s,onSlideMove:i,onSlideEnd:o,onHomeKeyDown:l,onEndKeyDown:u,onStepKeyDown:d,...f}=e,h=Od(up,r);return S.jsx(Pn.span,{...f,ref:n,onKeyDown:Yt(e.onKeyDown,m=>{m.key==="Home"?(l(m),m.preventDefault()):m.key==="End"?(u(m),m.preventDefault()):gD.concat(vD).includes(m.key)&&(d(m),m.preventDefault())}),onPointerDown:Yt(e.onPointerDown,m=>{const v=m.target;v.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(v)?v.focus({preventScroll:!0,focusVisible:!1}):s(m)}),onPointerMove:Yt(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&i(m)}),onPointerUp:Yt(e.onPointerUp,m=>{const v=m.target;v.hasPointerCapture(m.pointerId)&&(v.releasePointerCapture(m.pointerId),o(m))})})},"SliderImpl")),wae="SliderTrack",xae=g.forwardRef(It(function(e,n){const{__scopeSlider:r,...s}=e,i=Od(wae,r);return S.jsx(Pn.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...s,ref:n})},"SliderTrack")),JA="SliderRange",bae=g.forwardRef(It(function(e,n){const{__scopeSlider:r,...s}=e,i=Od(JA,r),o=wD(JA,r),l=g.useRef(null),u=Xt(n,l),d=i.values.length,f=i.values.map(v=>n6(v,i.min,i.max)),h=d>1?Math.min(...f):0,m=100-Math.max(...f);return S.jsx(Pn.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...s,ref:u,style:{...e.style,[o.startEdge]:h+"%",[o.endEdge]:m+"%"}})},"SliderRange")),Sae="SliderThumb",[kae,bD]=t6(Sae),Eae="SliderThumbProvider";function SD(t){const{__scopeSlider:e,name:n,children:r,internal_do_not_use_render:s}=t,i=Od(Eae,e),o=pae(e),[l,u]=g.useState(null),d=g.useMemo(()=>l?o().findIndex(x=>x.ref.current===l):-1,[o,l]),f=aS(l),h=l?!!i.form||!!l.closest("form"):!0,m=i.values[d],v=n??(i.name?i.name+(i.values.length>1?"[]":""):void 0),w=m===void 0?0:n6(m,i.min,i.max);g.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]);const _={value:m,name:v,form:i.form,isFormControl:h,index:d,thumb:l,onThumbChange:u,percent:w,size:f};return S.jsx(kae,{scope:e,..._,children:ID(s)?s(_):r})}It(SD,"SliderThumbProvider");var e2="SliderThumbTrigger",Cae=g.forwardRef(It(function(e,n){const{__scopeSlider:r,...s}=e,i=Od(e2,r),o=wD(e2,r),{index:l,value:u,percent:d,size:f,onThumbChange:h}=bD(e2,r),m=Xt(n,h),v=ED(l,i.values.length),w=f==null?void 0:f[o.size],_=w?PD(w,d,o.direction):0;return S.jsx("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[o.startEdge]:`calc(${d}% + ${_}px)`},children:S.jsx(Ax.ItemSlot,{scope:r,children:S.jsx(Pn.span,{role:"slider","aria-label":e["aria-label"]||v,"aria-valuemin":i.min,"aria-valuenow":u,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...s,ref:m,style:u===void 0?{display:"none"}:e.style,onFocus:Yt(e.onFocus,()=>{i.valueIndexToChangeRef.current=l})})})})},"SliderThumbTrigger")),Pae=g.forwardRef(It(function(e,n){const{__scopeSlider:r,name:s,...i}=e;return S.jsx(SD,{__scopeSlider:r,name:s,internal_do_not_use_render:({index:o,isFormControl:l})=>S.jsxs(S.Fragment,{children:[S.jsx(Cae,{...i,ref:n,__scopeSlider:r}),l?S.jsx(Aae,{__scopeSlider:r},o):null]})})},"SliderThumb")),e5="SliderBubbleInput",Aae=g.forwardRef(It(function({__scopeSlider:e,onInput:n,...r},s){const{index:i,value:o,name:l,form:u}=bD(e5,e),{userRequestedValues:d}=Od(e5,e),f=g.useRef(null),h=Xt(f,s),m=g.useRef(!1),v=g.useRef(o),w=g.useRef(d),_=g.useRef(d);return g.useEffect(()=>{const x=f.current;if(!x)return;const b=window.HTMLInputElement.prototype,C=Object.getOwnPropertyDescriptor(b,"value").set,P=v.current,T=P!==o;v.current=o;const M=d!==_.current;if(_.current=d,T&&C){const I=d!==w.current;w.current=d;const R=d==null?void 0:d[i],L=I&&(M&&R!==P||R===o);m.current=!L;const j=new Event("input",{bubbles:!0});C.call(x,o),x.dispatchEvent(j),m.current=!1}},[i,o,d]),S.jsx(Pn.input,{style:{display:"none"},name:l,form:u,...r,ref:h,defaultValue:o,onInput:Yt(n,x=>{m.current&&x.stopPropagation()})})},"SliderBubbleInput"));function kD(t=[],e,n){const r=[...t];return r[n]=e,r.sort((s,i)=>s-i)}It(kD,"getNextSortedValues");function n6(t,e,n){const i=100/(n-e)*(t-e);return Vg(i,[0,100])}It(n6,"convertValueToPercentage");function ED(t,e){return e>2?`Value ${t+1} of ${e}`:e===2?["Minimum","Maximum"][t]:void 0}It(ED,"getLabel");function CD(t,e){if(t.length===1)return 0;const n=t.map(s=>Math.abs(s-e)),r=Math.min(...n);return n.indexOf(r)}It(CD,"getClosestValueIndex");function PD(t,e,n){const r=t/2,i=Av([0,50],[0,r]);return(r-i(e)*n)*n}It(PD,"getThumbInBoundsOffset");function AD(t){return t.slice(0,-1).map((e,n)=>t[n+1]-e)}It(AD,"getStepsBetweenValues");function TD(t,e){if(e>0){const n=AD(t);return Math.min(...n)>=e}return!0}It(TD,"hasMinStepsBetweenValues");function Av(t,e){return n=>{if(t[0]===t[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(t[1]-t[0]);return e[0]+r*(n-t[0])}}It(Av,"linearScale");function r6(t){if(!Number.isFinite(t))return 0;const e=t.toString();if(e.includes("e")){const[r,s]=e.split("e"),i=r.split(".")[1]||"",o=Number(s);return Math.max(0,i.length-o)}const n=e.split(".")[1];return n?n.length:0}It(r6,"getDecimalCount");function fh(t,e){const n=Math.pow(10,e);return Math.round(t*n)/n}It(fh,"roundValue");function RD(t,{min:e,step:n,direction:r,multiplier:s}){const i=r6(n),o=(t-e)/n,l=Math.round(o),u=fh(l*n+e,i)===fh(t,i);let d;return u?d=l+s*r:r>0?d=Math.ceil(o):d=Math.floor(o),fh(d*n+e,i)}It(RD,"getNextStepValue");function ID(t){return typeof t=="function"}It(ID,"isFunction");const Tx=g.forwardRef(({className:t,...e},n)=>S.jsxs(vae,{ref:n,className:Zt("relative flex w-full touch-none select-none items-center","data-[disabled]:opacity-50",t),...e,children:[S.jsx(xae,{className:"relative h-1 w-full grow overflow-hidden rounded-full bg-input",children:S.jsx(bae,{className:"absolute h-full bg-primary"})}),S.jsx(Pae,{className:Zt("block h-3.5 w-3.5 rounded-full border border-border bg-foreground shadow-sm","transition-transform hover:scale-110 active:scale-95","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#6B97FF]","disabled:pointer-events-none")})]}));Tx.displayName="Slider";const Tae=[{name:"surface-1",utility:"bg-surface-1",className:"bg-surface-1"},{name:"surface-2",utility:"bg-surface-2",className:"bg-surface-2"},{name:"surface-3",utility:"bg-surface-3",className:"bg-surface-3"},{name:"surface-4",utility:"bg-surface-4",className:"bg-surface-4"},{name:"surface-5",utility:"bg-surface-5",className:"bg-surface-5"},{name:"surface-6",utility:"bg-surface-6",className:"bg-surface-6"}],Rae=[{name:"primary",utility:"bg-primary",className:"bg-primary"},{name:"selected",utility:"bg-selected",className:"bg-selected"},{name:"accent",utility:"bg-accent",className:"bg-accent"},{name:"success",utility:"bg-accent-success",className:"bg-accent-success"},{name:"warning",utility:"bg-accent-warning",className:"bg-accent-warning"},{name:"error",utility:"bg-accent-error",className:"bg-accent-error"}],Iae=[{name:"gap-1",className:"w-1"},{name:"gap-2",className:"w-2"},{name:"gap-3",className:"w-3"},{name:"gap-4",className:"w-4"},{name:"gap-6",className:"w-6"},{name:"gap-8",className:"w-8"}],J0=[{name:"Accordion",path:"components/Accordion.tsx",status:"showcased",note:"Reusable primitive shown with local item composition."},{name:"AgentVariantsPanel",path:"components/AgentVariantsPanel.tsx",status:"feature-only",note:"Requires live variant session state and editor atoms."},{name:"AuthProgressScreen",path:"components/AuthProgressScreen.tsx",status:"feature-only",note:"Auth flow surface; represented through progress treatment."},{name:"AuthScreenView",path:"components/AuthScreenView.tsx",status:"feature-only",note:"Auth flow surface that depends on sign-in actions."},{name:"Button",path:"components/Button.tsx",status:"showcased",note:"Reusable tooltip-wrapped button shown in multiple states."},{name:"CommentCarouselLayer",path:"components/CommentCarouselLayer.tsx",status:"feature-only",note:"Preview overlay layer tied to iframe geometry."},{name:"ElementInspector",path:"components/ElementInspector.tsx",status:"feature-only",note:"Primary editor surface with many app-level dependencies."},{name:"GitHome",path:"components/GitHome.tsx",status:"feature-only",note:"Git dashboard tied to repository state."},{name:"IframePreview",path:"components/IframePreview.tsx",status:"unsuitable",note:"Needs live iframe target and cross-window integration."},{name:"PreviewFrame",path:"components/PreviewFrame.tsx",status:"unsuitable",note:"Requires proxied app URL and iframe lifecycle."},{name:"PreviewSurface",path:"components/PreviewSurface.tsx",status:"unsuitable",note:"Requires preview iframe and overlay orchestration."},{name:"ProfileAvatar",path:"components/ProfileAvatar.tsx",status:"feature-only",note:"Account chrome tied to user identity data."},{name:"Progress",path:"components/Progress.tsx",status:"showcased",note:"Reusable inline loading/status primitive."},{name:"SecondaryVariantIframe",path:"components/SecondaryVariantIframe.tsx",status:"unsuitable",note:"Requires variant preview iframe lifecycle."},{name:"SparkleLoader",path:"components/SparkleLoader.tsx",status:"showcased",note:"Reusable loading animation shown in feedback states."},{name:"SplitButton",path:"components/SplitButton.tsx",status:"showcased",note:"Reusable compound action button shown with dropdown."},{name:"StatusSurface",path:"components/StatusSurface.tsx",status:"showcased",note:"Unified full-surface primitive: LoadingSurface / EmptyState / ErrorState."},{name:"SupportTicketModal",path:"components/SupportTicketModal.tsx",status:"feature-only",note:"Support workflow modal tied to form submission."},{name:"ThinkingIndicator",path:"components/ThinkingIndicator.tsx",status:"showcased",note:"Reusable thinking/loading indicator shown in feedback states."},{name:"Tooltip",path:"components/Tooltip.tsx",status:"showcased",note:"Reusable tooltip API shown with hover target."},{name:"VariantDragGhost",path:"components/VariantDragGhost.tsx",status:"feature-only",note:"Drag visual tied to variant split interactions."},{name:"VariantSplitDropZones",path:"components/VariantSplitDropZones.tsx",status:"feature-only",note:"Drop-zone visual tied to variant split interactions."},{name:"ui/accordion",path:"components/ui/accordion.tsx",status:"showcased",note:"Radix accordion primitive backing the local Accordion showcase."},{name:"ui/slider",path:"components/ui/slider.tsx",status:"showcased",note:"Radix slider primitive shown in enabled and disabled states."},{name:"ui/tooltip",path:"components/ui/tooltip.tsx",status:"showcased",note:"Radix tooltip primitive shown with forced-open preview."}],Mae=()=>{window.location.hash=""},Po=({title:t,eyebrow:e,description:n,children:r})=>S.jsxs("section",{className:"border-border bg-card shadow-surface-3 rounded-2xl border p-5",children:[S.jsxs("div",{className:"mb-5 max-w-2xl",children:[S.jsx("p",{className:"text-primary text-xs font-semibold tracking-[0.18em] uppercase",children:e}),S.jsx("h2",{className:"text-foreground mt-2 text-xl font-semibold",children:t}),S.jsx("p",{className:"text-muted-foreground mt-2 text-sm leading-6",children:n})]}),r]}),t5=({swatches:t})=>S.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:t.map(e=>S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-3",children:[S.jsx("div",{className:`h-16 rounded-lg ${e.className}`}),S.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[S.jsx("span",{className:"text-foreground text-sm font-medium",children:e.name}),S.jsx("code",{className:"bg-muted text-muted-foreground rounded px-2 py-1 text-xs",children:e.utility})]})]},e.name))}),Oae=t=>t==="showcased"?"border-accent-success/40 bg-accent-success/10 text-accent-success":t==="cataloged"?"border-primary/40 bg-primary/10 text-primary":t==="generated"?"border-accent/40 bg-accent/10 text-accent":t==="unsuitable"?"border-accent-warning/40 bg-accent-warning/10 text-accent-warning":"border-border bg-surface-4 text-content-muted",Lae=()=>{const t=J0.filter(n=>n.status==="showcased").length,e=J0.filter(n=>n.status==="cataloged").length;return S.jsx("main",{className:"bg-main font-main text-content h-screen overflow-y-auto",children:S.jsxs("div",{className:"mx-auto flex w-full max-w-6xl flex-col gap-6 px-6 py-6 lg:px-8",children:[S.jsxs("header",{className:"border-border bg-surface-2 shadow-surface-4 rounded-3xl border p-6",children:[S.jsxs("button",{type:"button",onClick:Mae,className:"text-content-subtle hover:text-content mb-6 inline-flex items-center gap-2 text-sm transition-colors",children:[S.jsx(sY,{className:"h-4 w-4",weight:"bold"}),"Back to editor"]}),S.jsxs("div",{className:"flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between",children:[S.jsxs("div",{className:"max-w-3xl",children:[S.jsx("p",{className:"text-primary text-xs font-semibold tracking-[0.22em] uppercase",children:"Local component gallery"}),S.jsx("h1",{className:"text-foreground mt-3 text-4xl font-semibold tracking-tight",children:"Rivet design system"}),S.jsx("p",{className:"text-muted-foreground mt-3 text-base leading-7",children:"A Storybook-like route for checking the current UI primitives, tokens, and interaction states inside the Vite app."})]}),S.jsx("div",{className:"border-border bg-surface-3 rounded-2xl border p-4",children:S.jsxs("div",{className:"text-content-muted flex items-center gap-3 text-sm",children:[S.jsx(w3,{className:"text-primary h-5 w-5",weight:"bold"}),"Open with ",S.jsx("code",{className:"text-content",children:"#/design-system"})]})})]})]}),S.jsx(Po,{eyebrow:"Controls",title:"Button, split button, and tooltip",description:"Rivet's shared Button exposes variants and sizes backed by Fluid Functionalism, alongside the split button and tooltip controls.",children:S.jsxs("div",{className:"grid gap-4 lg:grid-cols-[1fr_1fr]",children:[S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-foreground mb-3 text-sm font-medium",children:"Rivet Button"}),S.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[S.jsx(Qi,{title:"Primary action",shortcut:"D",variant:"primary",children:"Design action"}),S.jsx(Qi,{title:"Secondary action",variant:"secondary",children:"Secondary"}),S.jsx(Qi,{title:"Disabled action",disabled:!0,variant:"tertiary",children:"Disabled"}),S.jsx(I9,{primaryLabel:"Ship",primaryIcon:__,primaryAction:()=>{},dropdownItems:[{label:"Create PR",onClick:()=>{}},{label:"Copy branch",onClick:()=>{}}]})]})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-foreground mb-3 text-sm font-medium",children:"Tooltip states"}),S.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[S.jsx(Tc,{label:"Rivet tooltip API",side:"bottom",children:S.jsx("button",{className:"border-border bg-surface-4 text-content rounded-lg border px-4 py-2 text-sm",children:"Hover target"})}),S.jsx(fS,{content:"Forced open preview",forceOpen:!0,side:"right",children:S.jsx("button",{className:"bg-selected text-content rounded-lg px-4 py-2 text-sm",children:"UI tooltip"})})]})]})]})}),S.jsx(Po,{eyebrow:"Tokens",title:"Surface ladder",description:"Surface tokens move from the base app background toward raised panels without leaving the dark Rivet palette.",children:S.jsx(t5,{swatches:Tae})}),S.jsx(Po,{eyebrow:"Tokens",title:"Color roles",description:"Named roles should communicate purpose: brand, selection, neutral accent, and outcome colors.",children:S.jsx(t5,{swatches:Rae})}),S.jsx(Po,{eyebrow:"Type",title:"Typography",description:"Satoshi remains the default UI voice with clear hierarchy and muted support text.",children:S.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-primary text-xs tracking-[0.18em] uppercase",children:"Display"}),S.jsx("p",{className:"text-foreground mt-2 text-3xl font-semibold tracking-tight",children:"Visual edits, quickly"})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-foreground text-sm font-semibold",children:"Panel heading"}),S.jsx("p",{className:"text-muted-foreground mt-2 text-sm leading-6",children:"Body copy uses compact line height and muted contrast for dense inspector panels."})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-content-subtle text-xs font-medium tracking-[0.16em] uppercase",children:"Micro label"}),S.jsx("code",{className:"bg-muted text-muted-foreground mt-3 block rounded-lg px-3 py-2 text-xs",children:"font-main text-content"})]})]})}),S.jsx(Po,{eyebrow:"Layout",title:"Spacing rhythm",description:"A compact spacing scale keeps editor chrome dense while preserving scannable groupings.",children:S.jsx("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:S.jsx("div",{className:"flex flex-col gap-3",children:Iae.map(n=>S.jsxs("div",{className:"flex items-center gap-4",children:[S.jsx("code",{className:"text-muted-foreground w-16 text-xs",children:n.name}),S.jsx("div",{className:`${n.className} bg-primary h-4 rounded`}),S.jsx("div",{className:"bg-border h-px flex-1"})]},n.name))})})}),S.jsx(Po,{eyebrow:"Primitives",title:"Accordion and slider",description:"Representative Radix primitives styled through the local component layer.",children:S.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[S.jsxs(Im,{defaultValue:["foundations"],className:"border-border bg-surface-2 rounded-xl border p-2",children:[S.jsx(Im.Item,{value:"foundations",title:"Foundations",description:"Tokens, surfaces, type, and spacing.",className:"first-item",icon:S.jsx(__,{className:"text-primary h-4 w-4"}),children:S.jsx("p",{children:"Use these pieces before adding one-off visual rules."})}),S.jsx(Im.Item,{value:"components",title:"Components",description:"Buttons, tooltips, accordions, sliders.",children:S.jsx("p",{children:"Keep states visible in this route as the system evolves."})})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-5",children:[S.jsx("p",{className:"text-foreground mb-5 text-sm font-medium",children:"Slider states"}),S.jsxs("div",{className:"space-y-6",children:[S.jsx(Tx,{defaultValue:[64],max:100,step:1}),S.jsx(Tx,{defaultValue:[36],max:100,step:1,disabled:!0})]})]})]})}),S.jsx(Po,{eyebrow:"Feedback",title:"Motion and loading",description:"Loading states use existing CSS animation utilities and avoid per-frame React work where possible.",children:S.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-foreground mb-4 text-sm font-medium",children:"Progress"}),S.jsx(nae,{message:"Applying visual change..."})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-foreground mb-4 text-sm font-medium",children:"Sparkle strip"}),S.jsx(kS,{className:"text-primary text-xl"})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-foreground mb-4 text-sm font-medium",children:"Shimmer text"}),S.jsx("span",{className:"shimmer-text text-sm font-medium",children:"Generating variants"})]}),S.jsx("div",{className:"border-border bg-surface-2 rounded-xl border p-4 sm:col-span-3",children:S.jsx(cae,{hint:"Reading selected elements"})})]})}),S.jsx(Po,{eyebrow:"Feedback",title:"Status surfaces",description:"The unified full-surface system: one StatusSurface primitive with LoadingSurface / EmptyState / ErrorState wrappers. Every full-page loading, empty, and error state routes through these so they share layout, copy tone, and a single status_surface_shown impression event. Inline loaders (Sparkle, ThinkingIndicator, above) stay inline and are deliberately not part of this system.",children:S.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[S.jsx("div",{className:"border-border relative h-56 overflow-hidden rounded-xl border",children:S.jsx(ux,{fill:"surface",loader:"coalesce",trackGlobalLoaderCount:!1})}),S.jsx("div",{className:"border-border relative h-56 overflow-hidden rounded-xl border",children:S.jsx(nL,{icon:S.jsx(__,{size:32}),title:"Nothing to preview yet",description:"Pick a direction from the panel."})}),S.jsx("div",{className:"border-border relative h-56 overflow-hidden rounded-xl border",children:S.jsx(CS,{fill:"surface",size:"sm",title:"Preview isn't connected",description:"Rivet lost connection to your project.",actions:[{label:"Reload",onClick:()=>{}}]})})]})}),S.jsxs(Po,{eyebrow:"Inventory",title:"Component coverage",description:"Every current component file is accounted for here. Reusable primitives are rendered above; app surfaces that need live editor, git, auth, iframe, or generated state are cataloged instead of mounted unsafely.",children:[S.jsxs("div",{className:"mb-4 grid gap-3 sm:grid-cols-3",children:[S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-content-subtle text-xs tracking-[0.16em] uppercase",children:"Total components"}),S.jsx("p",{className:"text-foreground mt-2 text-2xl font-semibold",children:J0.length})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-content-subtle text-xs tracking-[0.16em] uppercase",children:"Showcased"}),S.jsx("p",{className:"text-accent-success mt-2 text-2xl font-semibold",children:t})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-content-subtle text-xs tracking-[0.16em] uppercase",children:"Cataloged"}),S.jsx("p",{className:"text-primary mt-2 text-2xl font-semibold",children:e})]})]}),S.jsxs("div",{className:"border-border overflow-hidden rounded-xl border",children:[S.jsxs("div",{className:"border-border bg-surface-3 text-content-subtle grid grid-cols-[minmax(140px,1fr)_minmax(110px,auto)_minmax(220px,2fr)] border-b px-4 py-3 text-xs font-semibold tracking-[0.14em] uppercase",children:[S.jsx("span",{children:"Component"}),S.jsx("span",{children:"Status"}),S.jsx("span",{children:"Coverage note"})]}),S.jsx("div",{className:"divide-border bg-surface-2 divide-y",children:J0.map(n=>S.jsxs("div",{className:"grid grid-cols-[minmax(140px,1fr)_minmax(110px,auto)_minmax(220px,2fr)] gap-3 px-4 py-3 text-sm",children:[S.jsxs("div",{children:[S.jsx("p",{className:"text-foreground font-medium",children:n.name}),S.jsx("code",{className:"text-muted-foreground text-xs",children:n.path})]}),S.jsx("div",{children:S.jsx("span",{className:`inline-flex rounded-full border px-2 py-1 text-xs font-medium ${Oae(n.status)}`,children:n.status})}),S.jsx("p",{className:"text-muted-foreground",children:n.note})]},n.path))})]})]})]})})},Nae=t=>(t.startsWith("#/")?t.slice(2):t.slice(1)).split("?")[0]==="design-system"?"design-system":"editor",Rx=274,Hg=395,t2=Math.min(Hg,Math.round((Rx+Hg)/2*1.1)),n5="rivet:panelWidth:v2",Dae=({projectPath:t,libraryOrigin:e})=>{const n=dt(S9)>0,[r,s]=mI(x9),i=nK(),[o,l]=g.useState(()=>{if(typeof window>"u")return t2;const T=Number(window.localStorage.getItem(n5));return Number.isFinite(T)&&T>=Rx&&T<=Hg?T:t2}),[u,d]=g.useState(!1),[f,h]=g.useState(eie),m=r?o:0,[v,w]=g.useState(r);g.useEffect(()=>{if(!r){w(!1);return}h(T=>Jse({position:T,boundsLeftPx:o}))},[r,o]),g.useEffect(()=>{window.localStorage.setItem(n5,String(o))},[o]),g.useEffect(()=>{if(!r)return;const T=M=>{M.key==="Escape"&&(lI(M.target)||(M.preventDefault(),s(!1)))};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[r,s]);const _=g.useCallback(T=>{T.preventDefault(),T.stopPropagation();const M=T.clientX,I=o;d(!0);const R=j=>{const F=Math.min(Hg,Math.max(Rx,I+(j.clientX-M)));l(F)},L=()=>{window.removeEventListener("pointermove",R),window.removeEventListener("pointerup",L),window.removeEventListener("pointercancel",L),d(!1)};window.addEventListener("pointermove",R),window.addEventListener("pointerup",L),window.addEventListener("pointercancel",L)},[o]),x=g.useCallback(()=>l(t2),[]),b=pie(),k=dt(_v);vie({enabled:!k});const C=b.isProcessing?"Completing authentication...":null,P=yt(yv);return g.useEffect(()=>{P(t??null)},[t,P]),S.jsxs(ki.div,{className:"relative flex h-screen overflow-hidden",initial:!1,animate:{opacity:1},transition:{duration:.5,ease:"easeOut"},"data-cy":"rivet-app",children:[C!==null?S.jsx("div",{className:"absolute inset-0 z-50",children:S.jsx(Vse,{message:C})}):null,S.jsx(pre,{}),S.jsx(S.Fragment,{children:n?null:S.jsxs(S.Fragment,{children:[S.jsx("div",{className:"relative order-first h-full flex-shrink-0",style:{width:v?o:0},children:S.jsxs(ki.div,{className:"absolute inset-y-0 left-0 z-30",initial:!1,animate:{x:r?0:-o},transition:i?{duration:0}:{duration:.2,ease:[.22,1,.36,1]},onAnimationComplete:()=>{r&&w(!0)},style:{width:o,willChange:"transform"},children:[S.jsx(Ene,{onClose:()=>s(!1),libraryOrigin:e}),S.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panel",onPointerDown:_,onDoubleClick:x,className:"group/resize absolute inset-y-0 right-0 z-20 flex w-3 cursor-col-resize touch-none justify-end",children:S.jsx("span",{className:`h-full transition-all duration-150 ${u?"bg-content-muted w-0.5":"bg-divider group-hover/resize:bg-content-muted w-px group-hover/resize:w-0.5"}`})})]})}),u&&S.jsx("div",{className:"fixed inset-0 z-[100] cursor-col-resize"}),S.jsx(rie,{isVisible:!0,isPanelOpen:r,isReducedMotion:!!i,position:f,dragBoundsLeftPx:m,onPositionChange:h,onToggle:()=>s(T=>!T)})]})}),S.jsx(MK,{duration:5e3,richColors:!0,toastOptions:{style:{maxHeight:"150px",overflow:"hidden"}}})]})},Ix="rivet_connect_deep_link",jae=()=>{if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search),e=t.get("connect"),n=e??window.sessionStorage.getItem(Ix);if(n!=="pinterest"&&n!=="arena"&&n!=="x")return null;if(window.sessionStorage.setItem(Ix,n),e){t.delete("connect");const r=t.toString();window.history.replaceState(null,document.title,window.location.pathname+(r?`?${r}`:"")+window.location.hash)}return n},$ae=jae(),Fae=()=>{const[t,e]=g.useState(window.location.hash),[n]=g.useState(()=>typeof window<"u"&&window.sessionStorage.getItem(Ig)==="1"),[r,s]=g.useState(!1),[i,o]=g.useState($ae);g.useEffect(()=>{n&&window.sessionStorage.removeItem(Ig)},[n]);const{config:l,refetchConfig:u,loading:d,error:f}=hie(),h=yt(_v),{startLogin:m,isStartingLogin:v,loginError:w}=G9(),[_,x]=g.useState(!1);g.useEffect(()=>{Z2()&&(l!=null&&l.userId?($e.identify(l.userId,{...l.email?{email:l.email}:{}}),l.email&&$e.alias(l.email,l.userId)):l!=null&&l.email&&$e.identify(l.email,{email:l.email}))},[l==null?void 0:l.userId,l==null?void 0:l.email]),g.useEffect(()=>{l&&$e.register({source:"visual_editor",surface:"visual_editor"})},[l]);const b=l!=null&&l.agentModeAvailable!==!0,k=Nae(t),C=g.useCallback(async()=>{x(!0),h(!0);try{await u()}finally{h(!1),x(!1)}},[u,h]);if(g.useEffect(()=>{const I=()=>{const R=window.location.hash;e(R)};return window.addEventListener("hashchange",I),()=>window.removeEventListener("hashchange",I)},[]),k==="design-system")return S.jsx(Lae,{});if(!d&&l===null&&!_){const I=f||"Could not load Rivet configuration.";return S.jsx("div",{className:"bg-main flex h-screen items-center justify-center px-6",children:S.jsxs("div",{className:"border-divider bg-main w-full max-w-md rounded-lg border p-6 text-center shadow-lg",children:[S.jsx("p",{className:"text-content text-sm font-medium",children:"We could not start Rivet yet."}),S.jsx("p",{className:"text-content-muted mt-2 text-xs",children:I}),S.jsx("button",{type:"button",className:"border-divider text-content hover:bg-main/80 mt-4 rounded-md border px-3 py-1.5 text-xs",onClick:()=>{C()},children:"Retry"})]})})}if(b)return S.jsx($se,{isSigningIn:v,onStartSignIn:()=>{m()},errorMessage:w,displayMode:"full"});const T=(l==null?void 0:l.agentModeAvailable)===!0&&i!==null,M=(l==null?void 0:l.agentModeAvailable)===!0&&n&&!r&&!T;return S.jsxs(S.Fragment,{children:[S.jsx(Dae,{projectPath:l==null?void 0:l.projectPath,libraryOrigin:(l==null?void 0:l.libraryOrigin)??null}),S.jsx(ax,{context:"onboarding",isOpen:M,onClose:()=>s(!0)}),S.jsx(ax,{context:"menu",isOpen:T,highlightProvider:i,onClose:()=>{window.sessionStorage.removeItem(Ix),o(null)}})]})};y7();const Vae=g.lazy(()=>h5(()=>import("./LibraryEntry-CFkd6v_O.js"),[])),s6=window.location.pathname.startsWith("/rivet/library");s6||xU();const Hae=new Zz,zae=()=>S.jsx("div",{style:{display:"flex",height:"100vh",alignItems:"center",justifyContent:"center"},children:S.jsx("p",{style:{fontSize:"14px",color:"#6b7280"},children:"Something went wrong. Please reload the page."})}),MD=document.getElementById("root");if(!MD)throw new Error("Rivet root element is missing");const Uae=()=>PU.createRoot(MD).render(S.jsx(_e.StrictMode,{children:S.jsx(aU,{client:$e,children:S.jsx(hU,{fallback:S.jsx(zae,{}),children:S.jsx(wz,{client:Hae,children:S.jsx(bX,{defaultShape:"rounded",children:S.jsx(Joe,{defaultLibrary:"lucide",children:s6?S.jsx(g.Suspense,{fallback:S.jsx("div",{className:"bg-background h-screen"}),children:S.jsx(Vae,{})}):S.jsx(Fae,{})})})})})})})),Bae=async()=>{s6&&await fz(),await _z(),Uae()};Bae();export{rz as $,fv as A,Qi as B,hv as C,dv as D,pv as E,mv as F,gv as G,$t as H,Rr as I,Hse as J,np as K,Hoe as L,qR as M,kh as N,P3 as O,yS as P,Vz as Q,oh as R,Xh as S,uoe as T,cr as U,yn as V,Ke as W,Yoe as X,ob as Y,Ec as Z,wE as _,qz as a,Zae as a0,pX as a1,we as a2,iz as a3,Za as a4,rle as a5,sle as a6,hz as a7,$te as a8,Zt as a9,Qae as aa,Jae as ab,ioe as ac,kne as ad,MK as ae,Ote as af,Yae as ag,Kae as ah,qae as ai,G9 as aj,bt as ak,dz as al,uz as am,Gae as an,Yz as b,g as c,Xz as d,eU as e,Qz as f,Uz as g,Sh as h,es as i,tU as j,nU as k,Jz as l,tI as m,vr as n,ct as o,si as p,_9 as q,JR as r,Xy as s,S as t,YR as u,Nw as v,_S as w,wS as x,xS as y,Loe as z};
|
|
439
|
-
//# sourceMappingURL=main-
|
|
438
|
+
*/const iD={name:"x",size:24,node:[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]};iD.node;const Yoe=ct(iD),Xoe={"chevron-right":foe,"chevron-down":doe,pipette:Noe,x:Yoe,copy:moe,menu:Poe,dot:goe,monitor:Toe,sun:qoe,moon:Roe,"rectangle-horizontal":$oe,circle:hoe,"square-library":Woe,clock:poe,star:Zoe,settings:zoe,plus:joe,"arrow-left":ioe,"arrow-right":ooe,"arrow-up":aoe,search:Hoe,loader:koe,users:Koe,lock:Eoe,mail:Coe,bell:loe,shield:Uoe,palette:Moe,lightbulb:boe,rocket:Foe,heart:yoe,paintbrush:Ioe,brain:coe,globe:voe,user:Goe,image:woe,link:Soe,check:uoe,"rotate-ccw":Voe,play:Doe,pause:Ooe,home:_oe,"message-circle":Aoe,inbox:xoe,pencil:Loe,"skip-forward":Boe},KA={lucide:Xoe},oD=g.createContext(null);function Qoe(t){const e=g.useContext(oD);return e?KA[e.iconLibrary][t]:KA.lucide[t]}function Joe({children:t,defaultLibrary:e="lucide"}){const[n,r]=g.useState(e),s=g.useCallback(i=>{r(i)},[]);return S.jsx(oD.Provider,{value:{iconLibrary:n,setIconLibrary:s},children:t})}const aD=g.createContext(null);function e6(){return g.useContext(aD)}const lD=g.createContext(null);function cD(){const t=g.useContext(lD);if(!t)throw new Error("AccordionTrigger/AccordionContent must be used within an AccordionItem");return t}const eae=g.forwardRef((t,e)=>{const{children:n,type:r="single",className:s,...i}=t,o=g.useRef(null),l=g.useRef(new Map),[u,d]=g.useState(new Map),{activeIndex:f,setActiveIndex:h,itemRects:m,sessionRef:v,handlers:w,registerItem:_,measureItems:x}=y9(o),b=g.useCallback((de,ne)=>{ne?l.current.set(de,ne):l.current.delete(de)},[]),k=g.useCallback(()=>{if(!o.current)return;const de=new Map;l.current.forEach((ne,Ce)=>{de.set(Ce,{top:ne.offsetTop,left:ne.offsetLeft,width:ne.offsetWidth,height:ne.offsetHeight})}),d(de)},[]),[C,P]=g.useState(()=>r==="single"?t.defaultValue??"":""),[T,M]=g.useState(()=>r==="multiple"?t.defaultValue??[]:[]),I=t.onValueChange,R=t.onValueChange,L=t.value,j=new Set(r==="multiple"?t.value??T:(()=>{const de=t.value??C;return de?[de]:[]})()),F=g.useCallback(de=>{const ne=t;ne.onValueChange?ne.onValueChange(de):P(de)},[I]),N=g.useCallback(de=>{const ne=t;ne.onValueChange?ne.onValueChange(de):M(de)},[R]),q=g.useCallback(de=>{if(r==="multiple"){const ne=t.value??T;N(ne.filter(Ce=>Ce!==de))}else F("")},[r,F,N,T,L]);g.useEffect(()=>{x(),k()},[x,k,n]);const W=[...j].join(",");g.useEffect(()=>{x(),k()},[x,k,W]);const[Y,H]=g.useState(null),J=f!==null?m[f]:null,B=Y!==null?m[Y]:null,Q=f!==null&&!u.has(f),V=rp(),{value:D,defaultValue:G,onValueChange:le,collapsible:re,type:ie,...ue}=i,fe=r==="multiple"?{type:"multiple",value:t.value??T,onValueChange:N}:{type:"single",collapsible:t.collapsible??!0,value:t.value??C,onValueChange:F};return S.jsx(aD.Provider,{value:{registerItem:_,registerFullItem:b,activeIndex:f,grouped:!0,remeasure:()=>{x(),k()},openValues:j,openItemRects:u,toggleValue:q},children:S.jsx(uN,{...fe,asChild:!0,children:S.jsxs("div",{ref:de=>{o.current=de,typeof e=="function"?e(de):e&&(e.current=de)},onMouseEnter:w.onMouseEnter,onMouseMove:de=>{const ne=o.current;if(ne){const Ce=ne.getBoundingClientRect(),De=ne.offsetHeight,Ee=Ce.height,ft=De>0?Ee/De:1,At=(de.clientY-Ce.top)/ft+ne.scrollTop;for(const[zt,wt]of u){const Tt=m[zt];if(!Tt)continue;const sn=Tt.top+Tt.height,Re=wt.top+wt.height;if(At>=sn&&At<=Re){h(null);return}}}w.onMouseMove(de)},onMouseLeave:w.onMouseLeave,onFocus:de=>{var Ce;const ne=(Ce=de.target.closest("[data-proximity-index]"))==null?void 0:Ce.getAttribute("data-proximity-index");if(ne!=null){const De=Number(ne);h(De),H(de.target.matches(":focus-visible")?De:null)}},onBlur:de=>{var ne;(ne=o.current)!=null&&ne.contains(de.relatedTarget)||(H(null),h(null))},className:Zt("relative flex flex-col gap-0.5 w-72 max-w-full",s),...ue,children:[S.jsx(As,{children:[...u.entries()].map(([de,ne])=>S.jsx(Bo.div,{className:`absolute ${V.bg} bg-accent/20 dark:bg-accent/12 pointer-events-none`,initial:!1,animate:{top:ne.top,left:ne.left,width:ne.width,height:ne.height,opacity:Q?.7:1},exit:{opacity:0,transition:{duration:.12}},transition:{top:{duration:0},left:{duration:0},width:{duration:0},height:{duration:0},opacity:{duration:.08}}},`expanded-${de}`))}),S.jsx(As,{children:J&&S.jsx(Bo.div,{className:`absolute ${V.bg} bg-hover pointer-events-none`,initial:{opacity:0,top:J.top,left:J.left,width:J.width,height:J.height},animate:{opacity:1,top:J.top,left:J.left,width:J.width,height:J.height},exit:{opacity:0,transition:{duration:.06}},transition:{...Dh.fast,opacity:{duration:.08}}},v.current)}),S.jsx(As,{children:B&&S.jsx(Bo.div,{className:`absolute ${V.focusRing} pointer-events-none z-20 border border-[#6B97FF]`,initial:!1,animate:{left:B.left-2,top:B.top-2,width:B.width+4,height:B.height+4},exit:{opacity:0,transition:{duration:.06}},transition:{...Dh.fast,opacity:{duration:.08}}})}),n]})})})});eae.displayName="AccordionGroup";const uD=g.forwardRef(({children:t,type:e="single",collapsible:n=!0,defaultValue:r,value:s,onValueChange:i,className:o,...l},u)=>{const[d,f]=g.useState(()=>e==="single"?r??"":""),[h,m]=g.useState(()=>e==="multiple"?r??[]:[]),v=new Set(e==="multiple"?s??h:(()=>{const k=s??d;return k?[k]:[]})()),w=g.useCallback(k=>{i?i(k):f(k)},[i]),_=g.useCallback(k=>{i?i(k):m(k)},[i]),x=g.useCallback(k=>{e==="multiple"?_((s??h).filter(P=>P!==k)):w("")},[e,s,h,w,_]),b=e==="multiple"?{type:"multiple",value:s??h,defaultValue:r,onValueChange:_}:{type:"single",collapsible:n,value:s??d,defaultValue:r,onValueChange:w};return S.jsx(uN,{...b,asChild:!0,children:S.jsx("div",{ref:u,className:Zt("w-72 max-w-full flex flex-col gap-0.5",o),...l,children:S.jsx(dD.Provider,{value:v,children:S.jsx(fD.Provider,{value:x,children:t})})})})});uD.displayName="Accordion";const dD=g.createContext(new Set),fD=g.createContext(()=>{}),hD=g.forwardRef(({value:t,index:e,disabled:n,children:r,className:s,...i},o)=>{const l=g.useRef(null),u=e6(),d=g.useContext(dD),f=g.useContext(fD),h=rp(),m=u!=null&&u.grouped?u.openValues.has(t):d.has(t),v=g.useRef(null),w=g.useCallback(()=>{u!=null&&u.grouped?u.toggleValue(t):f(t)},[u,f,t]);return g.useEffect(()=>{if(u!=null&&u.grouped&&e!==void 0)return u.registerItem(e,v.current),()=>u.registerItem(e,null)},[e,u]),g.useEffect(()=>{if(u!=null&&u.grouped&&e!==void 0)return m?u.registerFullItem(e,l.current):u.registerFullItem(e,null),()=>u.registerFullItem(e,null)},[e,u,m]),S.jsx(lD.Provider,{value:{index:e,value:t,isOpen:m,onToggle:w,triggerRef:v},children:S.jsxs(Uie,{ref:_=>{l.current=_,typeof o=="function"?o(_):o&&(o.current=_)},value:t,disabled:n,"data-proximity-index":e,className:Zt(!(u!=null&&u.grouped)&&"relative",s),...i,children:[!(u!=null&&u.grouped)&&S.jsx(As,{children:m&&S.jsx(Bo.div,{className:`absolute inset-0 ${h.bg} bg-accent/20 dark:bg-accent/12 pointer-events-none`,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0,transition:{duration:.06}},transition:{duration:.08}})}),r]})})});hD.displayName="AccordionItem";const pD=g.forwardRef(({children:t,className:e,...n},r)=>{const s=Qoe("chevron-right"),i=e6(),{index:o,isOpen:l,triggerRef:u}=cD(),d=rp(),[f,h]=g.useState(!1),m=i!=null&&i.grouped?i.activeIndex===o:f,v=S.jsx(Wie,{asChild:!0,children:S.jsx("div",{children:S.jsxs(Zie,{ref:r,className:Zt(`relative z-10 flex items-center gap-2.5 ${d.item} px-3 py-2 w-full cursor-pointer outline-none select-none`,!(i!=null&&i.grouped)&&"focus-visible:ring-1 focus-visible:ring-[#6B97FF] focus-visible:ring-offset-0",e),...n,children:[S.jsxs("span",{className:"inline-grid text-[13px] flex-1 text-left",children:[S.jsx("span",{className:"col-start-1 row-start-1 invisible",style:{fontVariationSettings:ah.semibold},"aria-hidden":"true",children:t}),S.jsx("span",{className:Zt("col-start-1 row-start-1 transition-[color,font-variation-settings] duration-80",l||m?"text-foreground":"text-muted-foreground"),style:{fontVariationSettings:l?ah.semibold:ah.normal},children:t})]}),S.jsx(Bo.span,{className:"shrink-0 inline-flex items-center justify-center",animate:{rotate:l?90:0},transition:Dh.fast,children:S.jsx(s,{size:16,strokeWidth:l||m?2:1.5,className:Zt("transition-[color,stroke-width] duration-80",l||m?"text-foreground":"text-muted-foreground")})})]})})});return i!=null&&i.grouped?S.jsx("div",{ref:u,children:v}):S.jsxs("div",{className:"relative",onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),children:[S.jsx(As,{children:f&&S.jsx(Bo.div,{className:`absolute inset-0 ${d.bg} bg-hover pointer-events-none`,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0,transition:{duration:.06}},transition:{duration:.08}})}),v]})});pD.displayName="AccordionTrigger";const mD=g.forwardRef(({children:t,className:e,...n},r)=>{const s=e6(),{isOpen:i}=cD();return S.jsx(As,{initial:!1,children:i&&S.jsx(Gie,{forceMount:!0,asChild:!0,...n,children:S.jsx(Bo.div,{ref:r,className:Zt("overflow-hidden",e),initial:{height:0},animate:{height:"auto"},exit:{height:0},transition:{...Dh.moderate,bounce:0},onUpdate:()=>{s==null||s.remeasure()},onAnimationComplete:()=>{s==null||s.remeasure()},children:S.jsx("div",{className:"px-3 pb-3 pt-1 text-[13px] text-muted-foreground",children:t})})})})});mD.displayName="AccordionContent";const Im=({children:t,defaultValue:e=[],className:n=""})=>S.jsx(uD,{type:"multiple",defaultValue:e,className:Zt("w-full",n),children:t}),tae=({value:t,title:e,description:n,dataCy:r,icon:s,children:i,className:o=""})=>{const l=o.includes("first-item");return S.jsxs(hD,{value:t,className:Zt("w-full",!l&&"border-t border-main-border"),children:[S.jsxs(pD,{"data-cy":r,children:[s?S.jsx("span",{className:"mr-1 inline-flex items-center",children:s}):null,e]}),S.jsxs(mD,{children:[n?S.jsx("p",{className:"pb-2 text-sm text-content-subtle",children:n}):null,i]})]})};Im.Item=tae;const nae=({message:t,isLoading:e=!0})=>S.jsxs("div",{className:"flex items-center gap-2 text-sm text-content",children:[e?S.jsx(tv,{className:"h-4 w-4 shrink-0 animate-spin text-primary",weight:"bold"}):null,S.jsx("span",{className:"whitespace-pre-wrap font-sans",children:t})]}),rae=()=>{const t=g.useRef(Date.now()),[e,n]=g.useState(0);return g.useEffect(()=>{const r=()=>n(Math.max(0,Math.floor((Date.now()-t.current)/1e3)));r();const s=setInterval(r,1e3);return()=>clearInterval(s)},[]),e},sae=t=>{const e=Math.floor(t/60),n=t%60;return`${e}:${n.toString().padStart(2,"0")}`},YA="M 12 8 C 14.21 8 16 9.79 16 12 C 16 14.21 14.21 16 12 16 C 9.79 16 8 14.21 8 12 C 8 9.79 9.79 8 12 8 Z",XA="M 12 12 C 14 8.5 19 8.5 19 12 C 19 15.5 14 15.5 12 12 C 10 8.5 5 8.5 5 12 C 5 15.5 10 15.5 12 12 Z",iae="M 12 16 C 14.21 16 16 14.21 16 12 C 16 9.79 14.21 8 12 8 C 9.79 8 8 9.79 8 12 C 8 14.21 9.79 16 12 16 Z",Mm=["Applying","Thinking","Planning","Crafting"],oae=Mm.reduce((t,e)=>t.length>=e.length?t:e),aae=20,lae="Still working — runs can take a few minutes.",cae=({hint:t,showElapsed:e=!0})=>{const[n,r]=g.useState(0),s=rae();g.useEffect(()=>{const o=setInterval(()=>{r(l=>(l+1)%Mm.length)},4e3);return()=>clearInterval(o)},[]);const i=t??(e&&s>=aae?lae:null);return S.jsxs("div",{role:"status",className:"flex items-center gap-2 px-3 py-1","data-cy":"thinking-indicator",children:[S.jsx(ki.svg,{"aria-hidden":!0,width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0 text-muted-foreground",children:S.jsx(ki.path,{animate:{d:[YA,XA,iae,XA,YA]},transition:{d:{duration:6,ease:"easeInOut",repeat:1/0,times:[0,.25,.5,.75,1]}}})}),S.jsxs("span",{className:"inline-grid overflow-hidden text-sm font-medium",style:{fontVariationSettings:ah.medium},children:[S.jsx("span",{className:"shimmer-text invisible col-start-1 row-start-1","aria-hidden":"true",children:oae}),S.jsx(As,{mode:"popLayout",initial:!1,children:S.jsx(ki.span,{className:"shimmer-text col-start-1 row-start-1",initial:{y:"80%",opacity:0},animate:{y:0,opacity:1,transition:{duration:.24,ease:[.4,0,.2,1]}},exit:{y:"-80%",opacity:0,transition:{duration:.16,ease:[.4,0,.2,1]}},children:Mm[n]},Mm[n])})]}),e?S.jsx("span",{className:"text-xs tabular-nums text-content-subtle","data-cy":"thinking-elapsed",children:sae(s)}):null,i?S.jsx("span",{className:"text-xs text-content-subtle",children:i}):null]})};var uae=Object.defineProperty,dae=(t,e)=>uae(t,"name",{value:e,configurable:!0});function Vg(t,[e,n]){return Math.min(n,Math.max(e,t))}dae(Vg,"clamp");var fae=Object.defineProperty,It=(t,e)=>fae(t,"name",{value:e,configurable:!0}),QA={Horizontal:"horizontal"},hae={LTR:"ltr"},gD=["PageUp","PageDown"],vD=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],yD={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},up="Slider",[Ax,pae,mae]=tN(up),[t6,ale]=so(up,[mae]),[gae,Od]=t6(up),vae=g.forwardRef(It(function(e,n){const{name:r,min:s=0,max:i=100,step:o=1,orientation:l=QA.Horizontal,disabled:u=!1,minStepsBetweenThumbs:d=0,preserveThumbOrder:f=!1,defaultValue:h=[s],value:m,onValueChange:v=It(()=>{},"onValueChange"),onValueCommit:w=It(()=>{},"onValueCommit"),inverted:_=!1,form:x,...b}=e,k=g.useRef(new Set),C=g.useRef(0),P=g.useRef(!1),[T,M]=g.useState(null),R=l===QA.Horizontal?yae:_ae,[L,j]=g.useState(null),F=Xt(n,j),[N=[],q]=dl({prop:m,defaultProp:h,onChange:It(V=>{var G;(G=[...k.current][C.current])==null||G.focus({preventScroll:!0,focusVisible:P.current}),P.current=!1,v(V)},"onChange")}),W=g.useRef(N),Y=g.useRef(N);g.useEffect(()=>{const V=x?L==null?void 0:L.ownerDocument.getElementById(x):L==null?void 0:L.closest("form");if(V instanceof HTMLFormElement){const D=It(()=>q(Y.current),"reset");return V.addEventListener("reset",D),()=>V.removeEventListener("reset",D)}},[L,x,q]);function H(V){const D=CD(N,V);Q(V,D)}It(H,"handleSlideStart");function J(V){Q(V,C.current)}It(J,"handleSlideMove");function B(){String(N)!==String(W.current)&&w(N)}It(B,"handleSlideEnd");function Q(V,D,{commit:G}={commit:!1}){const le=r6(o),re=fh(Math.round((V-s)/o)*o+s,le),ie=Vg(re,[s,i]),ue=d*o;function fe(ne){const Ce=f?Vg(ie,[ne[D-1]===void 0?s:ne[D-1]+ue,ne[D+1]===void 0?i:ne[D+1]-ue]):ie,De=kD(ne,Ce,D);return TD(De,ue)?{nextValues:De,changedIndex:f?D:De.indexOf(Ce),hasChanged:String(De)!==String(ne)}:null}It(fe,"getNextValues");const de=fe(N);de!=null&&de.hasChanged&&M(de.nextValues),q((ne=[])=>{const Ce=fe(ne);return Ce?(C.current=Ce.changedIndex,Ce.hasChanged&&G&&w(Ce.nextValues),Ce.hasChanged?Ce.nextValues:ne):ne})}return It(Q,"updateValues"),S.jsx(gae,{scope:e.__scopeSlider,name:r,disabled:u,min:s,max:i,valueIndexToChangeRef:C,thumbs:k.current,values:N,orientation:l,form:x,userRequestedValues:T,children:S.jsx(Ax.Provider,{scope:e.__scopeSlider,children:S.jsx(Ax.Slot,{scope:e.__scopeSlider,children:S.jsx(R,{"aria-disabled":u,"data-disabled":u?"":void 0,...b,ref:F,onPointerDown:Yt(b.onPointerDown,()=>{u||(W.current=N,P.current=!1)}),min:s,max:i,inverted:_,onSlideStart:u?void 0:H,onSlideMove:u?void 0:J,onSlideEnd:u?void 0:B,onHomeKeyDown:()=>{u||(P.current=!0,Q(s,0,{commit:!0}))},onEndKeyDown:()=>{u||(P.current=!0,Q(i,N.length-1,{commit:!0}))},onStepKeyDown:({event:V,direction:D})=>{if(!u){P.current=!0;const re=gD.includes(V.key)||V.shiftKey&&vD.includes(V.key)?10:1,ie=C.current,ue=N[ie],fe=RD(ue,{min:s,step:o,direction:D,multiplier:re});Q(fe,ie,{commit:!0})}}})})})})},"Slider")),[_D,wD]=t6(up,{startEdge:"left",endEdge:"right",size:"width",direction:1}),yae=g.forwardRef(It(function(e,n){const{min:r,max:s,dir:i,inverted:o,onSlideStart:l,onSlideMove:u,onSlideEnd:d,onStepKeyDown:f,...h}=e,[m,v]=g.useState(null),w=Xt(n,v),_=g.useRef(void 0),x=KS(i),b=x===hae.LTR,k=b&&!o||!b&&o;function C(P){const T=_.current||m.getBoundingClientRect(),M=[0,T.width],R=Av(M,k?[r,s]:[s,r]);return _.current=T,R(P-T.left)}return It(C,"getValueFromPointer"),S.jsx(_D,{scope:e.__scopeSlider,startEdge:k?"left":"right",endEdge:k?"right":"left",direction:k?1:-1,size:"width",children:S.jsx(xD,{dir:x,"data-orientation":"horizontal",...h,ref:w,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:P=>{const T=C(P.clientX);l==null||l(T)},onSlideMove:P=>{const T=C(P.clientX);u==null||u(T)},onSlideEnd:()=>{_.current=void 0,d==null||d()},onStepKeyDown:P=>{const M=yD[k?"from-left":"from-right"].includes(P.key);f==null||f({event:P,direction:M?-1:1})}})})},"SliderHorizontal")),_ae=g.forwardRef(It(function(e,n){const{min:r,max:s,inverted:i,onSlideStart:o,onSlideMove:l,onSlideEnd:u,onStepKeyDown:d,...f}=e,h=g.useRef(null),m=Xt(n,h),v=g.useRef(void 0),w=!i;function _(x){const b=v.current||h.current.getBoundingClientRect(),k=[0,b.height],P=Av(k,w?[s,r]:[r,s]);return v.current=b,P(x-b.top)}return It(_,"getValueFromPointer"),S.jsx(_D,{scope:e.__scopeSlider,startEdge:w?"bottom":"top",endEdge:w?"top":"bottom",size:"height",direction:w?1:-1,children:S.jsx(xD,{"data-orientation":"vertical",...f,ref:m,style:{...f.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:x=>{const b=_(x.clientY);o==null||o(b)},onSlideMove:x=>{const b=_(x.clientY);l==null||l(b)},onSlideEnd:()=>{v.current=void 0,u==null||u()},onStepKeyDown:x=>{const k=yD[w?"from-bottom":"from-top"].includes(x.key);d==null||d({event:x,direction:k?-1:1})}})})},"SliderVertical")),xD=g.forwardRef(It(function(e,n){const{__scopeSlider:r,onSlideStart:s,onSlideMove:i,onSlideEnd:o,onHomeKeyDown:l,onEndKeyDown:u,onStepKeyDown:d,...f}=e,h=Od(up,r);return S.jsx(Pn.span,{...f,ref:n,onKeyDown:Yt(e.onKeyDown,m=>{m.key==="Home"?(l(m),m.preventDefault()):m.key==="End"?(u(m),m.preventDefault()):gD.concat(vD).includes(m.key)&&(d(m),m.preventDefault())}),onPointerDown:Yt(e.onPointerDown,m=>{const v=m.target;v.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(v)?v.focus({preventScroll:!0,focusVisible:!1}):s(m)}),onPointerMove:Yt(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&i(m)}),onPointerUp:Yt(e.onPointerUp,m=>{const v=m.target;v.hasPointerCapture(m.pointerId)&&(v.releasePointerCapture(m.pointerId),o(m))})})},"SliderImpl")),wae="SliderTrack",xae=g.forwardRef(It(function(e,n){const{__scopeSlider:r,...s}=e,i=Od(wae,r);return S.jsx(Pn.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...s,ref:n})},"SliderTrack")),JA="SliderRange",bae=g.forwardRef(It(function(e,n){const{__scopeSlider:r,...s}=e,i=Od(JA,r),o=wD(JA,r),l=g.useRef(null),u=Xt(n,l),d=i.values.length,f=i.values.map(v=>n6(v,i.min,i.max)),h=d>1?Math.min(...f):0,m=100-Math.max(...f);return S.jsx(Pn.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...s,ref:u,style:{...e.style,[o.startEdge]:h+"%",[o.endEdge]:m+"%"}})},"SliderRange")),Sae="SliderThumb",[kae,bD]=t6(Sae),Eae="SliderThumbProvider";function SD(t){const{__scopeSlider:e,name:n,children:r,internal_do_not_use_render:s}=t,i=Od(Eae,e),o=pae(e),[l,u]=g.useState(null),d=g.useMemo(()=>l?o().findIndex(x=>x.ref.current===l):-1,[o,l]),f=aS(l),h=l?!!i.form||!!l.closest("form"):!0,m=i.values[d],v=n??(i.name?i.name+(i.values.length>1?"[]":""):void 0),w=m===void 0?0:n6(m,i.min,i.max);g.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]);const _={value:m,name:v,form:i.form,isFormControl:h,index:d,thumb:l,onThumbChange:u,percent:w,size:f};return S.jsx(kae,{scope:e,..._,children:ID(s)?s(_):r})}It(SD,"SliderThumbProvider");var e2="SliderThumbTrigger",Cae=g.forwardRef(It(function(e,n){const{__scopeSlider:r,...s}=e,i=Od(e2,r),o=wD(e2,r),{index:l,value:u,percent:d,size:f,onThumbChange:h}=bD(e2,r),m=Xt(n,h),v=ED(l,i.values.length),w=f==null?void 0:f[o.size],_=w?PD(w,d,o.direction):0;return S.jsx("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[o.startEdge]:`calc(${d}% + ${_}px)`},children:S.jsx(Ax.ItemSlot,{scope:r,children:S.jsx(Pn.span,{role:"slider","aria-label":e["aria-label"]||v,"aria-valuemin":i.min,"aria-valuenow":u,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...s,ref:m,style:u===void 0?{display:"none"}:e.style,onFocus:Yt(e.onFocus,()=>{i.valueIndexToChangeRef.current=l})})})})},"SliderThumbTrigger")),Pae=g.forwardRef(It(function(e,n){const{__scopeSlider:r,name:s,...i}=e;return S.jsx(SD,{__scopeSlider:r,name:s,internal_do_not_use_render:({index:o,isFormControl:l})=>S.jsxs(S.Fragment,{children:[S.jsx(Cae,{...i,ref:n,__scopeSlider:r}),l?S.jsx(Aae,{__scopeSlider:r},o):null]})})},"SliderThumb")),e5="SliderBubbleInput",Aae=g.forwardRef(It(function({__scopeSlider:e,onInput:n,...r},s){const{index:i,value:o,name:l,form:u}=bD(e5,e),{userRequestedValues:d}=Od(e5,e),f=g.useRef(null),h=Xt(f,s),m=g.useRef(!1),v=g.useRef(o),w=g.useRef(d),_=g.useRef(d);return g.useEffect(()=>{const x=f.current;if(!x)return;const b=window.HTMLInputElement.prototype,C=Object.getOwnPropertyDescriptor(b,"value").set,P=v.current,T=P!==o;v.current=o;const M=d!==_.current;if(_.current=d,T&&C){const I=d!==w.current;w.current=d;const R=d==null?void 0:d[i],L=I&&(M&&R!==P||R===o);m.current=!L;const j=new Event("input",{bubbles:!0});C.call(x,o),x.dispatchEvent(j),m.current=!1}},[i,o,d]),S.jsx(Pn.input,{style:{display:"none"},name:l,form:u,...r,ref:h,defaultValue:o,onInput:Yt(n,x=>{m.current&&x.stopPropagation()})})},"SliderBubbleInput"));function kD(t=[],e,n){const r=[...t];return r[n]=e,r.sort((s,i)=>s-i)}It(kD,"getNextSortedValues");function n6(t,e,n){const i=100/(n-e)*(t-e);return Vg(i,[0,100])}It(n6,"convertValueToPercentage");function ED(t,e){return e>2?`Value ${t+1} of ${e}`:e===2?["Minimum","Maximum"][t]:void 0}It(ED,"getLabel");function CD(t,e){if(t.length===1)return 0;const n=t.map(s=>Math.abs(s-e)),r=Math.min(...n);return n.indexOf(r)}It(CD,"getClosestValueIndex");function PD(t,e,n){const r=t/2,i=Av([0,50],[0,r]);return(r-i(e)*n)*n}It(PD,"getThumbInBoundsOffset");function AD(t){return t.slice(0,-1).map((e,n)=>t[n+1]-e)}It(AD,"getStepsBetweenValues");function TD(t,e){if(e>0){const n=AD(t);return Math.min(...n)>=e}return!0}It(TD,"hasMinStepsBetweenValues");function Av(t,e){return n=>{if(t[0]===t[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(t[1]-t[0]);return e[0]+r*(n-t[0])}}It(Av,"linearScale");function r6(t){if(!Number.isFinite(t))return 0;const e=t.toString();if(e.includes("e")){const[r,s]=e.split("e"),i=r.split(".")[1]||"",o=Number(s);return Math.max(0,i.length-o)}const n=e.split(".")[1];return n?n.length:0}It(r6,"getDecimalCount");function fh(t,e){const n=Math.pow(10,e);return Math.round(t*n)/n}It(fh,"roundValue");function RD(t,{min:e,step:n,direction:r,multiplier:s}){const i=r6(n),o=(t-e)/n,l=Math.round(o),u=fh(l*n+e,i)===fh(t,i);let d;return u?d=l+s*r:r>0?d=Math.ceil(o):d=Math.floor(o),fh(d*n+e,i)}It(RD,"getNextStepValue");function ID(t){return typeof t=="function"}It(ID,"isFunction");const Tx=g.forwardRef(({className:t,...e},n)=>S.jsxs(vae,{ref:n,className:Zt("relative flex w-full touch-none select-none items-center","data-[disabled]:opacity-50",t),...e,children:[S.jsx(xae,{className:"relative h-1 w-full grow overflow-hidden rounded-full bg-input",children:S.jsx(bae,{className:"absolute h-full bg-primary"})}),S.jsx(Pae,{className:Zt("block h-3.5 w-3.5 rounded-full border border-border bg-foreground shadow-sm","transition-transform hover:scale-110 active:scale-95","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#6B97FF]","disabled:pointer-events-none")})]}));Tx.displayName="Slider";const Tae=[{name:"surface-1",utility:"bg-surface-1",className:"bg-surface-1"},{name:"surface-2",utility:"bg-surface-2",className:"bg-surface-2"},{name:"surface-3",utility:"bg-surface-3",className:"bg-surface-3"},{name:"surface-4",utility:"bg-surface-4",className:"bg-surface-4"},{name:"surface-5",utility:"bg-surface-5",className:"bg-surface-5"},{name:"surface-6",utility:"bg-surface-6",className:"bg-surface-6"}],Rae=[{name:"primary",utility:"bg-primary",className:"bg-primary"},{name:"selected",utility:"bg-selected",className:"bg-selected"},{name:"accent",utility:"bg-accent",className:"bg-accent"},{name:"success",utility:"bg-accent-success",className:"bg-accent-success"},{name:"warning",utility:"bg-accent-warning",className:"bg-accent-warning"},{name:"error",utility:"bg-accent-error",className:"bg-accent-error"}],Iae=[{name:"gap-1",className:"w-1"},{name:"gap-2",className:"w-2"},{name:"gap-3",className:"w-3"},{name:"gap-4",className:"w-4"},{name:"gap-6",className:"w-6"},{name:"gap-8",className:"w-8"}],J0=[{name:"Accordion",path:"components/Accordion.tsx",status:"showcased",note:"Reusable primitive shown with local item composition."},{name:"AgentVariantsPanel",path:"components/AgentVariantsPanel.tsx",status:"feature-only",note:"Requires live variant session state and editor atoms."},{name:"AuthProgressScreen",path:"components/AuthProgressScreen.tsx",status:"feature-only",note:"Auth flow surface; represented through progress treatment."},{name:"AuthScreenView",path:"components/AuthScreenView.tsx",status:"feature-only",note:"Auth flow surface that depends on sign-in actions."},{name:"Button",path:"components/Button.tsx",status:"showcased",note:"Reusable tooltip-wrapped button shown in multiple states."},{name:"CommentCarouselLayer",path:"components/CommentCarouselLayer.tsx",status:"feature-only",note:"Preview overlay layer tied to iframe geometry."},{name:"ElementInspector",path:"components/ElementInspector.tsx",status:"feature-only",note:"Primary editor surface with many app-level dependencies."},{name:"GitHome",path:"components/GitHome.tsx",status:"feature-only",note:"Git dashboard tied to repository state."},{name:"IframePreview",path:"components/IframePreview.tsx",status:"unsuitable",note:"Needs live iframe target and cross-window integration."},{name:"PreviewFrame",path:"components/PreviewFrame.tsx",status:"unsuitable",note:"Requires proxied app URL and iframe lifecycle."},{name:"PreviewSurface",path:"components/PreviewSurface.tsx",status:"unsuitable",note:"Requires preview iframe and overlay orchestration."},{name:"ProfileAvatar",path:"components/ProfileAvatar.tsx",status:"feature-only",note:"Account chrome tied to user identity data."},{name:"Progress",path:"components/Progress.tsx",status:"showcased",note:"Reusable inline loading/status primitive."},{name:"SecondaryVariantIframe",path:"components/SecondaryVariantIframe.tsx",status:"unsuitable",note:"Requires variant preview iframe lifecycle."},{name:"SparkleLoader",path:"components/SparkleLoader.tsx",status:"showcased",note:"Reusable loading animation shown in feedback states."},{name:"SplitButton",path:"components/SplitButton.tsx",status:"showcased",note:"Reusable compound action button shown with dropdown."},{name:"StatusSurface",path:"components/StatusSurface.tsx",status:"showcased",note:"Unified full-surface primitive: LoadingSurface / EmptyState / ErrorState."},{name:"SupportTicketModal",path:"components/SupportTicketModal.tsx",status:"feature-only",note:"Support workflow modal tied to form submission."},{name:"ThinkingIndicator",path:"components/ThinkingIndicator.tsx",status:"showcased",note:"Reusable thinking/loading indicator shown in feedback states."},{name:"Tooltip",path:"components/Tooltip.tsx",status:"showcased",note:"Reusable tooltip API shown with hover target."},{name:"VariantDragGhost",path:"components/VariantDragGhost.tsx",status:"feature-only",note:"Drag visual tied to variant split interactions."},{name:"VariantSplitDropZones",path:"components/VariantSplitDropZones.tsx",status:"feature-only",note:"Drop-zone visual tied to variant split interactions."},{name:"ui/accordion",path:"components/ui/accordion.tsx",status:"showcased",note:"Radix accordion primitive backing the local Accordion showcase."},{name:"ui/slider",path:"components/ui/slider.tsx",status:"showcased",note:"Radix slider primitive shown in enabled and disabled states."},{name:"ui/tooltip",path:"components/ui/tooltip.tsx",status:"showcased",note:"Radix tooltip primitive shown with forced-open preview."}],Mae=()=>{window.location.hash=""},Po=({title:t,eyebrow:e,description:n,children:r})=>S.jsxs("section",{className:"border-border bg-card shadow-surface-3 rounded-2xl border p-5",children:[S.jsxs("div",{className:"mb-5 max-w-2xl",children:[S.jsx("p",{className:"text-primary text-xs font-semibold tracking-[0.18em] uppercase",children:e}),S.jsx("h2",{className:"text-foreground mt-2 text-xl font-semibold",children:t}),S.jsx("p",{className:"text-muted-foreground mt-2 text-sm leading-6",children:n})]}),r]}),t5=({swatches:t})=>S.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:t.map(e=>S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-3",children:[S.jsx("div",{className:`h-16 rounded-lg ${e.className}`}),S.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[S.jsx("span",{className:"text-foreground text-sm font-medium",children:e.name}),S.jsx("code",{className:"bg-muted text-muted-foreground rounded px-2 py-1 text-xs",children:e.utility})]})]},e.name))}),Oae=t=>t==="showcased"?"border-accent-success/40 bg-accent-success/10 text-accent-success":t==="cataloged"?"border-primary/40 bg-primary/10 text-primary":t==="generated"?"border-accent/40 bg-accent/10 text-accent":t==="unsuitable"?"border-accent-warning/40 bg-accent-warning/10 text-accent-warning":"border-border bg-surface-4 text-content-muted",Lae=()=>{const t=J0.filter(n=>n.status==="showcased").length,e=J0.filter(n=>n.status==="cataloged").length;return S.jsx("main",{className:"bg-main font-main text-content h-screen overflow-y-auto",children:S.jsxs("div",{className:"mx-auto flex w-full max-w-6xl flex-col gap-6 px-6 py-6 lg:px-8",children:[S.jsxs("header",{className:"border-border bg-surface-2 shadow-surface-4 rounded-3xl border p-6",children:[S.jsxs("button",{type:"button",onClick:Mae,className:"text-content-subtle hover:text-content mb-6 inline-flex items-center gap-2 text-sm transition-colors",children:[S.jsx(sY,{className:"h-4 w-4",weight:"bold"}),"Back to editor"]}),S.jsxs("div",{className:"flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between",children:[S.jsxs("div",{className:"max-w-3xl",children:[S.jsx("p",{className:"text-primary text-xs font-semibold tracking-[0.22em] uppercase",children:"Local component gallery"}),S.jsx("h1",{className:"text-foreground mt-3 text-4xl font-semibold tracking-tight",children:"Rivet design system"}),S.jsx("p",{className:"text-muted-foreground mt-3 text-base leading-7",children:"A Storybook-like route for checking the current UI primitives, tokens, and interaction states inside the Vite app."})]}),S.jsx("div",{className:"border-border bg-surface-3 rounded-2xl border p-4",children:S.jsxs("div",{className:"text-content-muted flex items-center gap-3 text-sm",children:[S.jsx(w3,{className:"text-primary h-5 w-5",weight:"bold"}),"Open with ",S.jsx("code",{className:"text-content",children:"#/design-system"})]})})]})]}),S.jsx(Po,{eyebrow:"Controls",title:"Button, split button, and tooltip",description:"Rivet's shared Button exposes variants and sizes backed by Fluid Functionalism, alongside the split button and tooltip controls.",children:S.jsxs("div",{className:"grid gap-4 lg:grid-cols-[1fr_1fr]",children:[S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-foreground mb-3 text-sm font-medium",children:"Rivet Button"}),S.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[S.jsx(Qi,{title:"Primary action",shortcut:"D",variant:"primary",children:"Design action"}),S.jsx(Qi,{title:"Secondary action",variant:"secondary",children:"Secondary"}),S.jsx(Qi,{title:"Disabled action",disabled:!0,variant:"tertiary",children:"Disabled"}),S.jsx(I9,{primaryLabel:"Ship",primaryIcon:__,primaryAction:()=>{},dropdownItems:[{label:"Create PR",onClick:()=>{}},{label:"Copy branch",onClick:()=>{}}]})]})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-foreground mb-3 text-sm font-medium",children:"Tooltip states"}),S.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[S.jsx(Tc,{label:"Rivet tooltip API",side:"bottom",children:S.jsx("button",{className:"border-border bg-surface-4 text-content rounded-lg border px-4 py-2 text-sm",children:"Hover target"})}),S.jsx(fS,{content:"Forced open preview",forceOpen:!0,side:"right",children:S.jsx("button",{className:"bg-selected text-content rounded-lg px-4 py-2 text-sm",children:"UI tooltip"})})]})]})]})}),S.jsx(Po,{eyebrow:"Tokens",title:"Surface ladder",description:"Surface tokens move from the base app background toward raised panels without leaving the dark Rivet palette.",children:S.jsx(t5,{swatches:Tae})}),S.jsx(Po,{eyebrow:"Tokens",title:"Color roles",description:"Named roles should communicate purpose: brand, selection, neutral accent, and outcome colors.",children:S.jsx(t5,{swatches:Rae})}),S.jsx(Po,{eyebrow:"Type",title:"Typography",description:"Satoshi remains the default UI voice with clear hierarchy and muted support text.",children:S.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-primary text-xs tracking-[0.18em] uppercase",children:"Display"}),S.jsx("p",{className:"text-foreground mt-2 text-3xl font-semibold tracking-tight",children:"Visual edits, quickly"})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-foreground text-sm font-semibold",children:"Panel heading"}),S.jsx("p",{className:"text-muted-foreground mt-2 text-sm leading-6",children:"Body copy uses compact line height and muted contrast for dense inspector panels."})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-content-subtle text-xs font-medium tracking-[0.16em] uppercase",children:"Micro label"}),S.jsx("code",{className:"bg-muted text-muted-foreground mt-3 block rounded-lg px-3 py-2 text-xs",children:"font-main text-content"})]})]})}),S.jsx(Po,{eyebrow:"Layout",title:"Spacing rhythm",description:"A compact spacing scale keeps editor chrome dense while preserving scannable groupings.",children:S.jsx("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:S.jsx("div",{className:"flex flex-col gap-3",children:Iae.map(n=>S.jsxs("div",{className:"flex items-center gap-4",children:[S.jsx("code",{className:"text-muted-foreground w-16 text-xs",children:n.name}),S.jsx("div",{className:`${n.className} bg-primary h-4 rounded`}),S.jsx("div",{className:"bg-border h-px flex-1"})]},n.name))})})}),S.jsx(Po,{eyebrow:"Primitives",title:"Accordion and slider",description:"Representative Radix primitives styled through the local component layer.",children:S.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[S.jsxs(Im,{defaultValue:["foundations"],className:"border-border bg-surface-2 rounded-xl border p-2",children:[S.jsx(Im.Item,{value:"foundations",title:"Foundations",description:"Tokens, surfaces, type, and spacing.",className:"first-item",icon:S.jsx(__,{className:"text-primary h-4 w-4"}),children:S.jsx("p",{children:"Use these pieces before adding one-off visual rules."})}),S.jsx(Im.Item,{value:"components",title:"Components",description:"Buttons, tooltips, accordions, sliders.",children:S.jsx("p",{children:"Keep states visible in this route as the system evolves."})})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-5",children:[S.jsx("p",{className:"text-foreground mb-5 text-sm font-medium",children:"Slider states"}),S.jsxs("div",{className:"space-y-6",children:[S.jsx(Tx,{defaultValue:[64],max:100,step:1}),S.jsx(Tx,{defaultValue:[36],max:100,step:1,disabled:!0})]})]})]})}),S.jsx(Po,{eyebrow:"Feedback",title:"Motion and loading",description:"Loading states use existing CSS animation utilities and avoid per-frame React work where possible.",children:S.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-foreground mb-4 text-sm font-medium",children:"Progress"}),S.jsx(nae,{message:"Applying visual change..."})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-foreground mb-4 text-sm font-medium",children:"Sparkle strip"}),S.jsx(kS,{className:"text-primary text-xl"})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-foreground mb-4 text-sm font-medium",children:"Shimmer text"}),S.jsx("span",{className:"shimmer-text text-sm font-medium",children:"Generating variants"})]}),S.jsx("div",{className:"border-border bg-surface-2 rounded-xl border p-4 sm:col-span-3",children:S.jsx(cae,{hint:"Reading selected elements"})})]})}),S.jsx(Po,{eyebrow:"Feedback",title:"Status surfaces",description:"The unified full-surface system: one StatusSurface primitive with LoadingSurface / EmptyState / ErrorState wrappers. Every full-page loading, empty, and error state routes through these so they share layout, copy tone, and a single status_surface_shown impression event. Inline loaders (Sparkle, ThinkingIndicator, above) stay inline and are deliberately not part of this system.",children:S.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[S.jsx("div",{className:"border-border relative h-56 overflow-hidden rounded-xl border",children:S.jsx(ux,{fill:"surface",loader:"coalesce",trackGlobalLoaderCount:!1})}),S.jsx("div",{className:"border-border relative h-56 overflow-hidden rounded-xl border",children:S.jsx(nL,{icon:S.jsx(__,{size:32}),title:"Nothing to preview yet",description:"Pick a direction from the panel."})}),S.jsx("div",{className:"border-border relative h-56 overflow-hidden rounded-xl border",children:S.jsx(CS,{fill:"surface",size:"sm",title:"Preview isn't connected",description:"Rivet lost connection to your project.",actions:[{label:"Reload",onClick:()=>{}}]})})]})}),S.jsxs(Po,{eyebrow:"Inventory",title:"Component coverage",description:"Every current component file is accounted for here. Reusable primitives are rendered above; app surfaces that need live editor, git, auth, iframe, or generated state are cataloged instead of mounted unsafely.",children:[S.jsxs("div",{className:"mb-4 grid gap-3 sm:grid-cols-3",children:[S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-content-subtle text-xs tracking-[0.16em] uppercase",children:"Total components"}),S.jsx("p",{className:"text-foreground mt-2 text-2xl font-semibold",children:J0.length})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-content-subtle text-xs tracking-[0.16em] uppercase",children:"Showcased"}),S.jsx("p",{className:"text-accent-success mt-2 text-2xl font-semibold",children:t})]}),S.jsxs("div",{className:"border-border bg-surface-2 rounded-xl border p-4",children:[S.jsx("p",{className:"text-content-subtle text-xs tracking-[0.16em] uppercase",children:"Cataloged"}),S.jsx("p",{className:"text-primary mt-2 text-2xl font-semibold",children:e})]})]}),S.jsxs("div",{className:"border-border overflow-hidden rounded-xl border",children:[S.jsxs("div",{className:"border-border bg-surface-3 text-content-subtle grid grid-cols-[minmax(140px,1fr)_minmax(110px,auto)_minmax(220px,2fr)] border-b px-4 py-3 text-xs font-semibold tracking-[0.14em] uppercase",children:[S.jsx("span",{children:"Component"}),S.jsx("span",{children:"Status"}),S.jsx("span",{children:"Coverage note"})]}),S.jsx("div",{className:"divide-border bg-surface-2 divide-y",children:J0.map(n=>S.jsxs("div",{className:"grid grid-cols-[minmax(140px,1fr)_minmax(110px,auto)_minmax(220px,2fr)] gap-3 px-4 py-3 text-sm",children:[S.jsxs("div",{children:[S.jsx("p",{className:"text-foreground font-medium",children:n.name}),S.jsx("code",{className:"text-muted-foreground text-xs",children:n.path})]}),S.jsx("div",{children:S.jsx("span",{className:`inline-flex rounded-full border px-2 py-1 text-xs font-medium ${Oae(n.status)}`,children:n.status})}),S.jsx("p",{className:"text-muted-foreground",children:n.note})]},n.path))})]})]})]})})},Nae=t=>(t.startsWith("#/")?t.slice(2):t.slice(1)).split("?")[0]==="design-system"?"design-system":"editor",Rx=274,Hg=395,t2=Math.min(Hg,Math.round((Rx+Hg)/2*1.1)),n5="rivet:panelWidth:v2",Dae=({projectPath:t,libraryOrigin:e})=>{const n=dt(S9)>0,[r,s]=mI(x9),i=nK(),[o,l]=g.useState(()=>{if(typeof window>"u")return t2;const T=Number(window.localStorage.getItem(n5));return Number.isFinite(T)&&T>=Rx&&T<=Hg?T:t2}),[u,d]=g.useState(!1),[f,h]=g.useState(eie),m=r?o:0,[v,w]=g.useState(r);g.useEffect(()=>{if(!r){w(!1);return}h(T=>Jse({position:T,boundsLeftPx:o}))},[r,o]),g.useEffect(()=>{window.localStorage.setItem(n5,String(o))},[o]),g.useEffect(()=>{if(!r)return;const T=M=>{M.key==="Escape"&&(lI(M.target)||(M.preventDefault(),s(!1)))};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[r,s]);const _=g.useCallback(T=>{T.preventDefault(),T.stopPropagation();const M=T.clientX,I=o;d(!0);const R=j=>{const F=Math.min(Hg,Math.max(Rx,I+(j.clientX-M)));l(F)},L=()=>{window.removeEventListener("pointermove",R),window.removeEventListener("pointerup",L),window.removeEventListener("pointercancel",L),d(!1)};window.addEventListener("pointermove",R),window.addEventListener("pointerup",L),window.addEventListener("pointercancel",L)},[o]),x=g.useCallback(()=>l(t2),[]),b=pie(),k=dt(_v);vie({enabled:!k});const C=b.isProcessing?"Completing authentication...":null,P=yt(yv);return g.useEffect(()=>{P(t??null)},[t,P]),S.jsxs(ki.div,{className:"relative flex h-screen overflow-hidden",initial:!1,animate:{opacity:1},transition:{duration:.5,ease:"easeOut"},"data-cy":"rivet-app",children:[C!==null?S.jsx("div",{className:"absolute inset-0 z-50",children:S.jsx(Vse,{message:C})}):null,S.jsx(pre,{}),S.jsx(S.Fragment,{children:n?null:S.jsxs(S.Fragment,{children:[S.jsx("div",{className:"relative order-first h-full flex-shrink-0",style:{width:v?o:0},children:S.jsxs(ki.div,{className:"absolute inset-y-0 left-0 z-30",initial:!1,animate:{x:r?0:-o},transition:i?{duration:0}:{duration:.2,ease:[.22,1,.36,1]},onAnimationComplete:()=>{r&&w(!0)},style:{width:o,willChange:"transform"},children:[S.jsx(Ene,{onClose:()=>s(!1),libraryOrigin:e}),S.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panel",onPointerDown:_,onDoubleClick:x,className:"group/resize absolute inset-y-0 right-0 z-20 flex w-3 cursor-col-resize touch-none justify-end",children:S.jsx("span",{className:`h-full transition-all duration-150 ${u?"bg-content-muted w-0.5":"bg-divider group-hover/resize:bg-content-muted w-px group-hover/resize:w-0.5"}`})})]})}),u&&S.jsx("div",{className:"fixed inset-0 z-[100] cursor-col-resize"}),S.jsx(rie,{isVisible:!0,isPanelOpen:r,isReducedMotion:!!i,position:f,dragBoundsLeftPx:m,onPositionChange:h,onToggle:()=>s(T=>!T)})]})}),S.jsx(MK,{duration:5e3,richColors:!0,toastOptions:{style:{maxHeight:"150px",overflow:"hidden"}}})]})},Ix="rivet_connect_deep_link",jae=()=>{if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search),e=t.get("connect"),n=e??window.sessionStorage.getItem(Ix);if(n!=="pinterest"&&n!=="arena"&&n!=="x")return null;if(window.sessionStorage.setItem(Ix,n),e){t.delete("connect");const r=t.toString();window.history.replaceState(null,document.title,window.location.pathname+(r?`?${r}`:"")+window.location.hash)}return n},$ae=jae(),Fae=()=>{const[t,e]=g.useState(window.location.hash),[n]=g.useState(()=>typeof window<"u"&&window.sessionStorage.getItem(Ig)==="1"),[r,s]=g.useState(!1),[i,o]=g.useState($ae);g.useEffect(()=>{n&&window.sessionStorage.removeItem(Ig)},[n]);const{config:l,refetchConfig:u,loading:d,error:f}=hie(),h=yt(_v),{startLogin:m,isStartingLogin:v,loginError:w}=G9(),[_,x]=g.useState(!1);g.useEffect(()=>{Z2()&&(l!=null&&l.userId?($e.identify(l.userId,{...l.email?{email:l.email}:{}}),l.email&&$e.alias(l.email,l.userId)):l!=null&&l.email&&$e.identify(l.email,{email:l.email}))},[l==null?void 0:l.userId,l==null?void 0:l.email]),g.useEffect(()=>{l&&$e.register({source:"visual_editor",surface:"visual_editor"})},[l]);const b=l!=null&&l.agentModeAvailable!==!0,k=Nae(t),C=g.useCallback(async()=>{x(!0),h(!0);try{await u()}finally{h(!1),x(!1)}},[u,h]);if(g.useEffect(()=>{const I=()=>{const R=window.location.hash;e(R)};return window.addEventListener("hashchange",I),()=>window.removeEventListener("hashchange",I)},[]),k==="design-system")return S.jsx(Lae,{});if(!d&&l===null&&!_){const I=f||"Could not load Rivet configuration.";return S.jsx("div",{className:"bg-main flex h-screen items-center justify-center px-6",children:S.jsxs("div",{className:"border-divider bg-main w-full max-w-md rounded-lg border p-6 text-center shadow-lg",children:[S.jsx("p",{className:"text-content text-sm font-medium",children:"We could not start Rivet yet."}),S.jsx("p",{className:"text-content-muted mt-2 text-xs",children:I}),S.jsx("button",{type:"button",className:"border-divider text-content hover:bg-main/80 mt-4 rounded-md border px-3 py-1.5 text-xs",onClick:()=>{C()},children:"Retry"})]})})}if(b)return S.jsx($se,{isSigningIn:v,onStartSignIn:()=>{m()},errorMessage:w,displayMode:"full"});const T=(l==null?void 0:l.agentModeAvailable)===!0&&i!==null,M=(l==null?void 0:l.agentModeAvailable)===!0&&n&&!r&&!T;return S.jsxs(S.Fragment,{children:[S.jsx(Dae,{projectPath:l==null?void 0:l.projectPath,libraryOrigin:(l==null?void 0:l.libraryOrigin)??null}),S.jsx(ax,{context:"onboarding",isOpen:M,onClose:()=>s(!0)}),S.jsx(ax,{context:"menu",isOpen:T,highlightProvider:i,onClose:()=>{window.sessionStorage.removeItem(Ix),o(null)}})]})};y7();const Vae=g.lazy(()=>h5(()=>import("./LibraryEntry-Cr4GFYXW.js"),[])),s6=window.location.pathname.startsWith("/rivet/library");s6||xU();const Hae=new Zz,zae=()=>S.jsx("div",{style:{display:"flex",height:"100vh",alignItems:"center",justifyContent:"center"},children:S.jsx("p",{style:{fontSize:"14px",color:"#6b7280"},children:"Something went wrong. Please reload the page."})}),MD=document.getElementById("root");if(!MD)throw new Error("Rivet root element is missing");const Uae=()=>PU.createRoot(MD).render(S.jsx(_e.StrictMode,{children:S.jsx(aU,{client:$e,children:S.jsx(hU,{fallback:S.jsx(zae,{}),children:S.jsx(wz,{client:Hae,children:S.jsx(bX,{defaultShape:"rounded",children:S.jsx(Joe,{defaultLibrary:"lucide",children:s6?S.jsx(g.Suspense,{fallback:S.jsx("div",{className:"bg-background h-screen"}),children:S.jsx(Vae,{})}):S.jsx(Fae,{})})})})})})})),Bae=async()=>{s6&&await fz(),await _z(),Uae()};Bae();export{rz as $,fv as A,Qi as B,hv as C,dv as D,pv as E,mv as F,gv as G,$t as H,Rr as I,Hse as J,np as K,Hoe as L,qR as M,kh as N,P3 as O,yS as P,Vz as Q,oh as R,Xh as S,uoe as T,cr as U,yn as V,Ke as W,Yoe as X,ob as Y,Ec as Z,wE as _,qz as a,Zae as a0,pX as a1,we as a2,iz as a3,Za as a4,rle as a5,sle as a6,hz as a7,$te as a8,Zt as a9,Qae as aa,Jae as ab,ioe as ac,kne as ad,MK as ae,Ote as af,Yae as ag,Kae as ah,qae as ai,G9 as aj,bt as ak,dz as al,uz as am,Gae as an,Yz as b,g as c,Xz as d,eU as e,Qz as f,Uz as g,Sh as h,es as i,tU as j,nU as k,Jz as l,tI as m,vr as n,ct as o,si as p,_9 as q,JR as r,Xy as s,S as t,YR as u,Nw as v,_S as w,wS as x,xS as y,Loe as z};
|
|
439
|
+
//# sourceMappingURL=main-tPO1OCpZ.js.map
|